Sie sind auf Seite 1von 393

INDEX

Sr. Company Nama


1 COGNZIANT
2 DELOITTE
3 GOOGLE
4 ABYETI TECHNOLOGIES
5 JK TECHNOSOFT
6 MICROSOFT
7 MICROSOFT TECHNICAL QUESTIONS
8 NINE LEAPS
9 WIPRO
10 HASHEDIN TECHNOLOGIES
11 MIND TREE
12 VIRTUSA (PE-2001)
13 PERSISTENT SYSTEM
14 WIPRO
15 VMWARE
16 INFORMATICA
17 FOURKITES
18 MU SIGMA
19 CLICK LABS PVT LTD
20 MICRO FOCUS PLACEMENT DRIVE
21 BA CONTINUUM
22 NEXT SCM
23 EPAM
24 BLUEPI
25 NEWGEN
26 CAPGEMINI
27 GRAY B
28 NIIT
29 AMAZON
30 SOFT PRODIGY
31 ZS ASSOCIATES
32 EVRY INDIA PVT. LTD.
33 MAVEN WAVE
33 JUST DIAL
34 BROADCOM
35 EVALUESERVE
36 SAPIENT
37 BRILLO TECHNOLOGIES
38 ORANGE BUSINESS SERVICE
39 EASTERN SOFTWARE
40 DE FACTO INFOTECH
Drive Name: COGNZIANT

Technical interview

1. Which is your favorite subject?


Student based Questions

2. What is OOPS? Give real life example?


Object-oriented programming (OOP) is a programming language model organized around objects rather than
"actions" and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input
data, processes it, and produces output data.

The programming challenge was seen as how to write the logic, not how to define the data. Object-oriented
programming takes the view that what we really care about are the objects we want to manipulate rather than the
logic required to manipulate them. Examples of objects range from human beings (described by name, address, and
so forth) to buildings and floors (whose properties can be described and managed) down to the little widgets on a
computer desktop (such as buttons and scroll bars).

The first step in OOP is to identify all the objects the programmer wants to manipulate and how they relate to each
other, an exercise often known as data modeling. Once an object has been identified, it is generalized as a class of
objects (think of Plato's concept of the "ideal" chair that stands for all chairs) which defines the kind of data it
contains and any logic sequences that can manipulate it. Each distinct logic sequence is known as a method. Objects
communicate with well-defined interfaces called messages.

The concepts and rules used in object-oriented programming provide these important benefits:

 The concept of a data class makes it possible to define subclasses of data objects that share some or all of the
main class characteristics. Called inheritance, this property of OOP forces a more thorough data analysis,
reduces development time, and ensures more accurate coding.

 Since a class defines only the data it needs to be concerned with, when an instance of that class (an object) is
run, the code will not be able to accidentally access other program data. This characteristic of data
hiding provides greater system security and avoids unintended data corruption.
 The definition of a class is reuseable not only by the program for which it is initially created but also by
other object-oriented programs (and, for this reason, can be more easily distributed for use in networks).

 The concept of data classes allows a programmer to create any new data type that is not already defined in
the language itself.

For example consider we have a Class of Cars under which Santro Xing, Alto and WagonR represents individual
objects. In this context each Car Object will have its own, Model,Year of Manufacture, Colour, Top Speed, Engine
Power etc.,which form Properties of the Car class and the associated actions i.e., object functions like Start, Move,
Stop form the Methods of Car class. No memory is allocated when a class is created. Memory is
allocated only when an object is created, i.e., when an instance of a class is created.

3. Concepts of OOPS?

Class
Here we can take Human Being as a class. A class is a blueprint for any functional entity which defines its
properties and its functions. Like Human Being, having body parts, and performing various actions.

Inheritance
Considering HumanBeing a class, which has properties like hands, legs, eyes etc, and functions like walk, talk, eat,
see etc. Male and Female are also classes, but most of the properties and functions are included in HumanBeing,
hence they can inherit everything from class HumanBeing using the concept of Inheritance.

Objects
My name is Abhishek, and I am an instance/object of class Male. When we say, Human Being, Male or Female, we
just mean a kind, you, your friend, me we are the forms of these classes. We have a physical existence while a class
is just a logical definition. We are the objects.

Abstraction
Abstraction means, showcasing only the required things to the outside world while hiding the details. Continuing our
example, Human Being's can talk, walk, hear, eat, but the details are hidden from the outside world. We can take
our skin as the Abstraction factor in our case, hiding the inside mechanism.

Encapsulation
This concept is a little tricky to explain with our example. Our Legs are binded to help us walk. Our hands, help us
hold things. This binding of the properties to functions is called Encapsulation.

Polymorphism
Polymorphism is a concept, which allows us to redefine the way something works, by either changing how it is done
or by changing the parts using which it is done. Both the ways have different terms for them.If we walk using our
hands, and not legs, here we will change the parts used to perform something. Hence this is called Overloading.And
if there is a defined way of walking, but I wish to walk differently, but using my legs, like everyone else. Then I can
walk like I want, this will be called as Overriding.

4. Abstraction and Inheritance?


Same as in Question Above. (Q.No 3 above)
5. Write any program.
Student based Questions
6. Explain any of the projects.
Student based Questions
7. Do you have any problem with relocation?
Not technical
Drive Name: DELOITTE

Technical Interview:
1. Tell me about yourself. (HR Question)
Ams: Depends upon Student.
2. What is the significance of OOPS? Give examples from real life.
Explanation: The main purpose of C++ programming is to add object orientation to the C programming
language and classes are the central feature of C++ that supports object-oriented programming and are
often called user-defined types.
A class is used to specify the form of an object and it combines data representation and methods for
manipulating that data into one neat package. The data and functions within a class are called members
of the class.
For example consider we have a Class of Cars under which Santro Xing, Alto and WaganR represents
individual Objects. In this context each Car Object will have its own, Model, Year of Manufacture, Color,
Top Speed, Engine Power etc., which form Properties of the Car class and the associated actions i.e., object
functions like Start, Move, Stop form the Methods of Car Class. No memory is allocated when a class is
created. Memory is allocated only when an object is created, i.e., when an instance of a class is created.

3. Pillars of OOPS.
Explanation: Object Oriented Programming is a paradigm that provides many concepts such as inheritance,
data binding, polymorphism etc.
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or
paradigm to design a program using classes and objects. It simplifies the software development and maintenance by
providing some concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike
etc. It can be physical and logical.
Class

Collection of objects is called class. It is a logical entity.


Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It
provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to convince the
customer differently, to draw something e.g. shape or rectangle etc.
In C++, we use Function overloading and Function overriding to achieve polymorphism.
Abstraction

Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't
know the internal processing.

In C++, we use abstract class and interface to achieve abstraction.


Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example:
capsule, it is wrapped with different medicines.

4. Abstraction. (Security in Java).


Explanation: Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery.

Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction

There are two ways to achieve abstraction in java

Abstract class (0 to 100%)


Interface (100%)
Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember

An abstract class must be declared with an abstract keyword.


It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors and static methods also.
It can have final methods which will force the subclass not to change the body of the method.
Java interface

There are mainly three reasons to use interface. They are given below.

It is used to achieve abstraction.


By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.

5. Encapsulation
Explanation: Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example
capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data
members are private here.

6. Polymorphism and its application in any of my projects .


Explanation: Polymorphism

If one task is performed by different ways, it is known as polymorphism. For example: to convince the
customer differently, to draw something, for example, shape, triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Application can be to speak something; Application, a cat speaks meow, dog barks woof, etc.

7. Tell me about 2 projects one was on Android and the other was a Data Analytics Project.

8. What is Operating system?


Explanation: An operating system (OS) is system software that manages computer hardware and software
resources and provides common services for computer programs.

Time-sharing operating systems schedule tasks for efficient use of the system and may also include
accounting software for cost allocation of processor time, mass storage, printing, and other resources.

For hardware functions such as input and output and memory allocation, the operating system acts as an
intermediary between programs and the computer hardware, although the application code is usually
executed directly by the hardware and frequently makes system calls to an OS function or is interrupted by
it. Operating systems are found on many devices that contain a computer – from cellular phones and video
game consoles to web servers and supercomputers.

9. How does a Java program works in accordance with the operating system?
Explanation: Java Program

Java, being a platform independent programming language, doesn’t work on one-step-compilation. Instead,
it involves a two-step execution, first through an OS independent compiler; and second, in a virtual machine
(JVM) which is custom-built for every operating system. The two principle stages are explained below:
Compilation

First, the source ‘.java’ file is passed through the compiler, which then encodes the source code into a
machine independent encoding, known as Bytecode. The content of each class contained in the source file is
stored in a separate ‘.class’ file. While converting the source code into the bytecode, the compiler follows the
following steps:

Parse: Reads a set of *.java source files and maps the resulting token sequence into AST (Abstract Syntax
Tree)-Nodes.
Enter: Enters symbols for the definitions into the symbol table.
Process annotations: If Requested, processes annotations found in the specifed compilation units.
Attribute: Attributes the Syntax trees. This step includes name resolution, type checking and constant
folding.
Flow: Performs dataflow analysis on the trees from the previous step. This includes checks for assignments
and reachability.
Desugar: Rewrites the AST and translates away some syntactic sugar.
Generate: Generates ‘.Class’ files.

Execution

The class files generated by the compiler are independent of the machine or the OS, which allows them to be
run on any system. To run, the main class file (the class that contains the method main) is passed to the JVM,
and then goes through three main stages before the final machine code is executed. These stages are:
Class Loader
The main class is loaded into the memory by passing its ‘.class’ file to the JVM, through invoking the latter.
All the other classes referenced in the program are loaded through the class loader.
A class loader, itself an object, creates a flat name space of class bodies that are referenced by a string
name.Bytecode Verifier
After the bytecode of a class is loaded by the class loader, it has to be inspected by the bytecode verifier,
whose job is to check that the instructions don’t perform damaging actions. The following are some of the
checks carried out:

Variables are initialized before they are used.


Method calls match the types of object references.
Rules for accessing private data and methods are not violated.
Local variable accesses fall within the runtime stack.
The run time stack does not overflow.

If any of the above checks fails, the verifier doesn’t allow the class to be loaded.
Just-In-Time Compiler
This is the final stage encountered by the java program, and its job is to convert the loaded bytecode into
machine code. When using a JIT compiler, the hardware can execute the native code, as opposed to having
the JVM interpret the same sequence of bytecode repeatedly and incurring the penalty of a relatively lengthy
translation process. This can lead to performance gains in the execution speed, unless methods are executed
less frequently.

10. What is Machine Learning? What are its types?


Explanation: Machine learning is an application of artificial intelligence (AI) that provides systems the
ability to automatically learn and improve from experience without being explicitly programmed. Machine
learning focuses on the development of computer programs that can access data and use it learn for
themselves.

The process of learning begins with observations or data, such as examples, direct experience, or instruction,
in order to look for patterns in data and make better decisions in the future based on the examples that we
provide. The primary aim is to allow the computers learn automatically without human intervention or
assistance and adjust actions accordingly.

Some machine learning methods

Machine learning algorithms are often categorized as supervised or unsupervised.

Supervised machine learning algorithms can apply what has been learned in the past to new data using
labeled examples to predict future events. Starting from the analysis of a known training dataset, the learning
algorithm produces an inferred function to make predictions about the output values. The system is able to
provide targets for any new input after sufficient training. The learning algorithm can also compare its output
with the correct, intended output and find errors in order to modify the model accordingly.

In contrast, unsupervised machine learning algorithms are used when the information used to train is neither
classified nor labeled. Unsupervised learning studies how systems can infer a function to describe a hidden
structure from unlabeled data. The system doesn’t figure out the right output, but it explores the data and can
draw inferences from datasets to describe hidden structures from unlabeled data.
Semi-supervised machine learning algorithms fall somewhere in between supervised and unsupervised
learning, since they use both labeled and unlabeled data for training – typically a small amount of labeled
data and a large amount of unlabeled data. The systems that use this method are able to considerably
improve learning accuracy. Usually, semi-supervised learning is chosen when the acquired labeled data
requires skilled and relevant resources in order to train it / learn from it. Otherwise, acquiringunlabeled data
generally doesn’t require additional resources.

Reinforcement machine learning algorithms is a learning method that interacts with its environment by
producing actions and discovers errors or rewards. Trial and error search and delayed reward are the most
relevant characteristics of reinforcement learning. This method allows machines and software agents to
automatically determine the ideal behavior within a specific context in order to maximize its performance.
Simple reward feedback is required for the agent to learn which action is best; this is known as the
reinforcement signal.

11. Tell me about your Management system project?


 Draw all the tables relations used in your project.
 What were the primary keys used or all other constraints in those relations?

12. Where do you see yourself in 7 years:


 As a Project Manager
 As a Developer
 As a Decision Analyst
 And why? Give reasons for no choosing other options?
Drive Name: Google
1. This type of cable is plugged into the network adapter and allows you to connect to a network.
A. HDMI B. Ethernet C. VGA D. Serial

Answer B

Explanation: Ethernet is a family of computer networking technologies commonly used in local area networks
(LAN), metropolitan area networks (MAN) and wide area networks (WAN). It was commercially introduced in
1980 and first standardized in 1983 as IEEE 802.3, and has since been refined to support higher bit rates and
longer link distances.

2. 802. 1x is….
A. The theoretical throughput speed of fast Ethernet
B. A networking standard used for authentication
C. The latest Ubuntu release build number
D. The max distance Category 5 Ethernet data can travel before degradation

Answer B

Explanation: IEEE 802.1X is an IEEE Standard for port-based Network Access Control (PNAC). It is part of the
IEEE 802.1 group of networking protocols. It provides an authentication mechanism to devices wishing to attach
to a LAN or WLAN.

3. What Windows utility allows you to view running processes?


A. Process viewer B. Activity Monitor C. Registry D. Task Manager
Answer D

Explanation: Task Manager, previously known as Windows Task Manager, is a task manager, system monitor,
and startup manager included with Microsoft Windows systems. It provides information about computer
performance and running software, including name of running processes, CPU load, commit charge, I/O details,
logged-in users, and Windows services. Task Manager can also be used to set process priorities, processor
affinity, start and stop services, and forcibly terminate processes.

4. Asmall, self-contained network is generally called a _________


A. LAN B. WAN C. MAN D. STAN
Answer A

Explanation: A local area network (LAN) is a group of computers and associated devices that share a common
communications line or wireless link to a server. Typically, a LAN encompasses computers and peripherals
connected to a server within a distinct geographic area such as an office or a commercial establishment.

5. This is an example of an IANA reserved private IP address.


A. 168.192.23.5
B. 16.172.12.99
C. 12.10.10.1
D. 192.168.15.12

Answer D

Explanation: Several address ranges are reserved for "Special Use". These addresses all have restrictions of some
sort placed on their use, and in general should not appear in normal use on the public Internet. The overview
below briefly explains the purpose of these addresses – in general they are used in specialized technical contexts.
They are described in more detail in RFC 6890.

"Private Use" IP addresses:

10.0.0.0 - 10.255.255.255
172.16.0.0 - 172.31.255.255
192.168.0.0 - 192.168.255.255

These address blocks are reserved for use on private networks, and should never appear in the public Internet.
There are millions of private networks (for example home firewalls often use them). People can use these
address blocks without informing us, so we have no record of who uses which of these addresses.

The point of private address space is to allow many organizations in different places to use the same addresses,
and as long as these disconnected or self-contained islands of IP-speaking computers (private networks) are not
connected, there is no problem. If you see an apparent attack, or spam, coming from one of these address ranges,
then either it is coming from your local environment, your ISP, or the address has been "spoofed".

The Private addresses are documented in RFC 1918. If you have further questions about RFC 1918 usage, please
contact your ISP.
"Autoconfiguration" IP Addresses:

169.254.0.0 - 169.254.255.255

Addresses in the range 169.254.0.0 to 169.254.255.255 are used automatically by most network devices when
they are configured to use IP, do not have a static IP Address assigned and are unable to obtain an IP address
using DHCP.

This traffic is intended to be confined to the local network, so the administrator of the local network should look
for misconfigured hosts. Some ISPs inadvertently also permit this traffic, so you may also want to contact your
ISP. This is documented in RFC 6890.
"Loopback" IP addresses:

127.0.0.0 - 127.255.255.255

Each computer on the Internet uses 127.0.0.0/8 to identify itself, to itself. 127.0.0.0 to 127.255.255.255 is
earmarked for what is called "loopback". This construct allows a computer to confirm that it can use IP and for
different programs running on the same machine to communicate with each other using IP. Most software only
uses 127.0.0.1 for loopback purposes (the other addresses in this range are seldom used). All of the addresses
within the loopback address are treated with the same levels of restriction in Internet routing, so it is difficult to
use any other addresses within this block for anything other than node specific applications, generally
bootstraping. This is documented in RFC 6890.
"Unallocated" IP addresses:

The IPv4 Address Registry and the Whois use the word unallocated (sometimes "reserved") to mean that the
addresses are reserved for future allocation. No one should be using these addresses now. These addresses will
be assigned for use in the public Internet in the future. If addresses are needed for private networks then the
private-use addresses mentioned above should be used.
Multicast IP addresses:

224.0.0.0 - 239.255.255.255

Addresses in the range 224.0.0.0 to 239.255.255.255 are set aside for the special purpose of providing multicast
services in the Internet. Multicast services allow a computer to send a single message to many destinations.
Examples include the software that keeps computers’ clocks synchronised and television services delivered over
IP, typically by cable ISPs. Various addresses in this range are used by routers and others are used by hosts that
are listening to multicast sessions.

6. Many versions of linux use this kind of licensing, which means the source code is made freely available and can
be redistributed or modified.
A. open source B. free C. pirated D. public domain

Answer A

Explanation: Open-source software (OSS) is a type of computer software in which source code is released
under a license in which the copyright holder grants users the rights to study, change, and distribute the
software to anyone and for any purpose. Open-source software may be developed in a collaborative public
manner. According to scientists who have studied it, open-source software is a prominent example of open
collaboration. The term is often written without a hyphen as "open source software".

7. This is a collection of databases of configurations in Windows operating systems.


A. Registry B. Config database C. Sys Files D. Task Manager

Answer A

Explanation: The Windows Registry is a hierarchical database that stores low-level settings for the
Microsoft Windows operating system and for applications that opt to use the registry. The kernel, device
drivers, services, Security Accounts Manager, and user interface can all use the registry. The registry also
allows access to counters for profiling system performance.

In simple terms, the registry or Windows Registry contains information, settings, options, and other
values for programs and hardware installed on all versions of Microsoft Windows operating systems. For
example, when a program is installed, a new subkey containing settings such as a program's location, its
version, and how to start the program, are all added to the Windows Registry.
8. This command line utility in Windows will display the network address and related information.
A. ipconfig B. show network C. ifconfig D. view-ip

Answer A
Explanation: Displays all current TCP/IP network configuration values and refreshes Dynamic Host
Configuration Protocol (DHCP) and Domain Name System (DNS) settings. Used without parameters, ipconfig
displays Internet Protocol version 4 (IPv4) and IPv6 addresses, subnet mask, and default gateway for all
adapters.

9. This IP address is called a “loopback” address.


A. 192.168.1.1 B. 255.255.255.254
C. 169.168.1.1 D. 127.0.0.1

Answer D

Explanation: Loopback address is a special IP number (127.0.0.1) that is designated for the software loopback
interface of a machine. The loopback interface has no hardware associated with it, and it is not physically
connected to a network.

10. This is a system used to automatically assign IP addresses on a network.


A. IP-Auto B. DNS C. CUPS D. DHCP
Answer D

Explanation: Dynamic Host Configuration Protocol (DHCP) is a client/server protocol that automatically
provides an Internet Protocol (IP) host with its IP address and other related configuration information such as the
subnet mask and default gateway.

11. What Unix-based Mac command line utility can be used to query a machine’s IP address?
A. view-ip B. ifconfig C. ipconfig D. show network
Answer C
Explanation: Displays all current TCP/IP network configuration values and refreshes Dynamic Host
Configuration Protocol (DHCP) and Domain Name System (DNS) settings. Used without parameters, ipconfig
displays Internet Protocol version 4 (IPv4) and IPv6 addresses, subnet mask, and default gateway for all
adapters.

12. This linux user account is similar to an administrative account on windows and has default access to all files and
commands.
A. admin B. root C. superuser D. default

Answer B
Explanation: Root is the user name or account that by default has access to all commands and files on a Linux or
other Unix-like operating system. It is also referred to as the root account, root user and the superuser.

13. The ‘brains’ of a computer is normally referred to as this.


A. DHCP B. CPU C. BIOS D. RAM

Answer: B
Explanation: CPU is the abbreviation for central processing unit. Sometimes referred to simply as the central
processor, but more commonly called processor, the CPU is the brains of the computer where most calculations
take place.

14. What protocol is used to transmit web pages over the internet?
A. WWW B. HTTP C. SSH D. FTP

Answer B
Explanation: HTTP is based on the TCP/IP protocols, and is used commonly on the Internet for transmitting
web-pages from servers to browsers.

15. Where can you view system logs in Windows?


A. Event Viewer B. Log Reader
C. Registry D. Add/Remove Programs

Answer: A
Explanation: Event Viewer is a component of Microsoft's Windows NT line of operating systems that lets
administrators and users view the event logs on a local or remote machine.
16. What is the name of the Mac command line environment?
A. Terminal B. Command Interface
C. Command Prompt D. Console

Answer: A
Explanation: Terminal provides a command line interface to control the UNIX-based operating system that lurks
below macOS (or Mac OS X).

17. This refers to the broadcasted name of a wireless network:


A. DHCP B. SSID C. Net ID D. DNS

Answer B
Explanation: A service set identifier (SSID) is a sequence of characters that uniquely names a wireless local area
network (WLAN). An SSID is sometimes referred to as a "network name."

18. Peripherals such as keyboards and mice are connected through this prost.
A. PCI B. HDMI C. Ethernet D. USB

Answer D
Explanation: USB (abbreviation of Universal Serial Bus) is an industry standard that establishes specifications
for cables, connectors and protocols for connection, communication and power supply between personal
computers and their peripheral devices.

19. You can enter Windows Safe Mode by hitting which key(s) during the boot up sequence.
A. Enter B. F8 C. F10 D. Ctrl + Alt + Del
Answer B
Explanation: The F8 key is called a function key. This key is usually used to enter the Windows Startup menu or
the Advanced Boot Options.

20. This software built-in to a motherboard allows you to select the boot up device along with other hardware
configuration options.
A. POST B. BIOS C. RAM D. HDD

Answer B
Explanation: BIOS (basic input/output system) is the program a personal computer's microprocessor uses to get
the computer system started after you turn it on. It also manages data flow between the computer's operating
system and attached devices such as the hard disk, video adapter, keyboard, mouse and printer.

21. The unique hardware id which is used to identify each device on a network is more commonly called….
A. SSID B. NIC C. IP Address D. Mac Address
Answer C
Explanation: An Internet Protocol address (IP address) is a numerical label assigned to each device connected to
a computer network that uses the Internet Protocol for communication. An IP address serves two principal
functions: host or network interface identification and location addressing.

22. When a PC is powered on, it uses this process to test hardware functionality.
A. BIOS B. Boot loader C. Hardware Self-Test D. POST
Answer D
Explanation: POST (Power-On Self-Test) is the diagnostic testing sequence that a computer's basic input/output
system (or "starting program") runs to determine if the computer keyboard, random access memory, disk drives,
and other hardware are working correctly.

If the necessary hardware is detected and found to be operating properly, the computer begins to boot. If the
hardware is not detected or is found not to be operating properly, the BIOS issues an error message which may
be text on the display screen and/or a series of coded beeps, depending on the nature of the problem. Since POST
runs before the computer's video card is activated, it may not be possible to progress to the display screen. The
pattern of beeps may be a variable numbers of short beeps or a mixture of long and short beeps, depending on
what type of BIOS is installed.

23. Which of this is a type of volatile memory?


A. CMOS B. RAM C. ROM D. BIOS

Answer B
Explanation: Random-access memory (RAM) is a form of computer data storage that stores data and machine
code currently being used. A random-access memory device allows data items to be read or written in almost the
same amount of time irrespective of the physical location of data inside the memory.

24. This is considered the central module of the Linux operating system that connects hardware to software.
A. run level B.kernel C. root D. CPU
Answer B
Explanation: A kernel is the central part of an operating system. It manages the operations of the computer and
the hardware - most notably memory and CPU time. There are two types of kernels: A micro kernel, which only
contains basic functionality; A monolithic kernel, which contains many device drivers.

25. This file format is a mountable disk image commonly used to install applications in OSX.
A. plist B. dmg C. exe D. dll
Answer B
Explanation: A DMG file is a mountable disk image created in Mac OS X. It contains raw block data typically
compressed and sometimes encrypted. DMG files are commonly used for OS X software installers that are
downloaded from the Internet and mounts a virtual disk on the desktop when opened.

26. The IP address, 192.168.1.105, is in which class?


A. Class D B. Class A C. Class C D. Class B

Answer C
Explanation: The first octet of Class C IP address has its first 3 bits set to 110, that is: Class C IP addresses range
from 192.0.0.x to 223.255.255.x. The default subnet mask for Class C is 255.255.255.x. Class C gives 2097152
(221) Network addresses and 254 (28-2) Host addresses.

27. This protocol is connectionless and is commonly used to transmit voice and video data over the internet.
A. FTP B. TCP C. UDP D. APB

Answer C
Explanation: UDP (User Datagram Protocol) is an alternative communications protocol to Transmission Control
Protocol (TCP) used primarily for establishing low-latency and loss-tolerating connections between applications
on the internet.

28. This piece of software, embedded in a chip on the motherboard, allows you to select boot up devices in addition
to other configuration options:
A. BIOS B. RAM C. Configurator D. Ssd

Answer A
Explanation: BIOS (basic input/output system) is the program a personal computer's microprocessor uses to get
the computer system started after you turn it on. It also manages data flow between the computer's operating
system and attached devices such as the hard disk, video adapter, keyboard, mouse and printer.

29. Per second, what is the theoretical maximum speed rating of a Gigabit Ethernet connection?
A. 1000 Gigabits B. 2000 Megabits
C. 1000 Megabits D. 1000 Megabytes

Answer C
Explanation: The Gigabit Ethernet standard supports a theoretical maximum data rate of 1 gigabit per second
(Gbps) (1000 Mbps). When first developed, some thought achieving gigabit speeds with Ethernet would require
using fiber optic or other special network cable technology. However, that's only necessary for long distances.

30. This Windows utility allows you install or uninstall applications.


A. Add/Remove Programs
B. Device Manager
C. Windows Application Installer
D. Task Manager

Answer A
Explanation: In the Control Panel you can quickly access the old Add or Remove Programs by clicking or
tapping the "Uninstall a program" link found in the Programs section.

31. This is a network utility used to test connectivity to another device on the network.
A. nslookup B. nslookup C. ping D. ipconfig

Answer C
Explanation: Ping is a networking utility program or a tool to test if a particular host is reachable. It is a
diagnostic that checks if your computer is connected to a server. Ping, a term taken from the echo location of a
submarine, sends data packet to a server and if it receives a data packet back, then you have a connection.

32. This is an encryption method commonly used in wireless networks.


A. WPA2 B. WAMS C. DHCP D. Wifi-Strong

Answer A
Explanation: WPA2 is a type of encryption used to secure the vast majority of Wi-Fi networks. A WPA2
network provides unique encryption keys for each wireless client that connects to it.

33. This is a security application in Windows that allows you to filter incoming and outgoing network data.
A. Windows Shield B. Windows Anti-Virus
C. Windows Blocker D. Windows Firewall
Answer D
Explanation: The Windows Firewall is a security application created by Microsoft and built into Windows,
designed to filter network data transmissions to and from your Windows system and block harmful
communications and/or the programs that are initiating them.

34. This utility can be used to check log messages in OSX.


A. Console B. Logger
C. Message Viewer D. Event Log

Answer A
Explanation: Alternatively referred to as a computer console, root console, system console, or terminal. Console
is a basic computer or monitor and keyboard that is connected to another computer, server, or a mainframe over
a network. It is used to maintain or monitor the status of the network or computer.

35. Which one of these is not a result of the command ‘ipconfig /all’
A. DNS Servers B. Default Gateway
C. DHCP Server D. Physical Address

Answer D
Explanation: A physical address is a binarynumber in the form of logical high and low states on an address
busthat corresponds to a particular cell of primary storage(also called main memory), or to a particular register in
a memory-mapped I/O(input/output) device.

36. Which of the following is NOT a Linux distribution?


A. Derpian B. Fedora C. CentOS D. openSUSE
Answer A
Explanation: A Linux distribution (often abbreviated as distro) is an operating system made from a software
collection, which is based upon the Linux kernel and, often, a package management system.

37. Which of these is a type of hard drive?


A.SSD B. LCD C. FTP D. SSH
Answer A
Explanation: An SSD (solid-state drive) is a type of nonvolatile storage media that stores persistent data on solid-
state flash memory.The architectural configuration of the SSD controller is optimized to deliver high read and
write performance for both sequential and random data requests.

38. What does the acronym RAM stand for?


A. Router Access Machine B. Router Access Memory
C. Random-Access Memory D. Read-only Access Memory

Answer C
Explanation: Random-access memory (RAM) is a form of computer data storage that stores data and machine
code currently being used. A random-access memory device allows data items to be read or written in almost the
same amount of time irrespective of the physical location of data inside the memory.

39. This networking service translates web domains to IP addresses.


A. DNS B. DHCP C. WINS D. HTTP

Answer A
Explanation: The Domain Name System (DNS) is the phonebook of the Internet. Humans access information
online through domain names, like nytimes.com or espn.com. Web browsers interact through Internet Protocol
(IP) addresses. DNS translates domain names to IP addresses so browsers can load Internet resources.

40. What Windows utility allows you to configure hardware devices?


A. Event Viewer B. Device Manager
C. Drive installer D. Hardware Manger

Answer B
Explanation: Device Manager is a Control Panel applet in Microsoft Windows operating systems. It allows users
to view and control the hardware attached to the computer. When a piece of hardware is not working, the
offending hardware is highlighted for the user to deal with. The list of hardware can be sorted by various criteria.
Drive Name: Abyeti Technologies
Book Index: 61-(B)

TECHNICA L CODING TEST

1. An array of input is given with negative as well as positive values. Sort them using Stacks only. You can
use as many of stacks you want but no array. Print the final Output of sorted input.

// Function to Rearrange positive and negative


// numbers in a array
void RearrangePosNeg(int arr[], int n)
{
int key, j;
for(int i = 1; i < n; i++)
{
key = arr[i];

// if current element is positive


// do nothing
if (key > 0)
continue;

/* if current element is negative,


shift positive elements of arr[0..i-1],
to one position to their right */
j = i - 1;
while (j >= 0 && arr[j] > 0)
{
arr[j + 1] = arr[j];
j = j - 1;
}

// Put negative element at its right position


arr[j + 1] = key;
}
}

2. Problem:
1. Print a specific pattern

int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
cout<<”*”;
}
cout<<”\n”;
}
2. Given 2 numbers (where 6 can also be written as 5, and 5 as 6), calculate the maximum and minimum
possible sum

int replaceDig(int x, int from, int to)

{
int result = 0;
int multiply = 1;

while (x % 10 > 0)
{
int reminder = x % 10;

// Required digit found, replace it


if (reminder == from)
result = result + to * multiply;

else
result = result + reminder * multiply;

multiply *= 10;
x = x / 10;
}
return result;
}

// Returns maximum and minimum possible sums of


// x1 and x2 if digit replacements are allowed.
void calculateMinMaxSum(int x1, int x2)
{
// We always get minimum sum if we replace
// 6 with 5.
int minSum = replaceDig(x1, 6, 5) +
replaceDig(x2, 6, 5);

// We always get maximum sum if we replace


// 5 with 6.
int maxSum = replaceDig(x1, 5, 6) +
replaceDig(x2, 5, 6);
cout << "Minimum sum = " << minSum;
cout << "nMaximum sum = " << maxSum;
}

3. Find sum of all values of (a[j]-a[i]) where j>i and j-i is a prime.
int maxIndexDiff(int arr[], int n)
{
int maxDiff = -1;
int i, j;

for (i = 0; i < n; ++i)


{
for (j = n-1; j > i; --j)
{
if(arr[j] > arr[i] && maxDiff < (j - i))
maxDiff = j - i;
}
}

return maxDiff;
}

int main()
{
int arr[] = {9, 2, 3, 4, 5, 6, 7, 8, 18, 0};
int n = sizeof(arr)/sizeof(arr[0]);
int maxDiff = maxIndexDiff(arr, n);
printf("\n %d", maxDiff);
getchar();
return 0;
}

3. Problem
Knight and Queen Problem it is famous DP problem .

#include<stdio.h>

#define N 8

int solveKTUtil(int x, int y, int movei, int sol[N][N],


int xMove[], int yMove[]);

/* A utility function to check if i,j are valid indexes


for N*N chessboard */
bool isSafe(int x, int y, int sol[N][N])
{
return ( x >= 0 && x < N && y >= 0 &&
y < N && sol[x][y] == -1);
}

/* A utility function to print solution matrix sol[N][N] */


void printSolution(int sol[N][N])
{
for (int x = 0; x < N; x++)
{
for (int y = 0; y < N; y++)
printf(" %2d ", sol[x][y]);
printf("\n");
}
}

/* This function solves the Knight Tour problem using


Backtracking. This function mainly uses solveKTUtil()
to solve the problem. It returns false if no complete
tour is possible, otherwise return true and prints the
tour.
Please note that there may be more than one solutions,
this function prints one of the feasible solutions. */
bool solveKT()
{
int sol[N][N];

/* Initialization of solution matrix */


for (int x = 0; x < N; x++)
for (int y = 0; y < N; y++)
sol[x][y] = -1;

/* xMove[] and yMove[] define next move of Knight.


xMove[] is for next value of x coordinate
yMove[] is for next value of y coordinate */
int xMove[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
int yMove[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };

// Since the Knight is initially at the first block


sol[0][0] = 0;

/* Start from 0,0 and explore all tours using


solveKTUtil() */
if (solveKTUtil(0, 0, 1, sol, xMove, yMove) == false)
{
printf("Solution does not exist");
return false;
}
else
printSolution(sol);

return true;
}

/* A recursive utility function to solve Knight Tour


problem */
int solveKTUtil(int x, int y, int movei, int sol[N][N],
int xMove[N], int yMove[N])
{
int k, next_x, next_y;
if (movei == N*N)
return true;

/* Try all next moves from the current coordinate x, y */


for (k = 0; k < 8; k++)
{
next_x = x + xMove[k];
next_y = y + yMove[k];
if (isSafe(next_x, next_y, sol))
{
sol[next_x][next_y] = movei;
if (solveKTUtil(next_x, next_y, movei+1, sol,
xMove, yMove) == true)
return true;
else
sol[next_x][next_y] = -1;// backtracking
}
}

return false;
}
/* Driver program to test above functions */
int main()
{
solveKT();
return 0;
}
TECHNICAL INTERVIEW
1. 8 ball puzzle

proc weight n {
set num [expr {int(log($n*2-1)/log(3))+1}]
set len [expr {$n/3}]
set pn 0
set pri {2 5 7 11 13 17 19 23 29 31 37 41 43 59 61 67}
for {set i 0} {$i < $num} {incr i} {
set a {}
while {![llength $a]} {
set a {}
set b {}
set c {}
while {
($n+1)%[lindex $pri $pn]==0
||($n-1)%[lindex $pri $pn]==0
||$n%[lindex $pri $pn]==0} {incr pn; puts $pn}
set cpn [lindex $pri $pn]
for {set j 0} {$j < $len} {incr j} {
set tmp [expr {($j*$cpn)%$n}]
lappend a $tmp
incr tmp 1
if {$tmp in $a} {set a {}; break}
lappend b $tmp
}
incr pn
}
for {set j 0} {$j < $n} {incr j} {
if {$j ni $a && $j ni $b} {lappend c $j}
}
puts "[lsort -integer $a] VS [lsort -integer $b] - Which is havier? -1 = left,
0 = equal, 1 = right"
set idx [expr {[gets stdin] + 1}]
if {$i == 0} {
if {$idx == 1} {
set p1 $c
set p2 $c
} elseif {$idx == 0} {
set p1 $a
set p2 $b
} else {
set p1 $b
set p2 $a
}
} else {
set lists [list $a $c $b]
set p1 [lmap it [lindex $lists $idx] {if {$it ni $p1} continue; set it}]
set p2 [lmap it [lindex $lists 2-$idx] {if {$it ni $p2} continue; set it}]
}
}
if {[llength $p1]} {puts "Result $p1"} {puts "Result $p2"}
}
puts "Number of balls?"
weight [gets stdin]

2. 2.5 ltr 3ltr jar puzzle

Similar solution(Exactly not found)

Using a 3L and a 5L bottle, an exact quantity of 4L can be taken out of an unknown water source.
Let us denote 3L bottle the first bottle and 5L bottle the second one. The steps are as follows:

 Fill the second bottle from the source.


 Fill the first bottle using the water from second bottle.
 Now we have 3L water in first bottle and 2L in the second bottle.
 Empty the first bottle in the source.
 Now the first bottle is empty and 2L in second bottle.
 Now empty the second bottle in the first bottle.
 Now the first bottle has 2L quantity and the second bottle is empty.
 Now fill the second bottle from the source.
 At this instance the first bottle has 2L quantity and 5L in second bottle.
 Now empty 1L from second bottle in the first bottle, as it has a 3L capacity so only 1L
more water can be accommodated.
 At this point the first bottle is full and 4L in the second bottle.

Hence we have 4L water (desired quantity) in the second bottle.

3. A company has employees. An employee can also be a manager. Let A, B, C, D, E, F, G are employees
such that A is manager for B,C,D and B is manager for E,F,G. Design database to store the given
information. Write a query to retrieve the names of employees working under any manager.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NumberEmployeeUnderManager


{
// A hashmap to store result. It stores count of employees
// under every employee, the count may by 0 also
static Map<String,Integer> result =
new HashMap<String, Integer>();

// Driver function
public static void main(String[] args)
{
Map<String, String> dataSet = new HashMap<String, String>();
dataSet.put("A", "C");
dataSet.put("B", "C");
dataSet.put("C", "F");
dataSet.put("D", "E");
dataSet.put("E", "F");
dataSet.put("F", "F");

populateResult(dataSet);
System.out.println("result = " + result);
}

// This function populates 'result' for given input 'dataset'


private static void populateResult(Map<String, String> dataSet)
{
// To store reverse of original map, each key will have 0
// to multiple values
Map<String, List<String>> mngrEmpMap =
new HashMap<String, List<String>>();

// To fill mngrEmpMap, iterate through the given map


for (Map.Entry<String,String> entry: dataSet.entrySet())
{
String emp = entry.getKey();
String mngr = entry.getValue();
if (!emp.equals(mngr)) // excluding emp-emp entry
{
// Get the previous list of direct reports under
// current 'mgr' and add the current 'emp' to the list
List<String> directReportList = mngrEmpMap.get(mngr);

// If 'emp' is the first employee under 'mgr'


if (directReportList == null)
directReportList = new ArrayList<String>();

directReportList.add(emp);

// Replace old value for 'mgr' with new


// directReportList
mngrEmpMap.put(mngr, directReportList);
}
}

// Now use manager-Emp map built above to populate result


// with use of populateResultUtil()

// note- we are iterating over original emp-manager map and


// will use mngr-emp map in helper to get the count
for (String mngr: dataSet.keySet())
populateResultUtil(mngr, mngrEmpMap);
}

// This is a recursive function to fill count for 'mgr' using


// mngrEmpMap. This function uses memoization to avoid re-
// computations of subproblems.
private static int populateResultUtil(String mngr,
Map<String, List<String>> mngrEmpMap)
{
int count = 0;

// means employee is not a manager of any other employee


if (!mngrEmpMap.containsKey(mngr))
{
result.put(mngr, 0);
return 0;
}

// this employee count has already been done by this


// method, so avoid re-computation
else if (result.containsKey(mngr))
count = result.get(mngr);

else
{
List<String> directReportEmpList = mngrEmpMap.get(mngr);
count = directReportEmpList.size();
for (String directReportEmp: directReportEmpList)
count += populateResultUtil(directReportEmp, mngrEmpMap);

result.put(mngr, count);
}
return count;
}
}

4. How so you check if a tree is a BST? What if the definition of this tree is altered a little.

int isBST(struct node* node)


{
if (node == NULL)
return 1;

/* false if left is > than node */


if (node->left != NULL && node->left->data > node->data)
return 0;

/* false if right is < than node */


if (node->right != NULL && node->right->data < node->data)
return 0;

/* false if, recursively, the left or right is not a BST */


if (!isBST(node->left) || !isBST(node->right))
return 0;

/* passing all that, it's a BST */


return 1;
}

5. Data Structure and N-ary tree implementation


A binary tree is a structure comprising nodes, where each node has the following 3 components:

1. Data element: Stores any kind of data in the node


2. Left pointer: Points to the tree on the left side of node
3. Right pointer: Points to the tree on the right side of the node

As the name suggests, the data element stores any kind of data in the node.
The left and right pointers point to binary trees on the left and right side of the node respectively.

If a tree is empty, it is represented by a null pointer.

The following image explains the various components of a tree.

Commonly-used terminologies

 Root: Top node in a tree


 Child: Nodes that are next to each other and connected downwards
 Parent: Converse notion of child
 Siblings: Nodes with the same parent
 Descendant: Node reachable by repeated proceeding from parent to child
 Ancestor: Node reachable by repeated proceeding from child to parent.
 Leaf: Node with no children
 Internal node: Node with at least one child
 External node: Node with no children

Structure code of a tree node

In programming, trees are declared as follows:


struct node
{
int data; //Data element
struct node * left; //Pointer to left node
struct node * right; //Pointer to right node
};

Creating nodes

Simple node

struct node root;

Pointer to a node

struct node * root;


root=(node * )malloc(sizeof(node));

In this case, you must explicitly allocate the memory of the node type to the pointer (preferred method).

Utility function returning node

struct node * newnode(int element)


{
struct node * temp=(node * )malloc(sizeof(node));
temp->data=element;
temp->left=temp->right=NULL;
return temp;
}

Maximum depth/height of a tree

The idea is to do a post-order traversal and maintain two variables to store the left depth and right depth and
return max of both the depths.

int maxDepth(struct node* node)


{
if (node==NULL)
return 0;
else
{
/* compute the depth of each subtree */
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);

/* use the larger one */


if (lDepth > rDepth)
return(lDepth+1);
else
return(rDepth+1);
}
}

Time complexity

O(n)

Application of trees

1. a Manipulate hierarchical data


2. Make information easy to search (see tree traversal)
3. Manipulate sorted lists of data
4. Use as a workflow for compositing digital images for visual effects
5. Use in router algorithms

6. String manipulation

A string is a sequence of characters. In other words, a string is an array of character data type. An instance of a
string is called a string literal. For instance in C++: string s = "HackerEarth"; s is a string literal.

String Manipulation is a class of problems where a user is asked to process a given string and use/change its
data. An example question would be a great way to understand the problems that are usually classified under
this category.

 Given a string S of length N, shift each character of the string by K positions to the right, where K≤N.

For example: Say S = "hacker" and K=2. Here N=6.


Shifting each character in S by 2 positions to the right would result into erhack.
Note that S[0] i.e. 'h' is moved by 2 positions to the S[2]. Also, S[5] i.e. 'r', which is the last character in S comes
round-about back to S[1] as there is no space for 'r' to go beyond the limits of string length.

Approach:

 Declare another auxillary string shiftedS that is of the same size as S.


 Copy ith element of S to the (K+i)th position in shiftedS. This means, shiftedS[i+K]=S[i] where 0≤i<N.
 Make sure that i+K never exceeds N, because that will try to access a memory location which is not
declared in shiftedS. There's a simple trick to ensure that - use (i+K)modN .

Implementation:

void shiftByK(char S[], char shiftedS[], int N, int K) {


// Iterate through the length of given string
for(int i=0; i<N; i++) {
// Find the index for this current character in shiftedS[]
int idx = (i+K) % N;
// Copy that character at the found index idx
shiftedS[idx] = S[i];
}
// Add a NULL character to mark the end of string
shiftedS[N] = '\0';
}

Every character array in C/C++ ends with a '\0' (NULL) character. It marks the end of the string. If it is not
added in the end, then the code may produce garbage characters after the string.

7. Binary tree mirror image

The idea is to write a recursive function isMirror() that takes two trees as argument and returns true if trees
are mirror and false if trees are not mirror. The isMirror() function recursively checks two roots and
subtrees under the root.
Below is implementation of above algorithm.
// C++ program to check if a given Binary Tree is symmetric or not
#include<bits/stdc++.h>
using namespace std;

// A Binary Tree Node


struct Node
{
int key;
struct Node* left, *right;
};

// Utility function to create new Node


Node *newNode(int key)
{
Node *temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}

// Returns true if trees with roots as root1 and root2 are mirror
bool isMirror(struct Node *root1, struct Node *root2)
{
// If both trees are emptu, then they are mirror images
if (root1 == NULL && root2 == NULL)
return true;

// For two trees to be mirror images, the following three


// conditions must be true
// 1 - Their root node's key must be same
// 2 - left subtree of left tree and right subtree
// of right tree have to be mirror images
// 3 - right subtree of left tree and left subtree
// of right tree have to be mirror images
if (root1 && root2 && root1->key == root2->key)
return isMirror(root1->left, root2->right) &&
isMirror(root1->right, root2->left);
// if neither of above conditions is true then root1
// and root2 are not mirror images
return false;
}

// Returns true if a tree is symmetric i.e. mirror image of itself


bool isSymmetric(struct Node* root)
{
// Check if tre is mirror of itself
return isMirror(root, root);
}

// Driver program
int main()
{
// Let us construct the Tree shown in the above figure
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(4);
root->right->right = newNode(3);

cout << isSymmetric(root);


return 0;
}

8. Multithreading
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program
for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-
weight processes within a process.

Threads can be created by using two mechanisms :


1. Extending the Thread class
2. Implementing the Runnable Interface

Thread creation by extending the Thread class

We create a class that extends the java.lang.Thread class. This class overrides the run() method
available in the Thread class. A thread begins its life inside run() method. We create an object of our
new class and call start() method to start the execution of a thread. Start() invokes the run() method
on the Thread object.

class MultithreadingDemo extends Thread


{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println ("Thread " +
Thread.currentThread().getId() +
" is running");

}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}

// Main Class
public class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}

9. Exception Handling

Exception handling is the process of responding to the occurrence, during computation, of exceptions –
anomalous or exceptional conditions requiring special processing – often changing the normal flow
of program execution. It is provided by specialized programming language constructs, computer
hardware mechanisms like interrupts or operating system IPC facilities like signals.
In general, an exception breaks the normal flow of execution and executes a pre-registered exception handler.
The details of how this is done depends on whether it is a hardware or software exception and how the
software exception is implemented. Some exceptions, especially hardware ones, may be handled so gracefully
that execution can resume where it was interrupted.
Alternative approaches to exception handling in software are error checking, which maintains normal program
flow with later explicit checks for contingencies reported using special return values or some auxiliary global
variable such as C's errno or floating point status flags; or input validation to preemptively filter exceptional
cases.
A different view of exceptions is based on the principles of design by contract and is supported in particular by
the Eiffel language. The idea is to provide a more rigorous basis for exception handling by defining precisely
what is "normal" and "abnormal" behavior. Specifically, the approach is based on two concepts:

 Failure: the inability of an operation to fulfill its contract. For example, an addition may produce an
arithmetic overflow (it does not fulfill its contract of computing a good approximation to the mathematical
sum); or a routine may fail to meet its postcondition.
 Exception: an abnormal event occurring during the execution of a routine (that routine is the "recipient"
of the exception) during its execution. Such an abnormal event results from the failure of an operation
called by the routine.
The "Safe Exception Handling principle" as introduced by Bertrand Meyer in Object-Oriented Software
Construction then holds that there are only two meaningful ways a routine can react when an exception occurs:

 Failure, or "organized panic": The routine fixes the object's state by re-establishing the invariant (this is
the "organized" part), and then fails (panics), triggering an exception in its caller (so that the abnormal
event is not ignored).
 Retry: The routine tries the algorithm again, usually after changing some values so that the next
attempt will have a better chance to succeed.

10.Oops concepts

OOPS Concept Definitions


Now, let us discuss some of the main features of Object Oriented Programming which you will be using in C++
(technically).

1. Objects

2. Classes

3. Abstraction

4. Encapsulation

5. Inheritance

6. Overloading

7. Exception Handling

Objects
Objects are the basic unit of OOP. They are instances of class, which have data members and uses various member
functions to perform tasks.

Class
It is similar to structures in C language. Class can also be defined as user defined data type but it also contains
functions in it. So, class is basically a blueprint for object. It declare & defines what data variables the object will
have and what operations can be performed on the class's object.

Abstraction
Abstraction refers to showing only the essential features of the application and hiding the details. In C++, classes can
provide methods to the outside world to access & use the data variables, keeping the variables hidden from direct
access, or classes can even declare everything accessible to everyone, or maybe just to the classes inheriting it. This
can be done using access specifiers.
Encapsulation
It can also be said data binding. Encapsulation is all about binding the data variables and functions together in class.

Inheritance
Inheritance is a way to reuse once written code again and again. The class which is inherited is called the Base class
& the class which inherits is called the Derived class. They are also called parent and child class.
So when, a derived class inherits a base class, the derived class can use all the functions which are defined in base
class, hence making code reusable.

Polymorphism
It is a feature, which lets us create functions with same name but different arguments, which will perform different
actions. That means, functions with same name, but functioning in different ways. Or, it also allows us to redefine a
function to provide it with a completely new definition. You will learn how to do this in details soon in coming
lessons.

Exception Handling
Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced at runtime.

11.Data Structure - Linked List ,

Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at
contiguous location; the elements are linked using pointers.

Arrays can be used to store linear data of similar types, but arrays have following limitations.
1) The size of the arrays is fixed: So we must know the upper limit on the number of elements in
advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the
usage.
2) Inserting a new element in an array of elements is expensive, because room has to be created
for the new elements and to create room existing elements have to shifted.

// A linked list node


struct Node
{
int data;
struct Node *next;
};

1. Binary Tree , BST

The following is definition of Binary Search Tree(BST) according to Binary Search Tree, is a node-based
binary tree data structure which has the following properties:
 The left subtree of a node contains only nodes with keys lesser than the node’s key.
 The right subtree of a node contains only nodes with keys greater than the node’s key.
 The left and right subtree each must also be a binary search tree.
There must be no duplicate nodes.

// C function to search a given key in a given BST


struct node* search(struct node* root, int key)
{
// Base Cases: root is null or key is present at root
if (root == NULL || root->key == key)
return root;

// Key is greater than root's key


if (root->key < key)
return search(root->right, key);

// Key is smaller than root's key


return search(root->left, key); }
Drive Name: JK TECHNOSOFT

Book Index: 71-(B)

1. What is Bootstrap?
Bootstrap is a free and open-source front-end framework for designing websites and web applications. It
contains HTML- and CSS-based design templates for typography, forms, buttons, navigation and other
interface components, as well as optional JavaScript extensions.

2. From a Table, How will you print two distinct elements?

void printDistinct(int arr[], int n)


{
// Pick all elements one by one
for (int i=0; i<n; i++)
{
// Check if the picked element is already printed
int j;
for (j=0; j<i; j++)
if (arr[i] == arr[j])
break;

// If not printed earlier, then print it


if (i == j)
cout << arr[i] << " ";
}
}

3. What is Normalization (SQL)?

Normalization is the process of reorganizing data in a database so that it meets two basic requirements: (1) There is
no redundancy of data (all data is stored in only one place), and (2) data dependencies are logical (all related data
items are stored together). Normalization is important for many reasons, but chiefly because it allows databases to
take up as little disk space as possible, resulting in increased performance.Normalization is also known as data
normalization.

4. About .NET and Its Input Output Operations?


Output functions:

Write()
writeLine(): create new line automatically

Input Functions:
read()
readLine():Reads the whole linea
5. What are IIS and JSP Servalets in Java?

Java Server Page (JSP) is a technology for controlling the content or appearance of Web pages through the use
of servlets, small programs that are specified in the Web page and run on the Web server to modify the Web page
before it is sent to the user who requested it. Sun Microsystems, the developer of Java, also refers to the JSP
technology as the Servlet application program interface (API). JSP is comparable to Microsoft's Active Server Page
(ASP) technology. Whereas a Java Server Page calls a Java program that is executed by the Web server, an Active
Server Page contains a script that is interpreted by a script interpreter (such as VBScript or JScript) before the page is
sent to the user.

IIS, or more specifically its Active Server Page (ASP) environment, contains a core group of classes that
virtually mirror those of the Java Servlet specification. ... You have to adapt (or wrap) the IIS versions of the
objects to make them look and act like servlet versions.

A servlet is a Java programming language class that is used to extend the capabilities of servers that host
applications accessed by means of a request-response programming model. Although servletscan respond to
any type of request, they are commonly used to extend the applications hosted by web servers.

6. What is the syntax for Java Class?

public class Dog {


String breed;
int age;
String color;

void barking() {
}

void hungry() {
}

void sleeping() {
}
}

7. What is Access Specifies?

An access specifier is a defining code element that can determine which elements of a program are allowed to access
a specific variable or other piece of data. Different programming languages have their own protocols for access
specifiers, as well as defaults for some code elements including both individual variables and classes.they are of 3
types:

1. Public: access allowed

2. Private:access not allowed outside the class

3. Protected:can access in inheritance.

8. What Is Default Scope?

Private in c++ and in java also.

9. What is the query of inner Joins ,Outer Join, Constant, Unique Key, Primary key, Inheritance ,Programs
Related to Linked List , In capsulation , Abstraction (there real Life Examples )

INNER JOIN: The INNER JOIN keyword selects all rows from both the tables as long as the condition
satisfies. This keyword will create the result-set by combining all rows from both the tables where the
condition satisfies i.e value of the common field will be same.
Syntax

SELECT table1.column1,table1.column2,table2.column1,....

FROM table1

INNER JOIN table2

ON table1.matching_column = table2.matching_column;

This query will show the names and age of students enrolled in different courses.

SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student

INNER JOIN StudentCourse

ON Student.ROLL_NO = StudentCourse.ROLL_NO;

OUTER JOIN

when performing an inner join, rows from either table that are unmatched in the other table are not returned. In an
outer join, unmatched rows in one or both tables can be returned. There are a few types of outer joins:

 LEFT JOIN returns only unmatched rows from the left table.
 RIGHT JOIN returns only unmatched rows from the right table.
 FULL OUTER JOIN returns unmatched rows from both tables.

Example of Left Outer Join:


SELECT companies.permalink AS companies_permalink,
companies.name AS companies_name,
acquisitions.company_permalink AS acquisitions_permalink,
acquisitions.acquired_at AS acquired_date
FROM tutorial.crunchbase_companies companies
LEFT JOIN tutorial.crunchbase_acquisitions acquisitions
ON companies.permalink = acquisitions.company_permalink

UNIQUE KEY
All tables in your databse should have a PK (although this is not enforced by most dbms), and PK can span
multiple columns. Unique key constraints are used to ensure that data is not duplicated in two rows in the
database. One row in the database is allowed to have null for the value of the unique key constraint

PRIMARY KEY

A primary key is a special relational database table column (or combination of columns) designated to
uniquely identify all table records. A primary key'smain features are: It must contain a unique value for each
row of data. It cannot contain null values.

10. What is SQ Lite?

SQLite is an embedded SQL database engine. Unlike most other SQL databases, SQLite does not have a separate
server process. SQLite reads and writes directly to ordinary disk files. A complete SQL database with multiple
tables, indices, triggers, and views, is contained in a single disk file. The database file format is cross-platform - you
can freely copy a database between 32-bit and 64-bit systems or between big-endian and little-endian architectures.
These features make SQLite a popular choice as an Application File Format. SQLite database files are
a recommended storage format by the US Library of Congress. Think of SQLite not as a replacement for Oracle but
as a replacement for fopen()

SQLite is a compact library. With all features enabled, the library size can be less than 600KiB, depending on the
target platform and compiler optimization settings. (64-bit code is larger. And some compiler optimizations such as
aggressive function inlining and loop unrolling can cause the object code to be much larger.) There is a tradeoff
between memory usage and speed. SQLite generally runs faster the more memory you give it. Nevertheless,
performance is usually quite good even in low-memory environments. Depending on how it is used, SQLite can
be faster than direct filesystem I/O.

SQLite is very carefully tested prior to every release and has a reputation for being very reliable. Most of the SQLite
source code is devoted purely to testing and verification. An automated test suite runs millions and millions of test
cases involving hundreds of millions of individual SQL statements and achieves 100% branch test coverage. SQLite
responds gracefully to memory allocation failures and disk I/O errors. Transactions are ACID even if interrupted by
system crashes or power failures. All of this is verified by the automated tests using special test harnesses which
simulate system failures. Of course, even with all this testing, there are still bugs. But unlike some similar projects
(especially commercial competitors) SQLite is open and honest about all bugs and provides bugs lists and minute-
by-minute chronologies of code changes.
The SQLite code base is supported by an international team of developers who work on SQLite full-time. The
developers continue to expand the capabilities of SQLite and enhance its reliability and performance while
maintaining backwards compatibility with the published interface spec, SQL syntax, and database file format. The
source code is absolutely free to anybody who wants it, but professional support is also available.

11. Database Query: Takeout a name from the table given?

Answer: Select name from the student where rollno=1;

Student is “TableName”
Name is the “ColumnName representing names of the student’
Rollno is the “ColumnName”

12. What are the real life examples of Stack and Queue?

Stack: Pile of dinner plates


Queue: Movie ticket window

13. What are DDL and DML?

DML statements are SQL statements that manipulate data. DML stands for Data Manipulation Language. The SQL
statements that are in the DML class are INSERT, UPDATE and DELETE. Some people also lump the SELECT
statement in the DML classification.

Data Definition Languages (DDL) are used to define the database structure. Any CREATE, DROP and ALTER
commands are examples of DDL SQL statements

14. Difference between SQ Lite and My SQL?

Sqlite is embeddable relational database management system. SQL is query language. ... Unlike other
databases (like SQL Server and MySQL) SQLite does not support stored procedures. SQLite is file-based,
unlike other databases, like SQL Server and MySQL which are server-based.

15. Where SQL is used? Give Real Life examples?

Data is stored in databases which in turn stores the data in tables that contains rows and columns. There are
several database applications available to handle the storage and management of data examples include Oracle,
Microsoft SQL and MySQL. ... Adding new record into a database. Deleting records from a database.e.g
Hospital records of patients and doctors.

16. Difference between KOTLIN and Java?

 Null Safety - As already mentioned in above section that Kotlin avoids NullPointerException. Kotlin fails at
compile-time whenever a NullPointerException may be thrown.
 Data Classes - In Kotlin there are Data Classes which leads to autogeneration of boilerplate like equals,
hashCode, toString, getters/setters and much more.

Extension Functions - Kotlin allows us to extend the functionality of existing classes without inheriting from
them. Means to say that Kotlin provides the ability to extend a class with new functionality without having to
inherit from the class. This is done by extension functions. To declare an extension function, we need to
prefix its name with a receiver type, i.e. the type being extended.

17. Have you heard about GO Language?

For the language released in 2003 by McCabe and Clark, see Go! (programming language).
"Google Go" redirects here. For the computer program by Google to play the board game Go, see AlphaGo.
Go (often referred to as Golang[12]) is a programming language designed by Google[13] engineers Robert
Griesemer, Rob Pike, and Ken Thompson.[10] Go is a statically typed, compiled language in the tradition of C, with
the added benefits of memory safety, garbage collection, structural typing,[3] and CSP-style concurrency.
[14]
The compiler, tools, and source code are all free and open source.[15]

18. Write a program of Fibonannci Series?

int main()
{
int i, n, t1 = 0, t2 = 1, nextTerm;

printf("Enter the number of terms: ");


scanf("%d", &n);

printf("Fibonacci Series: ");

for (i = 1; i <= n; ++i)


{
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}

19. What are main concepts of OOPS?

Objects:

Objects are the basic run-time entities in an object-oriented programming. They may represents a person, a place, a
bank account, a table of data or any item that the program has to handle. They may also represents user-defined data
such as vector, time and lists. When the program is executed, the object interact by sending message to one another.

Classes:
Objects contain data, and code to manipulate that data. The entire set of data and code of an object can be made a
user-defined data type with the help of class. In fact, objects are variable of the type class. Once a class has been
defined, we can create a number of objects belonging to that class. A class is a collection of objects of similar type.

Ex. Fruit mango;

Data Abstraction:

Abstractions refer to the act of representing essential features without including background details or explanation.
They are commonly known as Abstraction Data Type(ADT).

Encapsulation:

The wrapping up of data and functions into single unit is known as encapsulation. Data encapsulation is a striking
feature of a class. The data is not accessible to the outside world, and only those functions which are wrapped in the
class can access it. These functions provide the interface between the object's data and the program.

Inheritance:

Inheritance is the process by which objects of one class acquire the properties of object of another class. The class
whose members are inherited is called the Base class and the class that inherits those members is called Derived
class. It supports class of hierarchical classification.

The concept of inheritance provides the ideas of reusability. This means we can add essential features to an exciting
class without modifying it.

Polymorphism:

Polymorphism is another OOP concept. Polymorphism means the ability to take more than one form. An operation
may exhibit different behaviors at different instances.

20. There is a Bridge in .NET And Database, What it is called?


This interface acts as a bridge between an RDBMS system and a .Net application. ADO.NET is such an
interface that is created to connect .NET applications toRDBMS systems. In the .NET framework, Microsoft
introduced a new version of Active X Data Objects (ADO) called ADO.NET. ... ADO reduces the number of
objects.

21. What is static Queue?


A static queue is one that is defined ahead of time and the queue definition persists in the environment. A
dynamic queue is created on demand. ... A temporary dynamic queue is created on demand and is deleted
when the program that created it disconnects.

22. What is Project Architecture? What kind of Database you have used? Write its Database.

Ans: Ans: Project Architecure means what are the tiers in our project with flow diagram.
supposoe our project contains five tiers like client tier ,presentation tier, Business tier,Integration tier,Data tier. then
we draw the all tiers flow. Project approch is different from project architecure.

Client tier:
IE Browser (default) from which the end user will access the application
The request from the browser will be submitted to the Application Server using HTTP protocol.
The Response from the presentation layer (struts framework) will be interpreted into html pages to view on the
browsers.

Presentation Tier:
Struts Framework with Tiles
On Request from the browser, the appropriate Action Class handles the user request. The Action class then connects
to the business tier via Service Business Delegate.
Tiles have been used to create a set of pages with a consistent user interface (e.g.: the same navigation bar, header,
footer, etc.).
Taglibs are used for displaying tabular data (e.g. search results) in a consistent fashion, with pagination.

Business Delegate layer


Enable the Struts Action classes to be unaware of underlying Session Beans
Encapsulates the invocation of Service Locator to locate them.

Business Tier
The Business Delegate identifies the business service class (the Session EJBs) and delegates client request to the
EJBs. Internally, the session beans are shallow, and delegate all business logic requests to business logic POJOs,
which in turn implement the actual functionality.
The Business Logic POJOs encapsulate the server side business logic. They do not use Hibernate directly, but
instead call upon Data Access Objects (DAO) to work with the model. Parameters and return values are modeled as
Data Transfer Objects (DTO), and hence no Hibernate model classes will ever leave the DAO layer. The business
logic is made available in the business service class, which increases maintainability and easy debugging, if
necessary.

DB Tier
The DAOs encapsulates the database access. For all practical purposes, we are using Hibernate (v 2.1) as the OR
mapping layer. This saves development time to write SQLs for executing insert and update statements, find by
primary key etc. For each value object that directly or compositely represent a table in the database, we have
Hibernate mapping files.
For some complex data retrieval, however we will be using raw SQLs (independent of database) from the DAOs and
populate the Value Object POJOs. In those specific cases, the DAOs will be having direct access to the Databases
using the available connection. The connection properties of the ?DB Manager?, holding the data sources, direct the
request to the appropriate database.

23. What is Cloud Computing? What are its platforms? What are its advantages? What are its
disadvantages? Why it was started? What are its Modules?

Ans: Cloud computing is the the use of various services, such as software development platforms, servers, storage
and software, over the internet, often referred to as the "cloud."
In general, there are three cloud computing characteristics that are common among all cloud-computing vendors:

1. The back-end of the application (especially hardware) is completely managed by a cloud vendor.
2. A user only pays for services used (memory, processing time and bandwidth, etc.).
3. Services are scalable

Many cloud computing advancements are closely related to virtualization. The ability to pay on demand and scale
quickly is largely a result of cloud computing vendors being able to pool resources that may be divided among
multiple clients.
It is common to categorize cloud computing services as infrastructure as a service (IaaS), platform as a service
(PaaS) or software as a service (SaaS).

Cloud Computing advantages


Cloud computing is an emerging technology that almost every company switched to from on-premise technologies.
Whether it is public, private or hybrid, Cloud computing has become an essential factor for the companies to achieve
competitive. Let us find out why Cloud is so much preferred over on-premise technologies-

 Cost efficiency – The biggest reason behind shifting to cloud computing is that it takes considerably lesser
cost than an on-premise technology. Now the companies need not store the data in disks anymore as the Cloud
offers enormous space available saving money and resources of the companies.

 High Speed – Cloud computing lets you deploy the service quickly in fewer clicks. This quick deployment
lets you get the resources required for your system within fewer minutes.

 Excellent accessibility – Storing the information in cloud allows you to access it anywhere, anytime
regardless of the machine making it highly accessible and flexible technology of present times.

 Back-up and restore data – Once the data is stored in Cloud, it is easier to get the back-up and recovery of
that, which is quite a time taking process on-premise.

Cloud Computing disadvantages


Every technology has positive and negatives aspects that are highly important to discuss before implementing it.
Aforementioned points highlight the benefits of using cloud technology and following discussion will outline the
potential cons of Cloud Computing-

 Security issues – At time storing data in cloud may pose serious challenge of information theft in front of
the company. Though advanced security measures are deployed on cloud, still storing a confidential data in cloud
can be a risky affair.

 Low bandwidth – At times the bandwidth is low as many users are accessing cloud at the same time which
causes its bandwidth to go down. With less speed the benefits of cloud computing cannot be realized.

 Flexibility issues – The cloud services run on remote servers which make it hard for the companies to have
control over software and hardware. The services at times do not run the way it should.

 Incompatibility – Since entire infrastructure gets virtualized, incompatibility issues may arise at times that
may pose serious challenges on the way of smooth running of services.

24. Why Is Cloud Computing Preferable?


Ans: Kindly follow the advantages of Cloud Computing.

25. If there is a String A, B, C, D, E .Without affecting its elements, how will you reverse it?
Ans: Simple Solution:
1) Create a temporary character array say temp[].
2) Copy alphabetic characters from given array to temp[].
3) Reverse temp[] using standard string reversal algorithm.
4) Now traverse input string and temp in a single loop. Wherever there is alphabetic character is input string,
replace it with current character of temp[].

Efficient Solution:
Time complexity of above solution is O(n), but it requires extra space and it does two traversals of input string.
We can reverse with one traversal and without extra space. Below is algorithm.

1) Let input string be 'str[]' and length of string be 'n'


2) l = 0, r = n-1
3) While l is smaller than r, do following
a) If str[l] is not an alphabetic character, do l++
b) Else If str[r] is not an alphabetic character, do r--
c) Else swap str[l] and str[r]

26. What is the difference between Stored Procedure and Function?


Ans:

Stored Procedure Functions


1.Can have both input / output parameters 1.Can have only input parameters
2. Stored procedure can’t call from the functions 2.Functions can call from the stored procedures
3.It’s optional to return the value, as somestimes it returns 0 or
3.It’s should return the value
n values
4. It allows insert/update/delete/select 4.It allows only select statement
5.Procedures cant be utilized in a select statement 5.Function is embedded in a select statement
6.Procedure cannot be used in SQL statements with WHERE/ 6.SQL statements can be used with
HAVING/SELECT WHERE/HAVING/SELECT
7.Here, we can’t handle the exception, using try-
7. Exception can be handled by try-catch block
catch block

27. What do you know about Data Structure?


Ans: Data structure refers to methods of organizing units of data within larger data sets. Achieving and
maintaining specific data structures help improve data access and value. Data structures also help programmers
implement various programming tasks.

28. What is the working of Max Function?

Ans: The max() function of PHP is used to find the numerically maximum value in an array or the numerically
maximum value of several specified values. The max() function can take an array or several numbers as an argument
and return the numerically maximum value among the passed parameters. The return type is not fixed, it can be an
integer value or a float value based on input.
Syntax:
max(array_values)

or
max(value1, value2, ...)

Parameters: This function accepts two different types of arguments which are explained below:
1. array_values : It specifies an array containing the values.
2. value1, value2, … : It specifies two or more than two values to be compared.
Return Value: The max() function returns the numerically maximum value.

29. What are Joins? What are its queries?

Ans: Joins help retrieving data from two or more database tables. The tables are mutually related using primary and
foreign keys.

Types of joins

Cross JOIN

Cross JOIN is a simplest form of JOINs which matches each row from one database table to all rows of another.

In other words it gives us combinations of each row of first table with all records in second table.

Suppose we want to get all member records against all the movie records, we can use the script shown below to get
our desired results.

SELECT * FROM `movies` CROSS JOIN `members`

INNER JOIN

The inner JOIN is used to return rows from both tables that satisfy the given condition.

Suppose , you want to get list of members who have rented movies together with titles of movies rented by them.
You can simply use an INNER JOIN for that, which returns rows from both tables that satisfy with given conditions.
SELECT members.`first_name` , members.`last_name` , movies.`title`
FROM members ,movies
WHERE movies.`id` = members.`movie_id`

SELECT A.`first_name` , A.`last_name` , B.`title`


FROM `members`AS A
INNER JOIN `movies` AS B
ON B.`id` = A.`movie_id`

Outer JOINs

MySQL Outer JOINs return all records matching from both tables .

It can detect records having no match in joined table. It returns NULL values for records of joined table if no match
is found.

Sounds Confusing ? Let's look into an example -

LEFT JOIN

Assume now you want to get titles of all movies together with names of members who have rented them. It is clear
that some movies have not being rented by any one. We can simply use LEFT JOIN for the purpose.

The LEFT JOIN returns all the rows from the table on the left even if no matching rows have been found in the table
on the right. Where no matches have been found in the table on the right, NULL is returned.
SELECT A.`title` , B.`first_name` , B.`last_name`
FROM `movies` AS A
LEFT JOIN `members` AS B
ON B.`movie_id` = A.`id`

Executing the above script in MySQL workbench gives.You can see that in the returned result which is listed below
that for movies which are not rented, member name fields are having NULL values. That means no matching
member found members table for that particular movie.

RIGHT JOIN

RIGHT JOIN is obviously the opposite of LEFT JOIN. The RIGHT JOIN returns all the columns from the table on
the right even if no matching rows have been found in the table on the left. Where no matches have been found in the
table on the left, NULL is returned.

In our example, let's assume that you need to get names of members and movies rented by them. Now we have a
new member who has not rented any movie yet

SELECT A.`first_name` , A.`last_name`, B.`title`


FROM `members` AS A
RIGHT JOIN `movies` AS B
ON B.`id` = A.`movie_id`

"ON" and "USING" clauses

In above JOIN query examples, we have used ON clause to match the records between table.

USING clause can also be used for the same purpose. The difference with USING is it needs to have identical
names for matched columns in both tables.

In "movies" table so far we used its primary key with the name "id". We referred to same in "members" table with
the name "movie_id".

ALTER TABLE `movies` CHANGE `id` `movie_id` INT( 11 ) NOT NULL AUTO_INCREMENT;

Next let's use USING with above LEFT JOIN example.


SELECT A.`title` , B.`first_name` , B.`last_name`
FROM `movies` AS A
LEFT JOIN `members` AS B
USING ( `movie_id` )

Apart from using ON and USING with JOINs you can use many other MySQL clauses like GROUP BY,
WHERE and even functions like SUM, AVG, etc.

30. What is Branding in HTML?


Ans: The process involved in creating a unique name and image for a product in the consumers' mind, mainly
through advertising campaigns with a consistent theme. Branding aims to establish a significant and
differentiated presence in the market that attracts and retains loyal customers.

31. In which Programming Language, You are most comfortable with?


Ans: Based on student feedback.

32. What are IAAS, PAAS, and SAAS?


Ans: Software as a Service, also known as cloud application services, represent the most commonly utilized
option for businesses in the cloud market. SaaS utilizes the internet to deliver applications to its users, which are
managed by a third-party vendor. A majority of SaaS applications are run directly through the web browser, and
do not require any downloads or installations on the client side

Examples of SaaS
Google Apps, Dropbox, Salesforce, Cisco WebEx, Concur, GoToMeeting

PaaS: Platform as a Service


Cloud platform services, or Platform as a Service (PaaS), provide cloud components to certain software while
being used mainly for applications. PaaS provides a framework for developers that they can build upon and use
to create customized applications. All servers, storage, and networking can be managed by the enterprise or a
third-party provider while the developers can maintain management of the applications.

Examples of PaaS
AWS Elastic Beanstalk, Windows Azure, Heroku, Force.com, Google App Engine, Apache Stratos, OpenShift

IaaS: Infrastructure as a Service


Cloud infrastructure services, known as Infrastructure as a Service (IaaS), are made of highly scalable and
automated compute resources. IaaS is fully self-service for accessing and monitoring things like compute,
networking, storage, and other services, and it allows businesses to purchase resources on-demand and as-needed
instead of having to buy hardware outright.

Examples of IaaS
DigitalOcean, Linode, Rackspace, Amazon Web Services (AWS), Cisco Metapod, Microsoft Azure, Google
Compute Engine (GCE)
33. What is Azure (Microsoft)
Ans: Microsoft has leveraged its constantly-expanding worldwide network of data centers to create Azure, a
cloud platform for building, deploying, and managing services and applications, anywhere. Azure lets you add
cloud capabilities to your existing network through its platform as a service (PaaS) model, or entrust Microsoft
with all of your computing and network needs with Infrastructure as a Service (IaaS). Either option provides
secure, reliable access to your cloud hosted data—one built on Microsoft’s proven architecture. Azure provides
an ever expanding array of products and services designed to meet all your needs through one convenient, easy
to manage platform. Below are just some of the capabilities Microsoft offers through Azure and tips for
determining if the Microsoft cloud is the right choice for your organization.

34. What is web view App (in Android)? How will it perform?

Ans: Android system Webview app comes pre-installed into Android OS for rendering an in app browser as a part of
activity layout. This in-app browser is what we term as Webviews.

Webviews are the unique element of a hybrid application.


Hybrid Applications – As the name suggests they are a mixture of Native and Web Applications. They are available
in application store for download and require set of access from device like native apps, but they also have a browser
embedded in the application(WebView) for rendering HTML.
Instagram is a good example of a hybrid application.

35. How you can replace a number which is in middle of stack and link list?

Ans: Solution
Following example uses replaceAll() method to replace all the occurance of an element with a different element in a
list.

import java.util.*;

public class Main {


public static void main(String[] args) {
List list = Arrays.asList("one Two three Four five six one three
Four".split(" "));
System.out.println("List :"+list);
Collections.replaceAll(list, "one", "hundread");
System.out.println("replaceAll: " + list);
}
}

Result

The above code sample will produce the following result.

List :[one, Two, three, Four, five, six, one, three, Four]
replaceAll: [hundread, Two, three, Four, five, six,
hundread, three, Four]

36. In SQL if we have to take out an element from a Table then what is its query?

Ans:
select TheFieldYouWant from YourTable where RowIdYouWant = 1
This will get from the table the row with Id = 1 and then, show you the field you want. You could put more fields, if
you want to show more, or * to show all of them

37. Why we use SQL? What are benefits of Using SQL?

Ans: SQL is important because of the following main reasons -

a. SQL helps you to find the needed information or data easily.

b. SQL is a query language, not a programming language. You can easily write commands almost same as you write
English.

c. It quickly stores and gets data from the database quickly. SQL is used for the query, insert, collect and manages
data from the database.

d. Almost every database system will need SQL for further processing.

Reasons to learn SQL if you are still not planning to learn it

a. It doesn't require coding - SQL easily manages the database system without any requirement of adding
significant code. It does so by using standard SQL.

b. Portability - I think this is the main benefit of SQL. You can run SQL on PCs, laptop, servers, tablets, even on the
smartphone. Also, the database can easily be moved from one device to other.

c. Easy to learn - As I told you, it is the easiest language contains English statements. You can easily learn to write
queries and manipulate data.

d. SQL Standard - DQL databases are used by established standards. The first standard for this by ANSI (American
National Standards Institute) in 1986 and ISO (International Standards Organization) in 1987.

38. What is ASP.NET? What is its Framework?


Ans:
ASP.NET is an open-source server-side web application framework designed for web development to produce dynamic web pages. It
was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services.
It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server
Pages(ASP) technology. ASP.NET is built on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code
using any supported .NET language. The ASP.NET SOAP extension framework allows ASP.NET components to process SOAP
messages.
ASP.NET's successor is ASP.NET Core. It is a re-implementation of ASP.NET as a modular web framework, together with other
frameworks like Entity Framework. The new framework uses the new open-source .NET Compiler Platform (codename "Roslyn") and
is cross platform. ASP.NET MVC, ASP.NET Web API, and ASP.NET Web Pages (a platform using only Razor pages) have merged
into a unified MVC 6.

.NET Framework (pronounced dot net) is a software framework developed by Microsoft that runs primarily on Microsoft Windows. It
includes a large class library named Framework Class Library (FCL) and provides language interoperability (each language can use
code written in other languages) across several programming languages. Programs written for .NET Framework execute in
a software environment (in contrast to a hardware environment) named Common Language Runtime(CLR), an application virtual
machine that provides services such as security, memory management, and exception handling. (As such, computer code written
using .NET Framework is called "managed code".) FCL and CLR together constitute .NET Framework.
FCL provides user interface, data access, database connectivity, cryptography, web application development, numeric algorithms,
and network communications. Programmers produce software by combining their source code with .NET Framework and other
libraries. The framework is intended to be used by most new applications created for the Windows platform. Microsoft also produces
an integrated development environment largely for .NET software called Visual Studio.
.NET Framework began as proprietary software, although the firm worked to standardize the software stack almost immediately, even
before its first release. Despite the standardization efforts, developers, mainly those in the free and open-source softwarecommunities,
expressed their unease with the selected terms and the prospects of any free and open-source implementation, especially
regarding software patents. Since then, Microsoft has changed .NET development to more closely follow a contemporary model of a
community-developed software project, including issuing an update to its patent promising to address the concerns.
.NET Framework led to a family of .NET platforms targeting mobile computing, embedded devices, alternative operating systems,
and web browser plug-ins. A reduced version of the framework, .NET Compact Framework, is available on Windows CE platforms,
including Windows Mobile devices such as smartphones. .NET Micro Framework is targeted at very resource-constrained embedded
devices. Silverlight was available as a web browser plugin. Mono is available for many operating systems and is customized into
popular smartphone operating systems (Android and iOS) and game engines. .NET Core targets the Universal Windows
Platform (UWP), and cross-platform and cloud computing workloads

39. What are the drawbacks of using Cloud Computing?

Ans: Downtime
As cloud service providers take care of a number of clients each day, they can become overwhelmed and may even come up
against technical outages. This can lead to your business processes being temporarily suspended. Additionally, if your internet
connection is offline, you will not be able to access any of your applications, server or data from the cloud.
Security
Although cloud service providers implement the best security standards and industry certifications, storing data and important
files on external service providers always opens up risks. Using cloud-powered technologies means you need to provide your
service provider with access to important business data. Meanwhile, being a public service opens up cloud service providers to
security challenges on a routine basis. The ease in procuring and accessing cloud services can also give nefarious users the
ability to scan, identify and exploit loopholes and vulnerabilities within a system. For instance, in a multi-tenant cloud
architecture where multiple users are hosted on the same server, a hacker might try to break into the data of other users hosted
and stored on the same server. However, such exploits and loopholes are not likely to surface, and the likelihood of a
compromise is not great.

Vendor Lock-In
Although cloud service providers promise that the cloud will be flexible to use and integrate, switching cloud services is
something that hasn’t yet completely evolved. Organizations may find it difficult to migrate their services from one vendor to
another. Hosting and integrating current cloud applications on another platform may throw up interoperability and support
issues. For instance, applications developed on Microsoft Development Framework (.Net) might not work properly on the Linux
platform.

Limited Control
Since the cloud infrastructure is entirely owned, managed and monitored by the service provider, it transfers minimal control
over to the customer. The customer can only control and manage the applications, data and services operated on top of that, not
the backend infrastructure itself. Key administrative tasks such as server shell access, updating and firmware management may
not be passed to the customer or end user.
40. How many Modules were there in Your Project? How you connected it with the database? How you Fetch the
values from the database?
Ans: Based on student Project
Company Name: - Microsoft Placement Drive

Book Index: 108 – (C)

Technical
1. Consider the following operation along with Enqueue and Dequeue operations on queues, where k is a global
parameter
MultiDequeue (Q)
{
N=k
While (Q is not empty) and (n > Ө)
{
Dequeue (Q)
n= n-1
}
}

What is the worst- case time complexity of a sequence of ‘m’ MultiDequeue () operations on an initially
empty queue?
A. Ө (mk)
B. Ө (m)
C. Ө (m2)
D. Ө (m+k)
Ans: A

Explanation: Since the queue is empty initially, the condition of while loop never becomes true. So the time
complexity is Ө (mk)

2. Let a priority queue be implemented as a Max- Heap. At first, it has 5 elements. The level-order traversal of
the heap is 10,8,5,3,2. Two new elements 1 and 7 are inserted into the heap in that order. The level-order
traversal of the heap after the insertion of the elements will be:
A. 10,8,7,3,2,1,5
B. 10,8,7,2,3,1,5
C. 10,8,7,5,3,2,1
D. 10,8,7,1,2,3,5
Ans-c

Explanation:

Initially heap has 10, 8, 5, 3, 2


10
/ \
8 5
/ \
3 2

After insertion of 1
10
/ \
8 5
/ \ /
3 2 1
No need to heapify as 5 is greater than 1.

After insertion of 7
10
/ \
8 5
/ \ / \
3 2 1 7
Heapify 5 as 7 is greater than 5
10
/ \
8 7
/ \ / \
3 2 1 5
No need to heapify any further as 10 is
greater than 7

3. Four matrices A1,A2,A3and A4 of dimensions a × b, b × c, c × d and d × e respectively can be multiplied in


several with the different number of total scalar multiplications.
If a = 10 , b = 100, c = 20, d = 50 and e = 80, then at least how many scalar multiplications are required
here?
A. 80000
B. 44000
C. 14000
D. None of the mentioned options
Ans: B

Explanation 2-d array

4. Consider an array A[20,10]. Assume 4 words per memory cell and the base address of array A is 100. Find
the address of A[11,5] assuming row-major storage.
A. 420
B. 560
C. 650
D. 770
Ans: B

Explanation.

(0,0)---------(0,9)
-
-
-
-
-
(10,0)-------(10,9)
(11,0),---(11,4),.

Base address is 100.


Address of (11,5)= 100+110x4+20=560.

5. Which of the following products of Microsoft is used as a database server?


A. Microsoft Exchange Server
B. Microsoft Access Server
C. Microsoft SQL Server
D. Microsoft Database Server
Ans: C

6. Smallest scope to which Group Policy settings can be assigned is :


A. Organizational Units
B. Forest
C. Domains
D. None of these
Ans: A

7. In Active Directory,__________ is a general purpose container that can be used to group most other
classes together for administrative purposes.
A. Domain
B. Organizational units
C. Forest
D. Tree
Ans: B

8. Which of the following is a Domain-wide Operations Master Role?


A. RID Master
B. BDC Emulator Master
C. Infrastructure Master
D. Schema Master
Ans: C

9. Which of the following activities does and Active Directory Site help to facilitate?
A. Authentication
B. Replication
C. Service Location
D. All of these
Ans: B

10. A hardware device in each of the nodes of the network, which is used to connect to the network is :
A. Bridge
B. Network Interface Card / Network Adapter
C. Hub
D. Cable
Ans: B
11. __________ in AD DS represent the physical structure, or topology, of your network.
A. Sites
B. Links
C. None of these
D. DNS
Ans: B

12. RPC stands for:


A. Remote Process Call
B. Remote Process Computer
C. Remote Procedure Call
D. Remote Process Client
Ans: C

13. Active Directory supports multimaster replication of the directory data store between all domain
controllers (DC) in the domain.
A. False
B. True
Ans: A

14. What is the name of the snap – in that can be used to manage trusts in Active Directory?
A. Active Directory Trusts Editor
B. Active Directory Domains and Trusts
C. Active Directory Trusts Management Tool
D. Any of these
Ans: B

15. Organizational Units can futher contain more Organizational Units


A. False
B. True
Ans: A

16. To backup the Active Directory database, you need to have all the AD services in a stopped state.
A. False
B. True
Ans: A

17. Which of the following represent an essential service in AD?


A. KDC
B. Netlogon
C. Filre Replication
D. All of these
Ans: B

18. The first domain that is installed in the Active Directory Forest is referred as:
A. Primary Domain
B. Forest Domain
C. Root Domain
D. Key Domain
Ans: A

19. Which of the following AD partitions get replicated to all the domain controllers of a forest?
A. Schema
B. Domain
C. All of these
D. Configuration
Ans: B

20. ___________ describes the characteristics of some aspect of an object in Active Directory. It defines the
types of information that an object can hold.
A. Class
B. Schema
C. Syntaxes
D. Attributes
Ans: A
21. A process P1 has a period of 50 and a CPU burst of 25 and P2has a period of 80, CPU burst of 35 then
which of the following is the total CPU utilization?
A. 0.94
B. 0.49
C. 0.6
D. 0.82
Ans: B

Networking Technical

22. When data is transmitted from device (1) to device (2), the header from (1)’s 5 th layer is read by (2)’s:
A. Physical layer
B. None of the mentioned options
C. Session layer
D. Transport layer

Answer: C

Explanation: At device 1 the header from 5th layer that is session layer is read by the same layer at device 2
that is session layer. Because sender add the header and at the receiver same layer remove the header. So C is
correct answer.

23. Which of the following is true regarding HTTP pipelining?


A. Multiple HTTP requests are sent on a single TCP connection without waiting for the corresponding
responses
B. Multiple HTTP requests cannot be sent on a single TCP connection
C. Multiple HTTP requests are sent in a queue on a single TCP connection
D. None of the mentioned options

Answer: A
Sol: After three way handshaking, client can send multiple web requests without waiting for response.

24. Which of the following mentioned physical topologies is used in Fiber Distributed Data Interface
(FDDI)?
A. Ring
B. Star
C. Bus
D. Tree

Ans: A
Sol. FDDI (Fiber Distributed Data Interface) is a set of ANSI and ISO standards for data transmission on
fiber optic lines in a local area network (LAN) that can extend in range up to 200 km (124 miles). The FDDI
protocol is based on the token ring protocol. In addition to being large geographically, an FDDI local area
network can support thousands of users. FDDI is frequently used on the backbone for a wide area
network (WAN). An FDDI network contains two token rings, one for possible backup in case the primary
ring fails. The primary ring offers up to 100 Mbps capacity. If the secondary ring is not needed for backup,
it can also carry data, extending capacity to 200 Mbps. The single ring can extend the maximum distance;
a dual ring can extend 100 km (62 miles).

25. Which of the following command is used to copy a file from the client to the server?
A. STOR command.
B. LIST command.
C. None of the mentioned
D. RETR command.

Ans: A

Sol. The STORE (STOR) command is used by the client to tell the server to accept the data
transferred via the data connection and to store the data as a file at the server site.

26. Which of the following conditions should be satisfied by G(x) to detect the odd number of bits in
error?
A. G (x) does not divide 1+xk, for any k not exceeding the frame length
B. G (x) has an odd number of terms.
C. G (x) contains more than two terms
D. 1 + x is a factor of G (x)

Answer: D

27. Following given are the three different activities.


A1: Send an email from a mail client to mail server
A2: Download an email from mailbox server to a mail client
A3: Checking email in a web browser
Choose the application layer protocols which are generally used for each of these activities.
A. A1: SMTP, A2:FTP, A3:HTTP
B. A1: POP, A2: SMTP, A3:IMAP
C. A1: SMTP, A2:POP, A3:HTTP
D. A1: HTTP, A2:SMTP, A3:POP

Answer: C
Sol: 1. SMTP stands for Simple Mail Transfer Protocol. SMTP is used when email is delivered from an email client, such as
Outlook Express, to an email server or when email is delivered from one email server to another. SMTP is a push protocol and is used to
send the mail whereas POP (post office protocol) are used to retrieve those mails at the receiver’s side.
2. Stands for "Hypertext Transfer Protocol." HTTP is the protocol used to transfer data over the web. It is part of the Internet
protocol suite and defines commands and services used for transmitting webpage data. HTTP uses a server-client model.

28. In Microsoft Windows Operating System, the size of the virtual address space varies for each
hardware platform.
A. Depends
B. TRUE
C. FALSE
D. Question too ambiguous

Ans: B

Sol: It depends on the OS for how much default process space is allocated. In Windows 64-bit, a
default virtual address space for a process is 8 terabytes (there are a total of 2 ^ 24 addressable
terabytes on a 64-bit byte addressable system) and in 32-bit it's only 2 GB (4 GB addressable total).

29. Arrange the order in which the below version of windows were released by Microsoft:
1. Windows 3.0
2. Windows Vista
3. Windows XP
4. Windows NT
5. Windows 2000
A. 53124
B. 14532
C. 34215
D. 12345

Answer: B
Windows 3.0 22 May 1990
Windows NT 3.1 27 July 1993
Windows 2000 17 February 2000
Windows XP 25 October 2001
Windows Vista 30 January 2007

30. In the example “microsoft.com.”, which of the following statement is right?


A. “microsoft.com.” represents the second level domain D
B. “.com” represents the Top Level Domain
C. All of these
D. “.” represents the root domain

Answer: C
31. What will be the bit rate in Ethemet when Manchester encoding is used?
A. Four time the baud rate
B. Twice the baud rate
C. Half the baud rate
D. Sane as the baud rate
Answer: C
Sol: In Manchester encoding, the bitrate is half of the baud rate.

32. Which of the following is the protocol data unit (PDU) for the application layer in the Internet stack?
A. Frame
B. Message
C. Segment
D. Datagram
Ans: B

Sol: The Layer 1 (Physical Layer) PDU is the bit or, more generally, symbol The Layer 2 (Data Link Layer)
PDU is the frame. The Layer 3 (Network Layer) PDU is the packet. The Layer 4 (Transport Layer) PDU is
the segment for TCP or the datagram for UDP. The Layer 5 (Application Layer) PDU is the data or message.
Drive Name: Microsoft
Book Index: 108-(C)

Technical Interview
1. Tell me about yourself.
Explanation:
Not a technical question
2. What are the subjects that you studied in your 3 years of Engineering?
Explanation:
Answer will vary for each student.
3. Apart from Academics, What special preparations did you do for Microsoft?
Explanation:
Answer will vary for each student.

4. Tell me about process scheduling?


Explanation:

The act of determining which process is in the ready state, and should be moved to the running state is known
as Process Scheduling.
The prime aim of the process scheduling system is to keep the CPU busy all the time and to deliver minimum
response time for all programs. For achieving this, the scheduler must apply appropriate rules for swapping
processes IN and OUT of CPU.
Scheduling fell into one of the two general categories:

 Non Pre-emptive Scheduling: When the currently executing process gives up the CPU voluntarily.

 Pre-emptive Scheduling: When the operating system decides to favour another process, pre-empting the

currently executing process.

5. What is starvation?
Explanation:
Starvation is the name given to the indefinite postponement of a process because it requires some resource before it
can run, but the resource, though available for allocation, is never allocated to this process. It is sometimes called live
lock, though sometimes that name might be reserved for cases where the waiting process is doing something, but
nothing useful, as in a spin lock. However it happens, starvation is self-evidently a bad thing; more formally, it's bad
because we don't want a non-functional system. If starvation is possible in a system, then a process which enters the
system can be held up for an arbitrary length of time. To avoid starvation, it is often said that we want the system's
resources to be shared "fairly". This is an appealing suggestion, but in practice it isn't much use because it doesn't
define what we mean by "fairly", so it's really more of a description of the problem than a contribution to its solution.
It's more constructive to investigate the paths by which a system can reach a live locked state, and try to control
them.

6. Context switching and paging.


Explanation:
Context switching is the procedure of storing the state of an active process for the CPU when it has to start
executing a new one. For example, process A with its address space and stack is currently being executed by the
CPU and there is a system call to jump to a higher priority process B; the CPU needs to remember the current state of
the process A so that it can suspend its operation, begin executing the new process B and when done, return to its
previously executing process A.
Context switches are resource intensive and most operating system designers try to reduce the need for a context
switch. They can be software or hardware governed depending upon the CPU architecture.
Context switches can relate to either a process switch, a thread switch within a process or a register switch. The
major need for a context switch arises when CPU has to switch between user mode and kernel mode but some OS
designs may obviate it.
Paging is a memory management scheme that eliminates the need for contiguous allocation of physical memory.
This scheme permits the physical address space of a process to be non – contiguous.
 Logical Address or Virtual Address (represented in bits): An address generated by the CPU
 Logical Address Space or Virtual Address Space( represented in words or bytes): The set of all logical
addresses generated by a program
 Physical Address (represented in bits): An address actually available on memory unit
 Physical Address Space (represented in words or bytes): The set of all physical addresses corresponding to
the logical addresses

7. Deadlocks. Ways to Avoid Deadlock.


Explanation:
In concurrent computing, a deadlock is a state in which each member of a group is waiting for some other member
to take action, such as sending a message or more commonly releasing a lock. Deadlock is a common problem
in multiprocessing systems, parallel computing, and distributed systems, where software and hardware locks are used
to handle shared resources and implement process synchronization.
In an operating system, a deadlock occurs when a process or thread enters a waiting state because a requested system
resource is held by another waiting process, which in turn is waiting for another resource held by another waiting
process. If a process is unable to change its state indefinitely because the resources requested by it are being used by
another waiting process, then the system is said to be in a deadlock.

Deadlock Avoidance

 The general idea behind deadlock avoidance is to prevent deadlocks from ever happening, by preventing at
least one of the aforementioned conditions.
 This requires more information about each process, AND tends to lead to low device utilization. ( I.e. it is a
conservative approach. )
 In some algorithms the scheduler only needs to know the maximum number of each resource that a process
might potentially use. In more complex algorithms the scheduler can also take advantage of the schedule of
exactly what resources may be needed in what order.
 When a scheduler sees that starting a process or granting resource requests may lead to future deadlocks,
then that process is just not started or the request is not granted.
 A resource allocation state is defined by the number of available and allocated resources, and the maximum
requirements of all processes in the system.

8. Define sub-netting.
Explanation:
Subnetting is the strategy used to partition a single physical network into more than one smaller logical sub-networks
(subnets). An IP address includes a network segment and a host segment. Subnets are designed by accepting bits
from the IP addresses host part and using these bits to assign a number of smaller sub-networks inside the original
network. Subnetting allows an organization to add sub-networks without the need to acquire a new network number
via the Internet service provider (ISP). Subnetting helps to reduce the network traffic and conceals network
complexity. Subnetting is essential when a single network number has to be allocated over numerous segments of a
local area network (LAN).
Subnets were initially designed for solving the shortage of IP addresses over the Internet.

9. What is cloud? What are its types?


Explanation:
In cloud computing, the word "cloud" (also phrased as "the cloud") is used as a metaphor for "the Internet," so the
phrase cloud computing means a type of Internet-based computing, where different services —including servers,
storage and applications — are delivered to an organization's computers and devices through the Internet.
Cloud computing is an on-demand service that has obtained mass appeal in corporate data centres. The cloud enables
the data centre to operate like the Internet and computing resources to be accessed and shared as virtual resources in
a secure and scalable manner. Like most technologies, trends start in the enterprise and shift to adoption by small
business owners.

Types of clouds
1. Private Cloud-

Private cloud solutions are dedicated to one business or organizations. Its often have much more specific security
controls than does a public cloud. It may be owned, managed, and operated by the organization, a third party, or
some combination of them, and it may exist on or off premises. Using private cloud storage allows them to control
highly sensitive data by meeting regulations and industry-based criteria, whether that is medical records, trade
secrets, or other classified information.
2. Public Cloud-

Public cloud solutions are readily available from Google, Microsoft, Amazon, and others. The cloud infrastructure is
provisioned for open use by the general public. Gmail and “U” of “I” Box are examples of public cloud services. It
may be owned, managed, and operated by a business, academic, or some combination of them, or government
organization.
3. Hybrid Cloud-
Hybrid cloud is a cloud computing environment that uses a mix of on-premises, private cloud and third-party,
public cloud services with orchestration between the two platforms. Hybrid cloud solutions are a blend of public and
private clouds.

10. What is Machine Learning?


Explanation:
Machine learning is an application of artificial intelligence (AI) that provides systems the ability to automatically
learn and improve from experience without being explicitly programmed. Machine learning focuses on the
development of computer programs that can access data and use it learn for themselves.

The process of learning begins with observations or data, such as examples, direct experience, or instruction, in order
to look for patterns in data and make better decisions in the future based on the examples that we provide. The
primary aim is to allow the computers learn automatically without human intervention or assistance and adjust
actions accordingly.
11. What is Active Directory?
Explanation:
Active Directory (AD) is a Windows OS directory service that facilitates working with interconnected, complex and
different network resources in a unified manner.
Active Directory was initially released with Windows 2000 Server and revised with additional features in Windows
Server 2008. Active Directory provides a common interface for organizing and maintaining information related to
resources connected to a variety of network directories. The directories may be systems-based (like Windows OS),
application-specific or network resources, like printers. Active Directory serves as a single data store for quick data
access to all users and controls access for users based on the directory's security policy.

12. Explain DHCP in detail.


Explanation:
Dynamic Host Configuration Protocol (DHCP) is a client/server protocol that automatically provides an Internet
Protocol (IP) host with its IP address and other related configuration information such as the subnet mask and default
gateway. RFCs 2131 and 2132 define DHCP as an Internet Engineering Task Force (IETF) standard based on
Bootstrap Protocol (BOOTP), a protocol with which DHCP shares many implementation details. DHCP allows hosts
to obtain necessary TCP/IP configuration information from a DHCP server.
The Microsoft Windows Server 2003 operating system includes a DHCP Server service, which is an optional
networking component. All Windows-based clients include the DHCP client as part of TCP/IP, including Windows
Server 2003, Microsoft Windows XP, Windows 2000, Windows NT 4.0, Windows Millennium Edition (Windows
Me), and Windows 98.
Benefits of DHCP

In Windows Server 2003, the DHCP Server service provides the following benefits:

 Reliable IP address configuration. DHCP minimizes configuration errors caused by manual IP address
configuration, such as typographical errors, or address conflicts caused by the assignment of an IP address to
more than one computer at the same time.
 Reduced network administration. DHCP includes the following features to reduce network
administration:
o Centralized and automated TCP/IP configuration.
o The ability to define TCP/IP configurations from a central location.
o The ability to assign a full range of additional TCP/IP configuration values by means of DHCP
options.
o The efficient handling of IP address changes for clients that must be updated frequently, such as
those for portable computers that move to different locations on a wireless network.
o The forwarding of initial DHCP messages by using a DHCP relay agent, thus eliminating the need to
have a DHCP server on every subnet.

Why use DHCP

Every device on a TCP/IP-based network must have a unique unicast IP address to access the network and its
resources. Without DHCP, IP addresses must be configured manually for new computers or computers that are
moved from one subnet to another, and manually reclaimed for computers that are removed from the network.
DHCP enables this entire process to be automated and managed centrally. The DHCP server maintains a pool of IP
addresses and leases an address to any DHCP-enabled client when it starts up on the network. Because the IP
addresses are dynamic (leased) rather than static (permanently assigned), addresses no longer in use are
automatically returned to the pool for reallocation.
The network administrator establishes DHCP servers that maintain TCP/IP configuration information and provide
address configuration to DHCP-enabled clients in the form of a lease offer. The DHCP server stores the
configuration information in a database, which includes:

 Valid TCP/IP configuration parameters for all clients on the network.


 Valid IP addresses, maintained in a pool for assignment to clients, as well as excluded addresses.
 Reserved IP addresses associated with particular DHCP clients. This allows consistent assignment of a single
IP address to a single DHCP client.
 The lease duration, or the length of time for which the IP address can be used before a lease renewal is
required.

A DHCP-enabled client, upon accepting a lease offer, receives:

 A valid IP address for the subnet to which it is connecting.


 Requested DHCP options, which are additional parameters that a DHCP server is configured to assign to
clients. Some examples of DHCP options are Router (default gateway), DNS Servers, and DNS Domain
Name.

13. Types of classes in sub-netting along with their range. Calculate those ranges numerically/how do you get
the range of these classes.

Explanation:
An IP address is the unique numerical address of a device in a computer network that uses Internet Protocol for
communication. The IP addresses allow you to pinpoint a particular device from the billions of devices on the
Internet. To send you a letter, someone needs your mailing address. In the same sense, one computer needs the IP
address of another computer to communicate with it.

An IP address consists of four numbers; each can contain one to three digits. These numbers are separated with a
single dot (.). These four numbers can range from 0 to 255.

The classes of IPv4 addresses

The different classes of the IPv4 address are the following:

1) Class A address

2) Class B address

3) Class C address

4) Class D address

5) Class E address

Class A Address

The first bit of the first octet is always set to zero. So, the first octet ranges from 1 – 127. The class A address only
include IP starting from 1.x.x.x to 126.x.x.x. The IP range 127.x.x.x is reserved for loop back IP addresses. The
default subnet mask for class A IP address is 255.0.0.0. This means it can have 126 networks (2 7-2) and 16777214
hosts (224-2). Class A IP address format is thus: 0NNNNNNN.HHHHHHHH.HHHHHHHH.HHHHHHHH.
Class B Address

Here the first two bits are set to zero. Class B IP Addresses range from 128.0.x.x to 191.255.x.x. The default subnet
mask for Class B is 255.255.x.x. Class B has 16384 (2 14) Network addresses and 65534 (216-2) Host addresses. Class
B IP address format is: 10NNNNNN.NNNNNNNN.HHHHHHHH.HHHHHHHH

Class C Address

The first octet of this class has its first 3 bits set to 110. Class C IP addresses range from 192.0.0.x to 223.255.255.x.
The default subnet mask for Class C is 255.255.255.x. Class C gives 2097152 (2 21) Network addresses and 254 (2 8-2)
Host addresses. Class C IP address format is: 110NNNNN.NNNNNNNN.NNNNNNNN.HHHHHHHH

Class D Address

The first four bits of the first octet in class D IP address are set to 1110. Class D has IP address rage from 224.0.0.0
to 239.255.255.255. Class D is reserved for Multicasting. In multicasting data is not intended for a particular host,
but multiple ones. That is why there is no need to extract host address from the class D IP addresses. The Class D
does not have any subnet mask.

Class E Address

The class E IP addresses are reserved for experimental purpose only for R&D or study. IP addresses in the class E
ranges from 240.0.0.0 to 255.255.255.254. This class too is not equipped with any subnet mask.

Drive Name: NINE LEAPS


Book Index: 118-(C)

TECHNICAL

1. Write a program of factorial.


Answer:
#include <iostream>
using namespace std;

int main()
{
unsigned int n;
unsigned long long factorial = 1;

cout << "Enter a positive integer: ";


cin >> n;

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


{
factorial *= i;
}
cout << "Factorial of " << n << " = " << factorial;
return 0;
}

Output
Enter a positive integer: 12
Factorial of 12 = 479001600

2. Write a program of Fibonacci series.


Answer:
#include<iostream>

using namespace std;

main()
{
int n, c, first = 0, second = 1, next;

cout << "Enter the number of terms of Fibonacci series you want" << endl;
cin >> n;

cout << "First " << n << " terms of Fibonacci series are :- " << endl;

for ( c = 0 ; c < n ; c++ )


{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
cout << next << endl;
}

return 0;
}

3. Write a program for Merge sort program


Answer:
/* C program for Merge Sort */
#include<stdlib.h>
#include<stdio.h>

// Merges two subarrays of arr[].


// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

/* create temp arrays */


int L[n1], R[n2];

/* Copy data to temp arrays L[] and R[] */


for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];

/* Merge the temp arrays back into arr[l..r]*/


i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}

/* Copy the remaining elements of L[], if there


are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}

/* Copy the remaining elements of R[], if there


are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}

/* l is for left index and r is right index of the


sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;

// Sort first and second halves


mergeSort(arr, l, m);
mergeSort(arr, m+1, r);

merge(arr, l, m, r);
}
}

/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}

/* Driver program to test above functions */


int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/sizeof(arr[0]);

printf("Given array is \n");


printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");


printArray(arr, arr_size);
return 0;
}

Output:

Given array is
12 11 13 5 6 7

Sorted array is
5 6 7 11 12 13

4. Explain arrays.
Answer:
An array is a collection of data that holds fixed number of values of same type. For example: if you want to store
marks of 100 students, you can create an array for it.

float marks[100];
The size and type of arrays cannot be changed after its declaration.

Arrays are of two types:

One-dimensional arrays
Multidimensional arrays (will be discussed in next chapter)
How to declare an array in C?
data_type array_name[array_size];
For example,

float mark[5];
Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5 floating-point values.

Elements of an Array and How to access them?


You can access elements of an array by indices.

Suppose you declared an array mark as above. The first element is mark[0], second element is mark[1] and so on.

C Array declaration

Few key notes:


Arrays have 0 as the first index not 1. In this example, mark[0]
If the size of an array is n, to access the last element, (n-1) index is used. In this example, mark[4]
Suppose the starting address of mark[0] is 2120d. Then, the next address, a[1], will be 2124d, address of a[2] will be
2128d and so on. It's because the size of a float is 4 bytes.
How to initialize an array in C programming?
It's possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};

Another method to initialize array during declaration:

int mark[] = {19, 10, 8, 17, 9};

Initialize an array in C programming

Here,

mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9

How to insert and print array elements?


int mark[5] = {19, 10, 8, 17, 9}

// insert different value to third element


mark[3] = 9;

// take input from the user and insert in third element


scanf("%d", &mark[2]);

// take input from the user and insert in (i+1)th element


scanf("%d", &mark[i]);

// print first element of an array


printf("%d", mark[0]);

// print ith element of an array


printf("%d", mark[i-1]);

Example: C Arrays
// Program to find the average of n (n < 10) numbers using arrays

#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;

printf("Average = %d", average);

return 0;
}
Output

Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39

5. Explain data structure concepts like queues, stack, linked list.


Answer:

STACK:
Stack is an abstract data type with a bounded (predefined) capacity. It is a simple data structure that allows adding
and removing elements in a particular order. Every time an element is added, it goes on the top of the stack and the
only element that can be removed is the element that is at the top of the stack, just like a pile of objects.
Basic features of Stack

1. Stack is an ordered list of similar data type.


2. Stack is a LIFO(Last in First out) structure or we can say FILO(First in Last out).
3.
4. push() function is used to insert new elements into the Stack and pop() function is used to remove an element
from the stack. Both insertion and removal are allowed at only one end of Stack called Top.
5. Stack is said to be in Overflow state when it is completely full and is said to be in Underflow state if it is
completely empty.

Applications of Stack

The simplest application of a stack is to reverse a word. You push a given word to stack - letter by letter - and then
pop letters from the stack.
There are other uses also like:

1. Parsing
2. Expression Conversion(Infix to Postfix, Postfix to Prefix etc)

QUEUES:
Queue is also an abstract data type or a linear data structure, just like stack data structure, in which the first element
is inserted from one end called the REAR(also called tail), and the removal of existing element takes place from the
other end called as FRONT(also called head).
This makes queue as FIFO(First in First Out) data structure, which means that element inserted first will be removed
first.
Which is exactly how queue system works in real world. If you go to a ticket counter to buy movie tickets, and are
first in the queue, then you will be the first one to get the tickets. Right? Same is the case with Queue data structure.
Data inserted first, will leave the queue first.
The process to add an element into queue is called Enqueue and the process of removal of an element from queue is
called Dequeue.

Basic features of Queue

1. Like stack, queue is also an ordered list of elements of similar data types.
2. Queue is a FIFO( First in First Out ) structure.
3. Once a new element is inserted into the Queue, all the elements inserted before the new element in the queue
must be removed, to remove the new element.
4. peek( ) function is oftenly used to return the value of first element without de-queuing it.

Applications of Queue
Queue, as the name suggests is used whenever we need to manage any group of objects in an order in which the first
one coming in, also gets out first while the others wait for their turn, like in the following scenarios:

1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
2. In real life scenario, Call Center phone systems uses Queues to hold people calling them in an order, until a
service representative is free.
3. Handling of interrupts in real-time systems. The interrupts are handled in the same order as they arrive i.e
First come first served.
LINKED LISTS:

Introduction to Linked Lists


Linked List is a very commonly used linear data structure which consists of group of nodes in a sequence.
Each node holds its own data and the address of the next node hence forming a chain like structure.
Linked Lists are used to create trees and graphs.

Advantages of Linked Lists

 They are a dynamic in nature which allocates the memory when required.
 Insertion and deletion operations can be easily implemented.
 Stacks and queues can be easily executed.
 Linked List reduces the access time.

Disadvantages of Linked Lists

 The memory is wasted as pointers require extra memory for storage.


 No element can be accessed randomly; it has to access each node sequentially.
 Reverse Traversing is difficult in linked list.

Applications of Linked Lists

 Linked lists are used to implement stacks, queues, graphs, etc.


 Linked lists let you insert elements at the beginning and end of the list.
 In Linked Lists we don't need to know the size in advance.
Types of Linked Lists
There are 3 different implementations of Linked List available, they are:

1. Singly Linked List


2. Doubly Linked List
3. Circular Linked List

6. Explain SQL queries.


Answer:
Ambiguous question. There are many sql queries.

7. What are joins in DBMS explain with an example.


Answer:
Basic SQL Join Types

There are four basic types of SQL joins: inner, left, right, and full. The easiest and most intuitive way to explain the
difference between these four types is by using a Venn diagram, which shows all possible logical relations between
data sets.
Let’s say we have two sets of data in our relational database: table A and table B, with some
sort of relation specified by primary and foreign keys. The result of joining these tables
together can be visually represented by the following diagram:

The extent of the overlap, if any, is determined by how many records in Table A match the
records in Table B. Depending on what subset of data we would like to select from the two
tables, the four join types can be visualized by highlighting the corresponding sections of the
Venn diagram:
Examples of SQL Join Types

Let's use the tables we introduced in the “What is a SQL join?” section to show examples of these joins in action.
The relationship between the two tables is specified by the customer_id key, which is the "primary key" in

customers table and a "foreign key" in the orders table:

Note that (1) not every customer in our customers table has placed an order and (2) there
are a few orders for which no customer record exists in our customers table.

Inner Join

Let’s say we wanted to get a list of those customers who placed an order and the details of the order they placed.
This would be a perfect fit for an inner join, since an inner join returns records at the intersection of the two tables.
select first_name, last_name, order_date, order_amount
from customers c
inner join orders o
on c.customer_id = o.customer_id
Note that only George Washington, John Adams and Thomas Jefferson placed orders, with
Thomas Jefferson placing two separate orders on 3/14/1760 and 9/03/1790.

Left Join

If we wanted to simply append information about orders to our customers table, regardless of whether a customer
placed an order or not, we would use a left join. A left join returns all records from table A and any matching records
from table B.
select first_name, last_name, order_date, order_amount
from customers c
left join orders o
on c.customer_id = o.customer_id

Note that since there were no matching records for James Madison and James Monroe in our orders table,
the order_date and order_amount are NULL, which simply means there is no data for these fields.

So why would this be useful? By simply adding a “where order_date is NULL” line to our SQL query, it returns a
list of all customers who have not placed an order:
select first_name, last_name, order_date, order_amount
from customers c
left join orders o
on c.customer_id = o.customer_id
where order_date is NULL

Right Join

Right join is a mirror version of the left join and allows to get a list of all orders, appended with customer
information.
select first_name, last_name, order_date, order_amount
from customers c
right join orders o
on c.customer_id = o.customer_id
Note that since there were no matching customer records for orders placed in 1795 and 1787,
the first_name and last_name fields are NULL in the resulting set.

Also note that the order in which the tables are joined is important. We are right joining the orders table to the
customers table. If we were to right join the customers table to the orders table, the result would be the same as left
joining the orders table to the customers table.

Why is this useful? Simply adding a “where first_name is NULL” line to our SQL query returns a list of all orders
for which we failed to record information about the customers who placed them:
select first_name, last_name, order_date, order_amount
from customers c
right join orders o
on c.customer_id = o.customer_id
where first_name is NULL

Full Join

Finally, for a list of all records from both tables, we can use a full join.
select first_name, last_name, order_date, order_amount
from customers c
full join orders o
on c.customer_id = o.customer_id
8. What are the various advantages of using Java over any other language?
Answer:
Advantages of Java

 Java offers higher cross- functionality and portability as programs written in one platform can run across
desktops, mobiles, embedded systems.
 Java is free, simple, object-oriented, distributed, supports multithreading and offers multimedia and
network support.
 Java is a mature language, therefore more stable and predictable. The Java Class Library enables cross-
platform development.
 Being highly popular at enterprise, embedded and network level, Java has a large active user community
and support available.
 Unlike C and C++, Java programs are compiled independent of platform in bytecodelanguage which
allows the same program to run on any machine that has a JVM installed.
 Java has powerful development tools like Eclipse SDK and NetBeans which have debugging capability
and offer integrated development environment.
 Increasing language diversity, evidenced by compatibility of Java with Scala, Groovy, JRuby, and
Clojure.
 Relatively seamless forward compatibility from one version to the next

9. Define the following concepts


 Abstraction :
Data abstraction is one of the most essential and important feature of object oriented programming in C++.
Abstraction means displaying only essential information and hiding the details. Data abstraction refers to
providing only essential information about the data to the outside world, hiding the background details or
implementation.
Consider a real life example of a man driving a car. The man only knows that pressing the accelerators will
increase the speed of car or applying brakes will stop the car but he does not know about how on pressing
accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the
implementation of accelerator, brakes etc in the car. This is what abstraction is.

 Encapsulation :
In normal terms Encapsulation is defined as wrapping up of data and information under a single unit. In
Object Oriented Programming, Encapsulation is defined as binding together the data and the functions that
manipulates them.

Consider a real life example of encapsulation, in a company there are different sections like the accounts
section, finance section, sales section etc. The finance section handles all the financial transactions and keep
records of all the data related to finance. Similarly the sales section handles all the sales related activities and
keep records of all the sales. Now there may arise a situation when for some reason an official from finance
section needs all the data about sales in a particular month. In this case, he is not allowed to directly access
the data of sales section. He will first have to contact some other officer in the sales section and then request
him to give the particular data. This is what encapsulation is.
 Polymorphism:
The word polymorphism means having many forms. In simple words, we can define polymorphism as the
ability of a message to be displayed in more than one form.
Real life example of polymorphism, a person at a same time can have different characteristic. Like a man at a
same time is a father, a husband, a employee. So a same person possesses have different behaviour in
different situations. This is called polymorphism.
Polymorphism is considered as one of the important features of Object Oriented Programming.
In C++ polymorphism is mainly divided into two types:
 Compile time Polymorphism
 Runtime Polymorphism

 Recursion:
The process in which a function calls itself is known as recursion and the corresponding function is called
the recursive function. The popular example to understand the recursion is factorial function.

Factorial function: f(n) = n*f(n-1), base condition: if n<=1 then f(n) = 1. Don’t worry we wil discuss what
is base condition and why it is important.

In the following diagram. I have shown that how the factorial function is calling itself until the function
reaches to the base condition.

10. What is Binary Search Tree?


Answer:

Binary Search Tree is a node-based binary tree data structure which has the following properties:
 The left subtree of a node contains only nodes with keys lesser than the node’s key.
 The right subtree of a node contains only nodes with keys greater than the node’s key.
 The left and right subtree each must also be a binary search tree.

11. If you don’t know about particular coding, what will you do?
Answer:
Not a Technical Question.

Driver Name: WIPRO

Book Index: 125-(C)

THECNICLA INTERVIEW QUESTIONS

1. How database can be connected in C language?


Ans: #include<stdio.h>
#include<SQLAPI.h> // main SQLAPI++ header

int main(int argc, char* argv[])


{
// create connection object to connect to database
SAConnection con;
try
{
// connect to database
// in this example, it is Oracle,
// but can also be Sybase, Informix, DB2
// SQLServer, InterBase, SQLBase and ODBC
con.Connect ("test", // database name
"tester", // user name
"tester", // password
SA_Oracle_Client); //Oracle Client
printf("We are connected!\n");

// Disconnect is optional
// autodisconnect will occur in destructor if needed
con.Disconnect();
printf("We are disconnected!\n");
}

catch(SAException & x)
{
// SAConnection::Rollback()
// can also throw an exception
// (if a network error for example),
// we will be ready
try
{
// on error rollback changes
con.Rollback ();
}
catch(SAException &)
{
}
// print error message
printf("%s\n", (const char*)x.ErrText());
}
return 0;
}
2. Explain your project in detail.
Ans:

3. int n=4, n=n>>2, if given is the code, What will be the output
Ans: output will be 1

4. What is Database normalization?


Ans: Database normalization is the process of restructuring a relational database in accordance with a series of so-
called normal forms in order to reduce data redundancy and improve data integrity. It was first proposed by
Edgar F. Codd as an integral part of his relational model.

5. What are the types of pointers in Java?


Ans: We use reference in Java.
Reference: A reference is a variable that refers to something else and can be used as an alias for that something else.
Pointer: A pointer is a variable that stores a memory address, for the purpose of acting as an alias to what is stored at
that address.
So, a pointer is a reference, but a reference is not necessarily a pointer. Pointers are a particular implementation of
the concept of a reference, and the term tends to be used only for languages that give you direct access to the
memory address.

6. What is jdbc function in Java?


Ans: The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational
Database. JDBC helps you to write Java applications that manage these three programming activities: Connect to
a data source, like a database. Send queries and update statements to the database.

7. Print a value without using printf in C language?


Ans:
#include<stdio.h>
int main(){
switch (printf("Chandigarh" ))
{ }
}

8. Divide a number without using /.


Ans: #include <bits/stdc++.h>
using namespace std;

// Function to divide a by b and


// return floor value it
int divide(int dividend, int divisor) {

// Calculate sign of divisor i.e.,


// sign will be negative only iff
// either one of them is negative
// otherwise it will be positive
int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;

// Update both divisor and


// dividend positive
dividend = abs(dividend);
divisor = abs(divisor);

// Initialize the quotient


int quotient = 0;
while (dividend >= divisor) {
dividend -= divisor;
++quotient;
}

return sign * quotient;


}

// Driver code
int main() {
int a = 10, b = 3;
cout << divide(a, b) <<"\n";

a = 43, b = -8;
cout << divide(a, b);

return 0;
}

9. Write a program where the comparison between c++ and python can be drawn.
Ans:C++
#include <bits/stdc++.h>
using namespace std;

// Function to divide a by b and


// return floor value it
int divide(int dividend, int divisor) {

// Calculate sign of divisor i.e.,


// sign will be negative only iff
// either one of them is negative
// otherwise it will be positive
int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;

// Update both divisor and


// dividend positive
dividend = abs(dividend);
divisor = abs(divisor);

// Initialize the quotient


int quotient = 0;
while (dividend >= divisor) {
dividend -= divisor;
++quotient;
}

return sign * quotient;


}

// Driver code
int main() {
int a = 10, b = 3;
cout << divide(a, b) <<"\n";

a = 43, b = -8;
cout << divide(a, b);

return 0;
}

Python:
def divide(dividend, divisor):

# Calculate sign of divisor i.e.,


# sign will be negative only iff
# either one of them is negative
# otherwise it will be positive
sign = -1 if ((dividend < 0) ^ (divisor < 0)) else 1

# Update both divisor and


# dividend positive
dividend = abs(dividend)
divisor = abs(divisor)

# Initialize the quotient


quotient = 0
while (dividend >= divisor):
dividend -= divisor
quotient += 1

return sign * quotient

# Driver code
a = 10
b=3
print(divide(a, b))
a = 43
b = -8
print(divide(a, b))

10. What are DDL and DML commands?


Ans: DDL:-CREATE, ALTER, DROP, TRUNCATE AND COMMENT and RENAME, etc. DML:-SELECT,
INSERT, UPDATE, DELETE, MERGE, CALL, etc. Commands which Define the Structures or object are all
DDL . Also DDL commands are auto- commit , they are transaction in themselves.
11. What are transactions in DBMS?
Ans: A transaction is a single logical unit of work which accesses and possibly modifies the contents of a database.
Transactions access data using read and write operations. In order to maintain consistency in a database, before
and after transaction, certain properties are followed.

12. How can we print anything in java other than using SOPL?
Ans:import java.io.*;

public class PrintOutTest {


public static void main(String args[]) throws IOException {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new
FileOutputStream(FileDescriptor.out), "ASCII"), 512);
out.write("test string");
out.write('\n');
out.flush();
}
}
13. What is big data? Explain its applications
Ans: Big data usually includes data sets with sizes beyond the ability of commonly used software tools to
capture, curate, manage, and process data within a tolerable elapsed time. Big data philosophy encompasses
unstructured, semi-structured and structured data, however the main focus is on unstructured data.
Some of the industries propelled by big data analytics are –

Public Sector Services.


Healthcare contributions.
Learning Services.
Insurance Services.
Industrialized and Natural Resources.
Transportation Services.
Banking Sectors and Fraud Detection

14. Explain TCP/IP protocol.


Ans: Transmission Control Protocol/Internet Protocol (TCP/IP) is the language a computer uses to access the
internet. It consists of a suite of protocols designed to establish a network of networks to provide a host with
access to the internet.
Drive Name: Hashedin Technologies
Book Index: 128-(C)
Technical interview

Find subsequence in a given array.


Solution:
// C++ program to print distinct subset sums of
// a given array.
#include<bits/stdc++.h>
using namespace std;

// sum denotes the current sum of the subset


// currindex denotes the index we have reached in
// the given array
void distSumRec(int arr[], int n, int sum,
int currindex, unordered_set<int> &s)
{
if (currindex > n)
return;

if (currindex == n)
{
s.insert(sum);
return;
}

distSumRec(arr, n, sum + arr[currindex],


currindex+1, s);
distSumRec(arr, n, sum, currindex+1, s);
}

// This function mainly calls recursive function


// distSumRec() to generate distinct sum subsets.
// And finally prints the generated subsets.
void printDistSum(int arr[], int n)
{
unordered_set<int> s;
distSumRec(arr, n, 0, 0, s);

// Print the result


for (auto i=s.begin(); i!=s.end(); i++)
cout << *i << " ";
}

// Driver code
int main()
{
int arr[] = {2, 3, 4, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
printDistSum(arr, n);
return 0;
}

Write a program for Fibonacci series.


Solution:
/* Fibonacci series program in C language */
#include <stdio.h>

int main()
{
int n, first = 0, second = 1, next, c;

printf("Enter the number of terms\n");


scanf("%d", &n);

printf("First %d terms of Fibonacci series are:\n", n);

for (c = 0; c < n; c++)


{
if (c <= 1)
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n", next);
}

return 0;
}

What are arrays and strings?


Ans: Strings are similar to arrays with just a few differences. Usually, the array size is fixed, while strings can have a
variable number of elements. Arrays can contain any data type (char short int even other arrays) while strings are
usually ASCII characters terminated with a NULL (0) character.

Write a code to reverse a linked list.


Solution:
// Iterative C++ program to reverse
// a linked list
#include<iostream>
using namespace std;

/* Link list node */


struct Node
{
int data;
struct Node* next;
Node (int data)
{
this->data = data;
next = NULL;
}
};

struct LinkedList
{
Node *head;
LinkedList()
{
head = NULL;
}

/* Function to reverse the linked list */


void reverse()
{
// Initialize current, previous and
// next pointers
Node *current = head;
Node *prev = NULL, *next = NULL;

while (current != NULL)


{
// Store next
next = current->next;

// Reverse current node's pointer


current->next = prev;

// Move pointers one position ahead.


prev = current;
current = next;
}
head = prev;
}

/* Function to print linked list */


void print()
{
struct Node *temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}

void push(int data)


{
Node *temp = new Node(data);
temp->next = head;
head = temp;
}
};

/* Driver program to test above function*/


int main()
{
/* Start with the empty list */
LinkedList ll;
ll.push(20);
ll.push(4);
ll.push(15);
ll.push(85);

cout << "Given linked list\n";


ll.print();

ll.reverse();

cout << "\nReversed Linked list \n";


ll.print();
return 0;
}

What is double pointer?


Ans: a pointer points to a location in memory and thus used to store address of variables. So, when we define a
pointer to pointer. The first pointer is used to store the address of second pointer. That is why they are also known as
double pointers.

What is recursion?
Ans: Recursion is a method of solving problems that involves breaking a problem down into smaller and smaller
subproblems until you get to a small enough problem that it can be solved trivially. Usually recursion involves a
function calling itself. While it may not seem like much on the surface, recursion allows us to write elegant solutions
to problems that may otherwise be very difficult to program.
Write a program to find repeated element in array.
Solution:
// C++ program to find the only repeating element in an
// array of size n and elements from range 1 to n-1.
#include <bits/stdc++.h>
using namespace std;

// Returns index of second appearance of a repeating element


// The function assumes that array elements are in range from
// 1 to n-1.
int findRepeatingElement(int arr[], int low, int high)
{
// low = 0 , high = n-1;
if (low > high)
return -1;

int mid = (low + high) / 2;

// Check if the mid element is the repeating one


if (arr[mid] != mid + 1)
{
if (mid > 0 && arr[mid]==arr[mid-1])
return mid;

// If mid element is not at its position that means


// the repeated element is in left
return findRepeatingElement(arr, low, mid-1);
}

// If mid is at proper position then repeated one is in


// right.
return findRepeatingElement(arr, mid+1, high);
}

// Driver code
int main()
{
int arr[] = {1, 2, 3, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int index = findRepeatingElement(arr, 0, n-1);
if (index != -1)
cout << arr[index];
return 0;
}
Write program for a tic-tok game.
Solution:
// A C++ Program to play tic-tac-toe

#include<bits/stdc++.h>
using namespace std;

#define COMPUTER 1
#define HUMAN 2

#define SIDE 3 // Length of the board

// Computer will move with 'O'


// and human with 'X'
#define COMPUTERMOVE 'O'
#define HUMANMOVE 'X'

// A function to show the current board status


void showBoard(char board[][SIDE])
{
printf("\n\n");

printf("\t\t\t %c | %c | %c \n", board[0][0],


board[0][1], board[0][2]);
printf("\t\t\t--------------\n");
printf("\t\t\t %c | %c | %c \n", board[1][0],
board[1][1], board[1][2]);
printf("\t\t\t--------------\n");
printf("\t\t\t %c | %c | %c \n\n", board[2][0],
board[2][1], board[2][2]);

return;
}

// A function to show the instructions


void showInstructions()
{
printf("\t\t\t Tic-Tac-Toe\n\n");
printf("Choose a cell numbered from 1 to 9 as below"
" and play\n\n");

printf("\t\t\t 1 | 2 | 3 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 4 | 5 | 6 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 7 | 8 | 9 \n\n");

printf("-\t-\t-\t-\t-\t-\t-\t-\t-\t-\n\n");

return;
}
// A function to initialise the game
void initialise(char board[][SIDE], int moves[])
{
// Initiate the random number generator so that
// the same configuration doesn't arises
srand(time(NULL));

// Initially the board is empty


for (int i=0; i<SIDE; i++)
{
for (int j=0; j<SIDE; j++)
board[i][j] = ' ';
}

// Fill the moves with numbers


for (int i=0; i<SIDE*SIDE; i++)
moves[i] = i;

// randomise the moves


random_shuffle(moves, moves + SIDE*SIDE);

return;
}

// A function to declare the winner of the game


void declareWinner(int whoseTurn)
{
if (whoseTurn == COMPUTER)
printf("COMPUTER has won\n");
else
printf("HUMAN has won\n");
return;
}

// A function that returns true if any of the row


// is crossed with the same player's move
bool rowCrossed(char board[][SIDE])
{
for (int i=0; i<SIDE; i++)
{
if (board[i][0] == board[i][1] &&
board[i][1] == board[i][2] &&
board[i][0] != ' ')
return (true);
}
return(false);
}

// A function that returns true if any of the column


// is crossed with the same player's move
bool columnCrossed(char board[][SIDE])
{
for (int i=0; i<SIDE; i++)
{
if (board[0][i] == board[1][i] &&
board[1][i] == board[2][i] &&
board[0][i] != ' ')
return (true);
}
return(false);
}

// A function that returns true if any of the diagonal


// is crossed with the same player's move
bool diagonalCrossed(char board[][SIDE])
{
if (board[0][0] == board[1][1] &&
board[1][1] == board[2][2] &&
board[0][0] != ' ')
return(true);

if (board[0][2] == board[1][1] &&


board[1][1] == board[2][0] &&
board[0][2] != ' ')
return(true);

return(false);
}

// A function that returns true if the game is over


// else it returns a false
bool gameOver(char board[][SIDE])
{
return(rowCrossed(board) || columnCrossed(board)
|| diagonalCrossed(board) );
}

// A function to play Tic-Tac-Toe


void playTicTacToe(int whoseTurn)
{
// A 3*3 Tic-Tac-Toe board for playing
char board[SIDE][SIDE];

int moves[SIDE*SIDE];

// Initialise the game


initialise(board, moves);

// Show the instructions before playing


showInstructions();

int moveIndex = 0, x, y;
// Keep playing till the game is over or it is a draw
while (gameOver(board) == false &&
moveIndex != SIDE*SIDE)
{
if (whoseTurn == COMPUTER)
{
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = COMPUTERMOVE;
printf("COMPUTER has put a %c in cell %d\n",
COMPUTERMOVE, moves[moveIndex]+1);
showBoard(board);
moveIndex ++;
whoseTurn = HUMAN;
}

else if (whoseTurn == HUMAN)


{
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = HUMANMOVE;
printf ("HUMAN has put a %c in cell %d\n",
HUMANMOVE, moves[moveIndex]+1);
showBoard(board);
moveIndex ++;
whoseTurn = COMPUTER;
}
}

// If the game has drawn


if (gameOver(board) == false &&
moveIndex == SIDE * SIDE)
printf("It's a draw\n");
else
{
// Toggling the user to declare the actual
// winner
if (whoseTurn == COMPUTER)
whoseTurn = HUMAN;
else if (whoseTurn == HUMAN)
whoseTurn = COMPUTER;

// Declare the winner


declareWinner(whoseTurn);
}
return;
}

// Driver program
int main()
{
// Let us play the game with COMPUTER starting first
playTicTacToe(COMPUTER);

return (0);
}

What is DML compiler?


Ans: A data manipulation language (DML) is a family of syntax elements similar to a computer programming
language used for selecting, inserting, deleting and updating data in a database. Performing read-only queries of data
is sometimes also considered a component of DML.
A popular data manipulation language is that of Structured Query Language (SQL), which is used to retrieve and
manipulate data in a relational database.[1] Other forms of DML are those used by IMS/DLI, CODASYL databases,
such as IDMS and others.
Drive Name: MIND TREE
Book Index: 132-(C)

TECHNICAL INTERVEIW

1. What are Deadlocks?

Ans: A deadlock is a situation in which two computer programs sharing the same resource are effectively preventing
each other from accessing the resource, resulting in both programs ceasing to function.

The earliest computer operating systems ran only one program at a time. All of the resources of the system were
available to this one program. Later, operating systems ran multiple programs at once, interleaving them. Programs
were required to specify in advance what resources they needed so that they could avoid conflicts with other
programs running at the same time. Eventually some operating systems offered dynamic allocation of resources.
Programs could request further allocations of resources after they had begun running. This led to the problem of the
deadlock

2. What is Bubble Sorting?


Ans: Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in which
each pair of adjacent elements is compared and the elements are swapped if they are not in order. This algorithm
is not suitable for large data sets as its average and worst case complexity are of Ο(n2) where n is the number of
items.

3. What is Programming?

Ans: A programming language is a formal language, which comprises a set of instructions used to produce various
kinds of output. Programming languages are used to create programs that implement specific algorithms. Most
programming languages consist of instructions for computers, although there are programmable machines that use a
limited set of specific instructions, rather than the general programming languages of modern computers.

4. What is Recursion?

Ans: The process in which a function calls itself directly or indirectly is called recursion and the corresponding
function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily.
Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph,
etc.

In recursive program, the solution to base case is provided and solution of bigger problem is expressed in terms of
smaller problems.

int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
In the above example, base case for n < = 1 is defined and larger value of number can be solved by converting to
smaller one till base case is reached.

5. What is Data Base?


Ans: A database is a collection of information that is organized so that it can be easily accessed, managed and
updated. Data is organized into rows, columns and tables, and it is indexed to make it easier to find relevant
information. Data gets updated, expanded and deleted as new information is added. Databases process workloads
to create and update themselves, querying the data they contain and running applications against it.

6. What is round robin?


Ans: Round-robin (RR) is one of the algorithms employed by process and network schedulers in computing. As
the term is generally used, time slices (also known as time quanta) are assigned to each process in equal portions
and in circular order, handling all processes without priority (also known as cyclic executive).

7. What do you mean by scheduling numerical?


Ans: The process scheduling is the activity of the process manager that handles the removal of the running
process from the CPU and the selection of another process on the basis of a particular strategy.
8. What is segmentation (os) Programming?

Ans: Segmentation is also a memory management scheme. It supports the user’s view of the memory. The
process is divided into the variable size segments and loaded to the logical memory address space.

The logical address space is the collection of variable size segments. Each segment has its name and length. For
the execution, the segments from logical memory space are loaded to the physical memory space.

The address specified by the user contain two


quantities the segment name and the Offset. The segments are numbered and referred by the segment
numberinstead of segment name. This segment number is used as an index in thesegment table, and offset value
decides the length or limit of the segment. The segment number and the offset together combinely generates the
address of the segment in the physical memory space.
9. Explain Data base connectivity in detail?
Ans: Database Connectivity is an application programming interface (API) for the programming language Java,
which defines how a client may access a database. It is a Java-based data access technology used for Java
database connectivity. It is part of the Java Standard Edition platform, from Oracle Corporation. It provides
methods to query and update data in a database, and is oriented towards relational databases. A JDBC-to-
ODBC bridge enables connections to any ODBC-accessible data source in the Java virtual machine (JVM) host
environment.

10. What is Subnet masking?


Ans: A subnet mask is a number that defines a range of IP addresses that can be used in a network. (It is not
something you wear on your head to keep subnets out.) Subnet masks are used to designate subnetworks, or
subnets, which are typically local networks LANs that are connected to the Internet. Systems within the same
subnet can communicate directly with each other, while systems on different subnets must communicate through
a router. Therefore, subnetworks can be used to partition multiple networks and limit the traffic between them.

11. What do you mean by Topologies?


Ans: A network topology is the pattern in which nodes (i.e., computers, printers, routers or other
devices) are connected to a local area network (LAN) or other network via links (e.g., twisted pair copper wire
cable or optical fiber cable). Thereare four principal topologies used in LANs: bus, ring, star and mesh.

12. Explain the details of your Major project?


Ans: Based on Student’s feedback

13. 2D array program?


Ans:

#include<stdio.h>
int main(){
/* 2D array declaration*/
int disp[2][3];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &disp[i][j]);
}
}
//Displaying array elements
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("%d ", disp[i][j]);
if(j==2){
printf("\n");
}
}
}
return 0;
}
Output:
Enter value for disp[0][0]:1
Enter value for disp[0][1]:2
Enter value for disp[0][2]:3
Enter value for disp[1][0]:4
Enter value for disp[1][1]:5
Enter value for disp[1][2]:6
Two Dimensional array elements:
123
456

14. Explain Joins in RDBMS?

Ans: Let’s say we have two sets of data in our relational database: table A and table B, with some sort of relation
specified by primary and foreign keys. The result of joining these tables together can be visually represented by the
following diagram:

The extent of the overlap, if any, is determined by how many records in Table A match the records in Table B.
Depending on what subset of data we would like to select from the two tables, the four join types can be visualized
by highlighting the corresponding sections of the Venn diagram:

15. Explain Heap sorting?


Ans: Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to
selection sort where we first find the maximum element and place the maximum element at the end. We repeat
the same process for remaining element.

16. What is Scope of variable?

Ans: Scope of variable is one of the important concept of Oops programming. Scope of variable can be defined
as lifetime of that variable. There are two type of scopes of a variable -
1.global
2.local
A variable is said to have global scope if they can be used anywhere but within the same class in which it is declared.
An instance variables are the variables that have global scope. The variable that are declared inside the method are
said to have a local scope .lets consider an example-
class Addition
{
int a=10; // a and b are the instance variables and they have a global scopethey can be used anywhere but within the
class only in which they are declared . When the control move out of the class their scope ends.
int b=20;
void add()
{
int c=a+b; //c is a local variable because it is declared inside the method. When scope go out of the method its scope
ends.
System.out.println("c");
}
public static void main( String[] args)
{
Addition ad=new Addition();
}
}
17. What is difference between arguments and parameters?
Ans: The parameters of a function/method describe to you the values that it uses to calculate its result.
The arguments of a are the values assigned to these parameters during a particular call of the function/method.

18. What is difference between local and global variable?


Ans: Kindly refer Question no. 16.
Company Name: - PE-2001 (Virtusa)
Book Index: 145-(C)
Technical MCQ

1. Which of the following sorting methods sorts a given set of items that is already in sorted order or in
reverse sorted order with equal speed?
A. Selection Sort B. Quick Sort C. insertion sort D. Heap sort
Answer A

Explanation: Selection Sort Best case complexity is Ω(n^2) and worst case complexity is also same O(n^2).
Best-case performance О(n2) comparisons, О(n) swaps
Average performance О(n2) comparisons, О(n) swaps

2. Which of the following statement is true?


A. Except in case of VM shutdown, if a try block starts to execute, a corresponding finally block will
always start to execute.
B. A try statement must have at least one corresponding catch block.
C. Multiple catch statements can catch the same class of exception more than once.
D. Except in case of VM shutdown, if a try block starts to execute, a corresponding finally block
must always run to completion.
Answer: D

Explanation:
A is wrong. A try statement can exist without catch, but it must have a finally statement.

B is wrong. A try statement executes a block. If a value is thrown and the try statement has one or more
catch clauses that can catch it, then control will be transferred to the first such catch clause. If that catch
block completes normally, then the try statement completes normally.

C is wrong. Exceptions of type Error and RuntimeException do not have to be caught, only checked
exceptions (java.lang.Exception) have to be caught. However, speaking of Exceptions, Exceptions do not
have to be handled in the same method as the throw statement. They can be passed to another method.

If you put a finally block after a try and its associated catch blocks, then once execution enters the try block,
the code in that finally block will definitely be executed except in the following circumstances:

An exception arising in the finally block itself.


The death of the thread.
The use of System.exit()
Turning off the power to the CPU.
I suppose the last three could be classified as VM shutdown.

3. Which of the following is the measurement of degree to which a component, system or process meets
specified requirements and/or user/customer needs and expectations.
A. Software Product B. Software Process C. Software Quality D. Quantity
Answer: c

Explanation:
quality: The degree to which a component, system or process meets specified requirements and/or
user/customer needs and expectations.
software quality: The totality of functionality and features of a software product that bear on its ability to satisfy
stated or implied needs.

4. Which of the following model remains operative until the software is retired?
A. Water fall B. Spiral C. Incremental D. All of the above
Answer: C
Explanation: The spiral model is based on continuous refinement of key products for requirements definition and
analysis, system and software design, and implementation (the code). At each iteration around the cycle, the
products are extensions of an earlier product. This model uses many of the same phases as the waterfall model,
in essentially the same order, separated by planning, risk assessment, and the building of prototypes and
simulations

5. Which of the following sorting algorithm has the worst time complexity of nlog(n)?
A. Heap sort B. Selection Sort C. Quick Sort D. Insertion sort

Answer:A
Explanation:Heapsort has O(n) time when all elements are the same. Heapify takes O(n) time and then removing
elements from the heap is O(1) time for each of the n elements. The run time grows to O(nlog(n)) if all elements
must be distinct.

6. The information about an array that is used in a program will be stored in


A. symbol table B. system table C. dope vector D. activation record
Answer:C
Explanation: Dope vector is a data structure that is used by compilers to store some metadata about the array like
its total size, the size of one unit also called stride of the array, etc. These are used to describe arrays and other
similar structures that store multiple values of one datatype as a complete block of memory. It can also describe
structures that contain arrays and similar structures as its component. Dope vectors help compilers to access the
arrays with ease. Different checks that are implemented by compiler like Out of Bound check,datatype check,etc.
are all possible because of dope vector associated with the array.

7. Consider the following scenario: A company decides that it only wants to use the most popular names
for its products. You have to give the number of employees against each unique first name. Which of the
following four core interfaces is best-suited for implementing the above scenario?
A. Map B. Set C. Queue D. List
Answer:A
Explanation: A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can
map to at most one value.

8. Web pages starts with which of the following tag?


A. <BODY> B. <TITLE> C. <HTML> D. <FORM>
Answer:C
Explanation: The <html> tag tells the browser that this is an HTML document.

The <html> tag represents the root of an HTML document.

The <html> tag is the container for all other HTML elements (except for the <!DOCTYPE> tag).
Example: !DOCTYPE HTML>
<html>
<head>
<title>Title of the document</title>
</head>

<body>
The content of the document......
</body>

</html>

9. class MethodCall {
public static void main(String args[]) {
int num1 = 10, num2 = 20, result;
result = calc (num1, num2);
System.out.printin(result);
}
// insert code here
}
Which, inserted at line “// insert code here”, produces the output 30?
10. static void calc(n1, n2) {return (n1 + n2); }
11. public int calc(int n1, int n2) {return; }
12. public int calc(int n1, int n2) {return n1 + n2; }
13. static int calc(int n1, int n2) {return n1 + n2; }
Answer: D
Explanation: If we use C option there will be compile time error, because non-static method calc(int,int) cannot be
referenced from a static context.

14. What types of errors are missed by black-box testing and can be found by white-box testing?
15. Performance error
16. Interface error
17. Behavioral error
18. Logic errors
Answer:D
Explanation: BLACK BOX TESTING, also known as Behavioral Testing, is a software testing method in which the
internal structure/design/implementation of the item being tested is not known to the tester. These tests can be
functional or non-functional, though usually functional.
This method is named so because the software program, in the eyes of the tester, is like a black box; inside which
one cannot see.
This method attempts to find errors in the following categories:

Incorrect or missing functions


Interface errors
Errors in data structures or external database access
Behavior or performance errors
Initialization and termination errors

19. Which of the following is NOT a black box technique?


A. Linear code sequence and jump
B. State transition testing
C. Equivalence partitioning
D. Boundary value analysis

Answer:A
Explanation: BLACK BOX TESTING, also known as Behavioral Testing, is a software testing method in which the
internal structure/design/implementation of the item being tested is not known to the tester. These tests can be
functional or non-functional, though usually functional.
This method is named so because the software program, in the eyes of the tester, is like a black box; inside which
one cannot see.
This method attempts to find errors in the following categories:

Incorrect or missing functions


Interface errors
Errors in data structures or external database access
Behavior or performance errors
Initialization and termination errors

20. Which of the following is NOT a type of SQL constraint?


A. PRIMARY KEY
B. UNIQUE
C. ALTERNATE KEY
D. FOREIGN KEY
Answer:C
Explanation: There is no constraint in sql called alternate key
The following constraints are commonly used in SQL:

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 satisfies 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

21. SQL statement SELECT SUBSTR(‘123456789’, INSTR(‘abcabcabc’, ‘b’0, 4) FROM DUAL will result?
A. 2345 B. 6789 C. 456789 D. 1234

Answer:A
Explanation: INSTR Function:- The INSTR function in SQL is used to find the starting location of a pattern in a
string. The syntax for the INSTR function is as follows:
INSTR (str, pattern): Find the starting location of pattern in string str.

SUBSTR Function:- The Substring function in SQL is used to grab a portion of the stored data. The syntax for
the SUBSTR function is as follows:
SUBSTR(str,pos,len): Starting with the position pos in string str select the characters upto the length len.

In the above query,


INSTR('abcabcabc', 'b') outputs 2 as the starting location of pattern

22. Which statement is true for the class java.util.ArrayList?


A. The elements in the collection are ordered.
B. The elements in the collection are guaranteed to be unique.
C. The elements in the collection are accessed using a unique key.
D. The collection is guaranteed to be immutable.
a. Answer: A
Explanation:

Yes, always the elements in the collection are ordered.

23. The postfix form of A*B+C/D is


A. *AB/CD+
B. AB*CD/+
C. A*BC+/D
D. ABCD+/*
Answer:B
Explanation: The following steps will produce a string of tokens in postfix order.

Create an empty stack called opstack for keeping operators. Create an empty list for output.
Convert the input infix string to a list by using the string method split.
Scan the token list from left to right.
If the token is an operand, append it to the end of the output list.
If the token is a left parenthesis, push it on the opstack.
If the token is a right parenthesis, pop the opstack until the corresponding left parenthesis is removed. Append each
operator to the end of the output list.
If the token is an operator, *, /, +, or -, push it on the opstack. However, first remove any operators already on the
opstack that have higher or equal precedence and append them to the output list.
When the input expression has been completely processed, check the opstack. Any operators still on the stack can be
removed and appended to the end of the output list.

24. A query involves NOT, AND, OR with no parenthesis:?


A. NOT will be evaluated first; AND will be evaluated second; OR will be evaluated last
B. NOT will be evaluated first; OR will be evaluated second; AND will be evaluated last.
C. AND will be evaluated first; OR will be evaluated second; NOT will be evaluated last.
D. The order of occurrence determines the order of evaluation.

Answer:A
Explanation: When parenthesized conditions are nested, the innermost condition is evaluated first. Under the default
precedence rules, the condition x AND NOT y OR z is equivalent to (x AND (NOT y)) OR z. It’s wise to use
parentheses, rather than rely on the default evaluation order, to make the evaluation order clear.

25. If a method is declared as protected, where may the method be accessed?


A. A protected method will be accessed for all classes.
B. A protected method will be accessed only within the same package.
C. A protected method may only be accessed by classes or interfaces of the same package or by
subclasses of the class in which it is declared.
D. A protected method will be accessed only within the same class.

Answer:C

Explanation: Protected Access Modifier - Protected


Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by
the subclasses in other package or any class within the package of the protected members' class.

The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared
protected, however methods and fields in a interface cannot be declared protected.

Protected access gives the subclass a chance to use the helper method or variable, while preventing a
nonrelated class from trying to use it.

26. …………….. defines rules regarding the values allowed in columns and is the standard mechanism for
enforcing database integrity.
A. Constraint B. Column C. Trigger D. Index
Answer:A

Explanation:QL constraints are used to specify rules for the data in a table.

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.

27. The Linear sequential model of software development is _______


A. A useful approach when a customer cannot define requirements clearly.
B. An Old Fashioned model that cannot be used in a modern context.
C. A reasonable approach when requirement are well defined.
D. A good approach when a working program is required quickly

Answer:

28. The major advantage of bottom-up integration testing is _________.


A. no stubs need to be written
B. no drivers need to be written
C. major decision points are tested early
D. regression testing is not required
Answer:A

Explanation: Advantages of bottom up integration testing :

If the low level modules and their combined functions are often invoked by other modules, then it is more useful
to test them first so that meaningful effective integration of other modules can be done.

Appropriate for applications where bottom up design methodology is used.

Advantageous if major flaws occur towards the bottom of the program.

Test conditions are easier to create.

Observation of test results is easier.


Always starting at the bottom of the hierarchy again means that the critical modules are generally built and tested
first and therefore any errors or mistakes in these forms of modules are identified early in the process.

29. HTML is a subset of


A. SGMD B. SGMT C. SGML D. None of the above

Answer:C

Explanation:
HTML and XHTML are both subsets only of SGML, except that XHTML has additional specifications so that it
also validates as XML. Think of XML as XHTML's influential godfather.

Because of this relationship to SGML across all 3 of these languages, there are a lot of similarities, but they are
all considered different languages. However, much of what defines these languages is their restrictions on
SGML.

HTML restricts SGML by defining a list of tags that are allowed to be used.
XML restricts SGML by not allowing unclosed or empty start and end tags, and forces attributes to be explicit.
XML also has a large number of additional restrictions that are not found in SGML.
XHTML restricts SGML with the tags from HTML (with some exclusions, such as frameset, et al), and with
the tag and entity restrictions from XML.

30. The tag used to create a hypertext relationship between current document and another URL is
A. <A>
B. <LINK>
C. <ISINDEX>
D. None of the above

Answer:B

Explanation:For the most part, <LINK> is used to create an author-defined structure to other HTML
documents on a Web site. The attribute REL, for example, defines the relationship of the HREF URL to the
current document. Conversely, REV defines the relationship between the current document and the HREF'ed
URL

31. Which of the following are valid method declarations?


A. abstract void method(){}
B. final int method(){ return 10;}
C. abstract method(){}
D. abstract final void method(){}

Answer: B

Explanation: option A is incorrect because abstract methods cannot have a body

Option C is incorrect because any return is not mentioned


option D is incorrect because ,he following are various illegal combinations of other modifiers for methods
with respect to abstract modifier :
 final
 abstract native
 abstract synchronized
 abstract static
 abstract private
 abstract strictfp

32. A text is made up of the characters a, b, c, d, e each occurring with the probability .12, .4, .15, .08 and .25
respectively. The optimal coding technique will have the average length of
A. 3.01 B. 2.3 C. 2.15 D. 1.78

Answer:C

Explanation: Using Hoffman's algorithm, code for a is 1111; b is 0; c is 110; d is 1110; e is 10. Average code
length is
4 x.12 + 1 x .4 + 3 x.15 + 4 x.08 + 2 x.25 = 2.15

33. Which of the following is/are the DDL statements?


A. Create B. Drop C. Alter D. All of the above

Answer:D

Explanation: Data Definition Language (DDL) is a standard for commands that define the different structures in
a database. DDL statements create, modify, and remove database objects such as tables, indexes, and users.
Common DDL statements are CREATE, ALTER, and DROP.

Technical

Choose the best option


34. What is the postfix form of following prefix expression –A/B*C$DE
A. A-BCDE$*/
B. A-BCDE$*/-
C. ABC$ED*/-
D. ABCDE$*/-

Answer: D
Explanation:

Algorithm for Prefix to Postfix:


 Read the Prefix expression in reverse order (from right to left)
 If the symbol is an operand, then push it onto the Stack
 If the symbol is an operator, then pop two operands from the Stack
Create a string by concatenating the two operands and the operator after them.
string = operand1 + operand2 + operator
And push the resultant string back to Stack
 Repeat the above steps until end of Prefix expression.
For example:

Input: Prefix: *+AB-CD


Output: Postfix: AB+CD-*
Explanation:
Prefix to Infix: (A+B) * (C-D)
Infix to Postfix: AB+CD-*

35. What operator tests column for the absence of data?


A. NOT operator
B. IS NULL operator
C. EXISTS operator
D. None of these

Answer: B
Explanation:

Always use IS NULL to look for NULL values.


Syntax:
SELECT "column_name"
FROM "table_name"
WHERE "column_name" IS NULL

36. The language used in application programs to request data from the DBMS is referred to as
A. DDL
B. DML
C. Query Language
D. All of the above
Answer: A
Explanation:
The SQL commands that deals with the manipulation of data present in database belong to DML or Data
Manipulation Language and this includes most of the SQL statements.
Examples of DML:

SELECT – is used to retrieve data from the database.

37. Which keyword is used to call the constructors of the same class?
A. default
B. instance of
C. super
D. this

Answer: D
Explanation:

this ()is used to call one constructor from another; but condition is two constructors (calling and called) should
belong to the same class (not of super of class; for super class super() comes).

38. ___________________ is a type of software testing that intends to determine how a system performs in
terms of responsiveness and stability under a certain load.
A. Regression Testing
B. Smoke Testing
C. Performance Testing
D. None of the above

Answer: C
Explanation:
Software Performance testing is type of testing perform to determine the performance of system to major the
measure, validate or verify quality attributes of the system like responsiveness, Speed, Scalability, Stability under
variety of load conditions. The system is tested under a mixture of load conditions and check the time required
responding by the system under varying workloads.

39. Which of the following options is true about multi-level inheritance?


A. Inheriting from two super classes
B. Inheriting from a single class
C. Inheriting from a class which is already in an inheritance hierarchy
D. Inheriting from more than one super class

Answer: C
Explanation:

C++ Multilevel Inheritance


In C++ programming, not only you can derive a class from the base class but you can also derive a class from the
derived class. This form of inheritance is known as multilevel inheritance.

class A
{
... .. ...
};
class B: public A
{
... .. ...
};
class C: public B
{
... ... ...
};
Here, class B is derived from the base class A and the class C is derived from the derived class B.

40. Correct HTML tag for the largest heading is


A. <H6>
B. <Head>
C. <Heading>
D. <H1>

Answer: D
Explanation:

The <h1> to <h6> tags are used to define HTML headings.

<h1> defines the most important heading. <h6> defines the least important heading.

41. As part of the maintenance work, you are entrusted with the work of rearranging the library books in a shelf
in proper order, at the end of each day. The ideal choice will be
A. Selection sort
B. merge sort
C. insertion sort
D. bubble sort

Answer: C
Explanation:
Library sort, or gapped insertion sort is a sorting algorithm that uses an insertion sort, but with gaps in the array to
accelerate subsequent insertions. The name comes from an analogy:
Suppose a librarian were to store his books alphabetically on a long shelf, starting with the As at the left end, and
continuing to the right along the shelf with no spaces between the books until the end of the Zs. If the librarian
acquired a new book that belongs to the B section, once he finds the correct space in the B section, he will have to
move every book over, from the middle of the Bs all the way down to the Zs in order to make room for the new
book. This is an insertion sort. However, if he were to leave a space after every letter, as long as there was still space
after B, he would only have to move a few books to make room for the new one. This is the basic principle of the
Library Sort.

42. An algorithm is made up of 2 modules M1&M2. If order of M1 is f(n) & M2 is g(n) then the order of
algorithm is?
A. f(n) X g(n)
B. max (f(n),g(n))
C. min (f(n),g(n))
D. f(n) + g(n)

Answer: B
Explanation:
Out of f(n) and g(n), the module which contributes most towards the time complexity of the given algorithm will be
the order of given algorithm.

43. Coupling is a measure of


A. Both interdependence among module & Relative functional strength
B. Interdependence among module
C. Relative functional strength
D. None of the above

Answer: B
Explanation:

Coupling or dependency is the degree to which each program module relies on each one of the other modules.

44. Design phase includes


A. data, architectural and interface design only
B. data, architectural interface and procedural design
C. data, architectural and procedural designs only
D. architectural, procedural and interface design only

Answer: B
Explanation:

The Design Phase consists of the following:


 Choosing an appropriate Database Management System (DBMS)
 Establishing system security standards
 Interface Design
 Data Capture Requirements
 Standards for printed report production
 System navigation methods

45. Which of the following algorithms solves the all-pair shortest path problem?
A. Warshall’s
B. Dijkstra’s algorithm
C. Floyd’s algorithm
D. Prim’s algorithm

Answer: C
Explanation:

Dijkstra's algorithm solves single source shortest path problem. Warshall's algorithm finds transitive closure of a
given graph. Prim's algorithm constructs a minimum cost spanning tree for a given weighted graph.

46. Which of the following algorithm design technique is used in the quick sort algorithm?
A. Backtracking
B. Greedy method
C. Divide and conquer
D. Dynamic programming

Answer: C
Explanation:

Like Merge Sort, Quick Sort is a Divide and Conquer algorithm. It picks an element as
pivot and partitions the given array around the picked pivot.

47. The attribute name could be structured as an attribute consisting of first name, middle initial and last name.
This type of attribute is called
A. Multi valued attribute
B. Composite attribute
C. Simple attribute
D. Derived attribute

Answer: B
Explanation:

Composite attributes can be divided into subparts (that is, other attributes)

48. Which of the following are true about interfaces? Select the correct answers.
A. An interface can extend any number of interfaces.
B. Methods declared in interfaces are implicitly private.
C. The keyword implements indicate that an interface inherits from another.
D. Interfaces can’t have variables declared.

Answer: A
Explanation:
Yes, An interface can extend multiple interfaces. Any interface which extend more than one interface will have
property of all the interfaces it extends.

Here is a code, given in Java.

interface A{
public void test();
public void test1();
}
interface B{
public void test();
public void test2();
}
interface C extends A,B{
public void test3();
}
class D implements C{
@Override
public void test(){
System.out.println("Testing....");
}
@Override
public void test1(){
System.out.println("Testing....1");
}
@Override
public void test2(){
System.out.println("Testing....2");
}
@Override
public void test3(){
System.out.println("Testing....3");
}
}

public class Main{


public static void main(String[] args) {
D d=new D();
d.test();
d.test1();
d.test2();
d.test3();
}
}

49. The postfix form of the expression


(A+B)*(C*D-E)*F/G is
A. AB+CDE* -*F*G/
B. AB+CD * E-*F*G/
C. AB+CD * E-FG/**
D. AB+CD * E-F **G/
Answer: B
Explanation:
According to left to right associativity
(AB+)*(CD*E-)*F/G

(AB+)(CD*E-)**F/G
Multiplication will be executed first due to left-right associativity
so, (AB+)(CD*E-)*F* /G
(AB+)(CD*E-)*F*G/

50. WWW is based on which model?


A. 3 – tier
B. Client-Server
C. Local-Server
D. All of the above

Answer: B
Explanation:
The client–server model is a distributed application structure that partitions tasks or workloads between the
providers of a resource or service, called servers, and service requesters, called clients.

51. The concept of order (Big O) is important because


A. it determines the maximum size of a problem that can be solved in a given system , in a given amount of
time
B. it can be used to decide the best algorithm that solves a given problem
C. None of the above

Answer: B
Explanation:

We use big-O notation for asymptotic upper bounds, since it bounds the growth of the running time from above for
large enough input sizes.

52. Before launching software which testing is to be done in-house?


A. Alpha B. Beta C. Gamma D. None of the above
Answer: A
Explanation:
Alpha testing takes place at the developer's site by the internal teams, before release to external customers. This
testing is performed without the involvement of the development teams.

53. State True or False: In black box testing; only a small number of possible inputs can be tested and many
program paths will be left untested.
A. TRUE B. FALSE

Answer: A
Explanation:
Black box testing, which is also known as behavioral, opaque-box, closed-box, specification-based or eye-to-eye
testing, is a Software Testing method that analyses the functionality of a software/application without knowing
much about the internal structure/design of the item that is being tested and compares the input value with the
output value.

54. Which of the following is not a data definition language commands?


A. RENAME B. REVOKE C. UPDATE D. GRANT

Answer: C
Explanation:

RENAME: - With RENAME statement you can rename a table.


REVOKE: - The REVOKE command removes user access rights or privileges to the database objects.
GRANT: - In SQL GRANT is a command used to provide access or privileges on the database objects to the
users.
UPDATE: - The UPDATE Statement is used to modify the existing rows in a table.

RENAME, REVOKE and GRANT are DDL (Data Definition Language) commands and UPDATE is
DML(Data Manipulation Language) command.

55. An important benefit of code inspections is that they:


A. enable the code to be tested before the execution environment is ready.
B. are cheap to perform.
C. can be performed by the person who wrote the code.
D. can be performed by inexperienced staff.

Answer: A
Explanation:

Code Inspection is the most formal type of review, which is a kind of static testing to avoid the defect multiplication
at a later stage. The main purpose of code inspection is to find defects and it can also spot any process improvement
if any.

56. ………………joins two or more tables based on a specified column value not equaling a specified column
value in another table.
A. NON-EQUI JOIN
B. NATURAL JOIN
C. EQUIJOIN
D. OUTER JOIN

Answer: A
Explanation:

SQL Non equi joins


It is a sql join condition which makes use of some comparison operator other than the equal sign like >, <, >=,
<=

57. Which of the tag is used to create a number list?


A. <UL> B. <LL> C. <AL> D. <OL>

Answer: D
Explanation:
Ordered HTML List

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.

The list items will be marked with numbers by default. Ordered HTML List - The Type Attribute

The type attribute of the <ol> tag, defines the type of the list item marker:

Type Description

type="1" The list items will be numbered with numbers (default)

type="A" The list items will be numbered with uppercase letters

type="a" The list items will be numbered with lowercase letters

type="I" The list items will be numbered with uppercase roman numbers

type="i" The list items will be numbered with lowercase roman numbers

58. int i = Integer.MAX_VALUE + 10;


What is the result of executing the line of code above?
A. An Arithmetic Exception is thrown.
B. The value of “i” becomes a negative number.
C. The value of “i” becomes the “NaN” Not a Number constant.
D. The result is undefined.

Answer: A
Explanation:
Integer cannot take value greater than Integer.MAX_VALUE. The statement above will be evaluated as
2147483647+ 10 > Integer.MAX_VALUE. Therefore, it will throw an arithmetic exception.

Part-2

1. Write a MS SQL query to display:


To find Title and Book_Desc of all the books for which the orders are placed.
Your output should contain 2 columns in the below-mentioned order:
Title Book_Des
c
You can view the database schema by clicking the View Schema tab at the bottom of the query window on the
right-hand side of the screen.

2. Write an Oracle query to display:


The employee ID, employee name and total leave for the employee with employee ID ‘E002’ (use “Total
Leaves” as alias)
Your output should contain 3 columns in the below mentioned order.
EMPID EMPNAME Total_Leaves
You can view the database scheme by clicking the View Schema tab at the bottom of the query window on the
right-hand side of the screen.

3. Write a MS SQL query to display:


The first name (use : ‘Fname’) and the last name (use alias : ‘Lname’) of all customer s that have city ‘Texas’ in
their address.
Your output should contain 2 columns in the below-mentioned order.

Fname Lname

4. Write a query to find the train name and type description of all trains running between 0600 hours and 1800
hours.
Your output should contain 2 columns in the below mentioned order.
train_name type_description

Anagrams
5.
An anagram is a word, phrase, or name formed by rearranging the letters of another word, phrase, or name.
Write a function to check if two given strings are anagrams or not. Return “yes” if they are anagrams, otherwise
return “no”.
Input Specification:
input 1: the first string
input 2: the second string
Output Specification:
Return “yes” if they are anagrams, otherwise return “no”.
Example 1:
input 1: build
input 2: dubli
Output: yes
Example 2:
input 1: beast
input 2: yeast
Output: no
Explanation:

Below is a solution to check if two strings are k-anagrams of each other or not.
1. Stores occurrence of all characters of both strings in separate count arrays.
2. Count number of different characters in both strings (in this if a strings has 4 a and second has 3 ‘a’ then it
will be also count.
3. If count of different characters is less than or equal to k, then return true else false.

// Optimized C++ program to check if two strings


// are k anagram or not.
#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;

// Function to check if str1 and str2 are k-anagram


// or not
bool areKAnagrams(string str1, string str2, int k)
{
// If both strings are not of equal
// length then return false
int n = str1.length();
if (str2.length() != n)
return false;

int hash_str1[MAX_CHAR] = {0};

// Store the occurrence of all characters


// in a hash_array
for (int i = 0; i < n ; i++)
hash_str1[str1[i]-'a']++;

// Store the occurrence of all characters


// in a hash_array
int count = 0;
for (int i = 0; i < n ; i++)
{
if (hash_str1[str2[i]-'a'] > 0)
hash_str1[str2[i]-'a']--;
else
count++;

if (count > k)
return false;
}

// Return true if count is less than or


// equal to k
return true;
}

// Driver code
int main()
{
string str1 = "fodr";
string str2 = "gork";
int k = 2;
if (areKAnagrams(str1, str2, k) == true)
cout << "Yes";
else
cout << "No";
return 0;
}
String within String
6.
Given two strings, ‘X’ and ‘Y’ (1 <= length(X), length(Y) <= 10000), find out if ‘Y’ is contained in ‘X’. Output
“yes”, if ‘Y’ is contained in ‘X’, “no”, if not.
Input
input1: the string ‘X’
input2: the string ‘Y’
Output
Return “yes” or “no” accordingly.
Example
Input: abac, bc
Output: yes
!
Explanation:

The idea is simple; we traverse both strings from one side to other side (say from rightmost character to leftmost). If
we find a matching character, we move ahead in both strings. Otherwise we move ahead only in str2.
// Iterative C++ program to check if a string is subsequence of another string
#include<iostream>
#include<cstring>
using namespace std;

// Returns true if str1[] is a subsequence of str2[]. m is


// length of str1 and n is length of str2
bool isSubSequence(char str1[], char str2[], int m, int n)
{
int j = 0; // For index of str1 (or subsequence

// Traverse str2 and str1, and compare current character


// of str2 with first unmatched char of str1, if matched
// then move ahead in str1
for (int i=0; i<n&&j<m; i++)
if (str1[j] == str2[i])
j++;

// If all characters of str1 were found in str2


return (j==m);
}

// Driver program to test methods of graph class


int main()
{
char str1[] = "gksrek";
char str2[] = "geeksforgeeks";
int m = strlen(str1);
int n = strlen(str2);
isSubSequence(str1, str2, m, n)? cout << "Yes ":
cout << "No";
return 0;
}

7. Longest Common Subsequence


Given two strings. ‘X’ and ‘y’ (1<=length(x), length(y) <=1000), find the length of their Longest Common
Subsequence (LCS). The strings contains only lowercase letters.
You need to fill in a function that takes as input two strings and sets the output variable to the length of their
LCS.
Input
input 1: the string ‘x’
input 2: the string ‘y’
Output
Return the length of the LCS of ‘x’ and ‘y’
Example:
Input: aba, ababa
Output: 3
!
Explanation:

/* Dynamic Programming C/C++ implementation of LCS problem */


#include<bits/stdc++.h>

int max(int a, int b);

/* Returns length of LCS for X[0..m-1], Y[0..n-1] */


int lcs( char *X, char *Y, int m, int n )
{
int L[m+1][n+1];
int i, j;

/* Following steps build L[m+1][n+1] in bottom up fashion. Note


that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */
for (i=0; i<=m; i++)
{
for (j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;

else if (X[i-1] == Y[j-1])


L[i][j] = L[i-1][j-1] + 1;

else
L[i][j] = max(L[i-1][j], L[i][j-1]);
}
}

/* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */


return L[m][n];
}

/* Utility function to get max of 2 integers */


int max(int a, int b)
{
return (a > b)? a : b;
}
/* Driver program to test above function */
int main()
{
char X[] = "AGGTAB";
char Y[] = "GXTXAYB";

int m = strlen(X);
int n = strlen(Y);

printf("Length of LCS is %d", lcs( X, Y, m, n ) );

return 0;
}
Drive Name: PERSISTENT SYSTEM
Book Index: 150

TECHNICAL INTERVIEW

1. Write a program of factorial

Answer: Refer to question no. 1 above

2. Write a program of swapping


Answer:
Example 1: Swap Numbers (Using Temporary Variable)
#include <iostream>
using namespace std;

int main()
{
int a = 5, b = 10, temp;

cout << "Before swapping." << endl;


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

temp = a;
a = b;
b = temp;

cout << "\nAfter swapping." << endl;


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

return 0;
}

Output

Before swapping.
a = 5, b = 10

After swapping.
a = 10, b = 5
Company Name: - WIPRO
Book Index: 166- (C)

1. What is stream?
Ans: Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects
that supports various methods which can be pipelined to produce the desired result.
The features of Java stream are –
 A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
 Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
 Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate
operations can be pipelined. Terminal operations mark the end of the stream and return the result.

2. What do you understand by multiple inheritance?


Ans:

In multiple inheritance, a class can inherit from more than one classes. In simple words, a class can have more than
one parent classes. This type of inheritance is not present in Java.

Suppose we have to make two classes A and B as the parent classes of class C, then we have to define class C as
follows.

class C: public A, public B


{
// code
};

3. Define character arrays.


Ans: alue. An array is defined as a finite collection of homogeneous data, stored in contiguous memory locations.
A string is a sequence of characters treated as a single entity and is terminated by a null character (‘\0’).

C language however doesn’t support string as a data type. We can implement strings as array of characters.

Declaration and initialization:

1. char arr[12]= “hello world”;

Here size of the array is 12 including a ‘\0’ character automatically added to the end of the string by the compiler.

4. Databases
Ans: Database is a systematic collection of data. Databases support storage and manipulation of data. Databases
make data management easy. Let's discuss few examples.

An online telephone directory would definitely use database to store data pertaining to people, phone numbers,
other contact details, etc.

Your electricity service provider is obviously using a database to manage billing , client related issues, to handle
fault data, etc.

There are 4 major types of DBMS. Let's look into them in detail.

 Hierarchical - this type of DBMS employs the "parent-child" relationship of storing data. This type of
DBMS is rarely used nowadays. Its structure is like a tree with nodes representing records and branches
representing fields. The windows registry used in Windows XP is an example of a hierarchical database.
Configuration settings are stored as tree structures with nodes.
 Network DBMS - this type of DBMS supports many-to many relations. This usually results in complex
database structures. RDM Server is an example of a database management system that implements the
network model.
 Relational DBMS - this type of DBMS defines database relationships in form of tables, also known as
relations. Unlike network DBMS, RDBMS does not support many to many relationships.Relational
DBMS usually have pre-defined data types that they can support. This is the most popular DBMS type in
the market. Examples of relational database management systems include MySQL, Oracle, and
Microsoft SQL Server database.
 Object Oriented Relation DBMS - this type supports storage of new data types. The data to be stored is
in form of objects. The objects to be stored in the database have attributes (i.e. gender, ager) and
methods that define what to do with the data. PostgreSQL is an example of an object oriented relational
DBMS.

5. Try and catch Block


Ans: "Try" and "catch" are keywords that represent the handling of exceptions due to data or coding errors
during program execution. A try block is the block of code in which exceptions occur. A catch block catches
and handles try block exceptions.

The try/catch statement is used in many programming languages, including C programming language (C++
and C#), Java, JavaScript and Structured Query Language (SQL).

6. Lambda expression
Ans: Lambda expression is a new feature which is introduced in Java 8. A lambda expression is an anonymous
function. A function that doesn’t have a name and doesn’t belong to any class. The concept of lambda expression
was first introduced in LISP programming language.

Java Lambda Expression Syntax:To create a lambda expression, we specify input parameters (if there are any) on
the left side of the lambda operator ->, and place the expression or block of statements on the right side of lambda
operator. For example, the lambda expression (x, y) -> x + y specifies that lambda expression takes two arguments x
and y and returns the sum of these.

//Syntax of lambda expression


(parameter_list) -> {function_body}
Lambda expression vs method in Java
A method (or function) in Java has these main parts:
1. Name
2. Parameter list
3. Body
4. return type.

A lambda expression in Java has these main parts:


Lambda expression only has body and parameter list.
1. No name – function is anonymous so we don’t care about the name
2. Parameter list
3. Body – This is the main part of the function.
4. No return type – The java 8 compiler is able to infer the return type by checking the code. you need not to mention
it explicitly.

7. HTML tags
Ans: There are tow types of tags:

1. Paired Tags
2. Unpaired Tags
A paired tag consist of two tags, first one is called an opening tag and the second one is called a closing tag. These
tags contains the text in between at which the effect of that tag will be applied.
Example: <b>ABC</b>
Here <b> is the opening tag, </b> is the closing tag and ABC the text in between which will result as ABC on the
browser screen.

More Examples:

 <i> </i>
 <div> </div>
 <ul> </ul>
 <h1> </h1> , etc.
An Unpaired tag is a single tag which does not need a companion tag.
These tags can be written like < > or < /> both works as same, it’s your choice which style you choose.
Example:

 <br> or <br />


 <hr> or <hr />

8. Basics of Java
Ans: Java is a programming language that produces software for multiple platforms. When a programmer
writes a Java application, the compiled code (known as bytecode) runs on most operating systems (OS),
including Windows, Linux and Mac OS. Java derives much of its syntax from the C and C++ programming
languages.

Java was developed in the mid-1990s by James A. Gosling, a former computer scientist with Sun
Microsystems.

9. What is the difference between final, finally and finalize in java?

Ans: There are many differences between final, finally and finalize. A list of differences between final, finally and
finalize are given below:
No. final finally finalize

1) Final is used to apply restrictions on Finally is used to place Finalize is used to


class, method and variable. Final class important code, it will be perform clean up
can't be inherited, final method can't be executed whether processing just before
overridden and final variable value can't exception is handled or object is garbage
be changed. not. collected.

2) Final is a keyword. Finally is a block. Finalize is a method.

10. What are the differences between C++ and Java?


Ans: C++ was designed for system and application programming whereas Java is designed to minimize
implementation dependencies. Java relies on a JVM to be secure and highly portable whereas c++ runs as native
executable machine code for the target instruction set.

Other differences:

 C++ is WOCA(write once compile anywhere) whereas java is (WORA/WORE) write once run
anywhere/everywhere.
 C++ is platform dependent and java is platform independent. (C++ uses compiler only. C++ is
compiled and run using a compiler which converts source code into machine code so, c++ is platform
dependent. Java uses compiler and interpreter. Java source code is compiled into bytecode at compiltaion
time. The interpreter executes the bytecode at runtime and produces output. Java is interpreted thus it is
platform independent.)
 C++ support both call by value and call by reference. Java support call by value only.
 You can write pointer program in c++. Java support pointer internally. But you can't write the pointer
program in java.
 C++ supports structure and union. (Java does not)
 C++ does not have built-in support for threads. Java has built-in thread support.
 C++ creates new inheritance tree always. Java uses single inheritance tree always because all classes
are child of object class in java. Object class is the root of inheritance tree in java.
 Memory management in c++ is done via constructors, destructors and smart pointers. Java offers
automatic garbage collection.
 C++ can allocate arbitrary blocks of memory. Java only allocates memory via object instantiation.
Arbitrary memory blocks may be allocated in Java as an array of bytes
 C++ has destructors, while Java has finalizers. Both are invoked before an object's deallocation, but
they differ significantly. A C++ object's destructor must be invoked implicitly (in the case of stack-bound
variables) or explicitly to deallocate an object. The destructor executes synchronously just before the point
in a program at which an object is deallocated. Synchronous, coordinated uninitializing and deallocating
in C++ thus satisfy the RAII idiom. In Java, object deallocation is implicitly handled by the garbage
collector. A Java object's finalizer is invoked asynchronously some time after it has been accessed for the
last time and before it is deallocated. Very few objects need finalizers. A finalizer is needed by only
objects that must guarantee some cleanup of the object state before deallocating, typically releasing
resources external to the JVM.
 Java has generics, which main purpose is to provide type-safe containers. C++ has compile-time
templates, which provide more extensive support for generic programming and metaprogramming. Java
has annotations, which allow adding arbitrary custom metadata to classes and metaprogramming via an
annotation processing tool.
 C++ provides low-level features which Java lacks. In C++, pointers can be used to manipulate specific
memory locations, a task necessary for writing low-level operating system components. Similarly, many
C++ compilers support an inline assembler. Assembly language codes can be imported to a C program
and vice versa. This makes C language even faster. In Java, such code must reside in external libraries,
and can only be accessed via the Java Native Interface, with a significant overhead for each.

11. What happens when a thrown exception is not handled?

Ans: Java has two different types of exceptions: checked Exceptions and unchecked Exceptions.
Unchecked exceptions are subclasses of RuntimeException and you don't have to add a throws declaration. All
other exceptions have to be handled in the method body, either with a try/catch statement or with a throws
declaration.
Example for unchecked exceptions: IllegalArgumentException that is used sometimes to notify, that a
method has been called with illegal arguments. No throws needed.
Example for checked exceptions: IOException that some methods from the java.io package might throw.
Either use a try/catch or add throws IOException to the method declaration and delegate exception handling to
the method caller.

12. What are various concepts of OOPs?


Ans: Object oriented programming – As the name suggests uses objects in programming. Object oriented
programming aims to implement real world entities like inheritance, hiding, polymorphism etc in programming. The
main aim of OOP is to bind together the data and the functions that operates on them so that no other part of code
can access this data except that function.
Object: Objects are basic run-time entities in an object oriented system, objects are instances of a class these are
defined user defined data types.
ex:
class person
{
char name[20];
int id;
public:
void getdetails(){}
};

int main()
{
person p1; //p1 is a object
}

Object take up space in memory and have an associated address like a record in pascal or structure or union in C.
When a program is executed the objects interact by sending messages to one another.
Each object contains data and code to manipulate the data. Objects can interact without having to know details of
each others data or code, it is sufficient to know the type of message accepted and type of response returned by the
objects.
Class: Class is a blueprint of data and functions or methods. Class does not take any space.
Syntax for class:
class class_name
{
private:
//data members and member functions declarations
public:
//data members and member functions declarations
protected:
//data members and member functions declarations
};
Class is a user defined data type like structures and unions in C.
By default class variables are private but in case of structure it is public. in above example person is a class.
Encapsulation and Data abstraction: Wrapping up(combing) of data and functions into a single unit is known as
encapsulation. The data is not accessible to the outside world and only those functions which are wrapping in the
class can access it. This insulation of the data from direct access by the program is called data hiding or information
hiding.
Data abstraction refers to, providing only needed information to the outside world and hiding implementation
details. For example, consider a class Complex with public functions as getReal() and getImag(). We may implement
the class as an array of size 2 or as two variables. The advantage of abstractions is, we can change implementation at
any point, users of Complex class wont’t be affected as out method interface remains same. Had our implementation
be public, we would not have been able to change it.
Inheritance: inheritance is the process by which objects of one class acquire the properties of objects of another
class. It supports the concept of hierarchical classification. Inheritance provides re usability. This means that we can
add additional features to an existing class without modifying it.
Polymorphism: polymorphism means ability to take more than one form. An operation may exhibit different
behaviors in different instances. The behavior depends upon the types of data used in the operation.
C++ supports operator overloading and function overloading.
Operator overloading is the process of making an operator to exhibit different behaviors in different instances is
known as operator overloading.
Function overloading is using a single function name to perform different types of tasks.
Polymorphism is extensively used in implementing inheritance.
Dynamic Binding: In dynamic binding, the code to be executed in response to function call is decided at runtime.
C++ has virtual functions to support this.
Message Passing: Objects communicate with one another by sending and receiving information to each other. A
message for an object is a request for execution of a procedure and therefore will invoke a function in the receiving
object that generates the desired results. Message passing involves specifying the name of the object, the name of the
function and the information to be sent.
13. JDBC
Ans:
Java Database Connectivity (JDBC) is an application programming interface (API) for the programming
language Java, which defines how a client may access a database. It is a Java-based data access technology used for
Java database connectivity. It is part of the Java Standard Edition platform, from Oracle Corporation. It provides
methods to query and update data in a database, and is oriented towards relational databases. A JDBC-to-
ODBC bridge enables connections to any ODBC-accessible data source in the Java virtual machine (JVM) host
environment.

14. What are classes and objects?


Ans: Class: A class is a user defined blueprint or prototype from which objects are created. It represents the set of
properties or methods that are common to all objects of one type. In general, class declarations can include these
components, in order:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A
class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the
keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that provides the state of the class and its
objects, and methods are used to implement the behavior of the class and its objects.
Object: It is a basic unit of Object Oriented Programming and represents the real life entities. A typical Java
program creates many objects, which as you know, interact by invoking methods. An object consists of :
1. State : It is represented by attributes of an object. It also reflects the properties of an object.
2. Behavior : It is represented by methods of an object. It also reflects the response of an object with other
objects.
3. Identity : It gives a unique name to an object and enables one object to interact with other objects.
Example of an object : dog

15. How stack and heap are different?


16. Ans: 1) Both stack and heap are stored in memory(RAM). In multithread each thread have it's own stack
whereas different thread share heap.
2) One of the big difference between stack and heap is size , stack size is fixed i.e. we get stackoverflow
error , whereas heap size is operated by OS and can be change according to the needs.
3) Stack is much faster than a heap . Since in stack memory allocation is easy and moving the stack pointer
up.
4) For programming purpose , it's better to use stack rather than heap bcz it's easier to allocate memory on
stack.
If size of data is small use stack if not use heap .

17. State the differences between overloading and overriding.


Ans:

1. Overloading happens at compile-time while Overriding happens at runtime: The binding of overloaded
method call to its definition has happens at compile-time however binding of overridden method call to its
definition happens at runtime.
2. Static methods can be overloaded which means a class can have more than one static method of same name.
Static methods cannot be overridden, even if you declare a same static method in child class it has nothing to do
with the same method of parent class.
3. The most basic difference is that overloading is being done in the same class while for overriding base and
child classes are required. Overriding is all about giving a specific implementation to the inherited method of
parent class.
4. Static binding is being used for overloaded methods and dynamic binding is being used for
overridden/overriding methods.
5. Performance: Overloading gives better performance compared to overriding. The reason is that the binding
of overridden methods is being done at runtime.
6. private and final methods can be overloaded but they cannot be overridden. It means a class can have more
than one private/final methods of same name but a child class cannot override the private/final methods of their
base class.
7. Return type of method does not matter in case of method overloading, it can be same or different. However
in case of method overriding the overriding method can have more specific return type (refer this).
8. Argument list should be different while doing method overloading. Argument list should be same in method
Overriding.

TECHNICAL (Computer Programming)

Automata
Direction: 1-2 The current selected programming language is C. we emphasize the submission of a fully
working code over partially correct but efficient code. Once submitted, you cannot review this problem again.
You can use printf() to debug your code. The printf() may not work in case of syntax/runtime error. The version
of GCC being used is 5.2.0.
1. A sequence of parentheses is called balanced if it consists entirely of pairs of opening/closing parentheses
(in that order), which is well nested. For example, sequences "(())()" , "()" and "(()(()))" are balanced,
while "(()" and "(()))(" are not.
Write a function to determine if a given string contains balanced sequence of parentheses. The input to the
function balancedParentheses is a string str. Each character in the string will be "(" or ")". The output is
the count of balanced pairs if the sequence is balanced or -1 otherwise.
For example, if the input sequence is "(()(()))", the expected output is 4.

Solutions:
Algorithm:
1) Declare a character stack S.
2) Now traverse the expression string exp.
a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character
is the matching starting bracket then fine and increment the static count else parenthesis are not balanced.
3) After complete traversal, if there is some starting bracket left in stack then “not balanced”

// function to check if paranthesis are balanced


static count;
boolareParanthesisBalanced(string expr)
{
stack<char> s;
char x;

// Traversing the Expression


for (inti=0; i<expr.length(); i++)
{
if (expr[i]=='('||expr[i]=='['||expr[i]=='{')
{
// Push the element in the stack
s.push(expr[i]);
count ++;
continue;
}

// IF current current character is not opening


// bracket, then it must be closing. So stack
// cannot be empty at this point.
if (s.empty())
return false;

switch (expr[i])
{
case ')':

// Store the top element in a


x = s.top();
s.pop();
if (x=='{' || x=='[')
return false;
break;

case '}':
// Store the top element in b
x = s.top();
s.pop();
if (x=='(' || x=='[')
return false;
break;

case ']':

// Store the top element in c


x = s.top();
s.pop();
if (x =='(' || x == '{')
return false;
break;
}
}

// Check Empty Stack


return (s.empty());
}

// Driver program to test above function


int main()
{
stringexpr = "{()}[]";

if (areParanthesisBalanced(expr))
cout<< "Balanced"<<count;
else
cout<< "Not Balanced";
return 0;
}

2. Design a way to sort the list of positive integers in the descending order according to frequency of the
elements. The elements with higher frequency come before those with lower frequency. Elements with the
same frequency come in the same order as they appear in the given list.
Input
The input to the function/method consists of two arguments -
arr, a list of positive integers.
size, the number elements in the array.
Output
Return a list of positive integers sorted according to the frequency of elements present in arr.
Example
Input:
size = 19
arr = [1,2,2,3,3,3,4,4,5,5,5,5,6,6,6,7,8,9,10]
Output:
[5,5,5,5,3,3,3,6,6,6,2,2,4,4,1,7,8,9,10]

solution:
Algorithm :
1) Use a sorting algorithm to sort the elements O(nlogn)
2) Scan the sorted array and construct a 2D array of element and count O(n).
3) Sort the 2D array according to count O(nlogn).
Example:

Input 2 5 2 8 5 6 8 8

After sorting we get


2 2 5 5 6 8 88

Now construct the 2D array as


2, 2
5, 2
6, 1
8, 3

Sort by count
8, 3
2, 2
5, 2
6, 1
How to maintain order of elements if frequency is same?
The above approach doesn’t make sure order of elements if frequency is same. To handle this, we should use
indexes in step 3, if two counts are same then we should first process(or print) the element with lower index. In
step 1, we should store the indexes instead of elements.

Input 5 22 8 5 6 8 8

After sorting we get


Element 2 2 5 5 6 8 88
Index 1 2 0 4 5 3 6 7

Now construct the 2D array as


Index, Count
1, 2
0, 2
5, 1
3, 3

Sort by count (consider indexes in case of tie)


3, 3
0, 2
1, 2
5, 1

Print the elements using indexes in the above 2D array.


// Sort elements by frequency. If two elements have same
// count, then put the elements that appears first
#include<bits/stdc++.h>
using namespace std;

// Used for sorting


structele
{
int count, index, val;
};

// Used for sorting by value


boolmycomp(structele a, structele b) {
return (a.val<b.val);
}

// Used for sorting by frequency. And if frequency is same,


// then by appearance
bool mycomp2(structele a, structele b) {
if (a.count != b.count) return (a.count<b.count);
else return a.index>b.index;
}

voidsortByFrequency(intarr[], int n)
{
structele element[n];
for (inti = 0; i< n; i++)
{
element[i].index = i; /* Fill Indexes */
element[i].count = 0; /* Initialize counts as 0 */
element[i].val = arr[i]; /* Fill values in structure
elements */
}

/* Sort the structure elements according to value,


we used stable sort so relative order is maintained. */
stable_sort(element, element+n, mycomp);

/* initialize count of first element as 1 */


element[0].count = 1;

/* Count occurrences of remaining elements */


for (inti = 1; i< n; i++)
{
if (element[i].val == element[i-1].val)
{
element[i].count += element[i-1].count+1;

/* Set count of previous element as -1 , we are


doing this because we'll again sort on the
basis of counts (if counts are equal than on
the basis of index)*/
element[i-1].count = -1;

/* Retain the first index (Remember first index


is always present in the first duplicate we
used stable sort. */
element[i].index = element[i-1].index;
}

/* Else If previous element is not equal to current


so set the count to 1 */
else element[i].count = 1;
}
/* Now we have counts and first index for each element so now
sort on the basis of count and in case of tie use index
to sort.*/
stable_sort(element, element+n, mycomp2);
for (inti = n-1, index=0; i>= 0; i--)
if (element[i].count != -1)
for (int j=0; j<element[i].count; j++)
arr[index++] = element[i].val;
}

// Driver program
int main()
{
intarr[] = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8};
int n = sizeof(arr)/sizeof(arr[0]);

sortByFrequency(arr, n);

for (inti=0; i<n; i++)


cout<<arr[i] << " ";
return 0;
}
Drive Name: VMWare
Book Index: 123 (C)
Technical interview questions
1. Basics of Windows and Linux operating systems

Ans:

 Linux is free and open source operating system whereas Windows is a commercial operating
system whose source code is inaccessible.

 Windows is not customizable as against Linux is customizable and a user can modify the code and
can change its the look and feel.

 Linux provides high security than windows because Linux is open source.

 Windows must boot from the primary partition. In contrast, there is no such constraint in Linux it
can be booted from either primary or logical partition.

 The separation of the directories is done using a backslash in windows. On the other hand, in Linux,
these are separated by using forward slash.

 In Linux, file names are case sensitive while windows file name are case-insensitive.

2. Describe Network protocols.


Ans: TCP/IP (Transmission Control Protocol/Internet Protocol): The Internet Protocol Suite (commonly known
as TCP/IP) is the set of communications protocols used for the Internet and other similar networks. The
Internet Protocol Suite, like many protocol suites, may be viewed as a set of layers.
ARP (Address Resolution Protocol): ARP is used for mapping a network address (e.g. an IPv4 address) to a
physical address like an Ethernet address (also named a MAC address).
DHCP (Dynamic Host Configuration Protocol): This is a protocol that is used to assist users to configure
multiple network devices from a single source.
DNS (Domain Name System): It converts the IPaddress to domain name.
HTTP (Hyper Text Transfer Protocol): This was the initial protocol that were used to access web
content, because of its security vulnerabilities it was replaced by HTTPS.
ICMP (Internet Control Message Protocol): Internet Control Message Protocol (ICMP) provides feedback
that you can use for diagnostics or to report logical errors. The most common ICMP type is the ping.
3. What is Windows registry?
Ans: Whenever a user installs a software, a hardware or a device driver for a newly connected hardware in
a Windows based computer system, the initial configuration settings of these are stored as keys and values
in a system defined, central hierarchical database repository called Windows Registry. During the usage of
the software or the hardware, the changes made to these configurations are updated in the registry. Also,
the changes made to Control Panel settings, file associations, Windows components and so on, during the
use of the computer, are updated in the registry.
4. Discuss your academic projects in detail.
Ans: Depends on Student’s Feedback
5. What are layers in OSI model?

Ans:

 Layer 7: Application layer


 Layer 6: Presentation layer.
 Layer 5: Session layer.
 Layer 4: Transport layer.
 Layer 3: Network layer.
 Layer 2: Data-link layer.
 Layer 1: Physical layer.

6. What is stop and wait protocol?


Ans: It is the simplest automatic repeat-request (ARQ) mechanism. A stop-and-wait ARQ sender sends one
frame at a time; it is a special case of the general sliding window protocol with transmit and receive
window sizes equal to one and greater than one respectively. After sending each frame, the sender doesn't
send any further frames until it receives an acknowledgement (ACK) signal. After receiving a valid frame,
the receiver sends an ACK. If the ACK does not reach the sender before a certain time, known as the
timeout, the sender sends the same frame again. The timeout countdown is reset after each frame
transmission.
7. Differentiate between Hub. Switch and Router?
Ans:
Hub
A hub is the simplest of these devices. Any data packet coming from one port is sent to all other ports. It is
then up to the receiving computer to decide if the packet is for it.
The biggest problem with hubs is their simplicity. Since every packet is sent out to every computer on the
network, there is a lot of wasted transmission. This means that the network can easily become bogged
down. Hubs are typically used on small networks where the amount of data going across the network is
never very high.
Switch
Switches are modern bridges by another name. It acts as multiport bridge to connect devices or segments
in a LAN. It operates at data link layer. It is an intelligent device. It uses MAC table to find the correct
destination.
Router
Routers are devices that connect two or more networks. It operates at network layer. They consist of a
combination of hardware and software.
The hardware can be a network server, a separate computer or a special device. The software in a router are
the operating system and the routing protocol.

8. What is DHCP, how does it work?


Ans: Dynamic Host Configuration Protocol (DHCP) is a network protocol that enables a server to
automatically assign an IP address to a computer from a defined range of numbers ( scope) configured for a
given network. A DHCP server provides this information to a DHCP client through the exchange of a
series of messages, known as the DHCP conversation or the DHCP transaction.

How DHCP Work?


DHCP discovery
The client computers broadcasts messages on the physical subnet to discover available DHCP servers. This
client-computers creates a User Datagram Protocol (UDP) packet with the default broadcast destination of
255.255.255.255 or the specific subnet broadcast address if any configured.
DHCP offer
When a DHCP server receives an IP lease request from a client, it reserves an IP address for the client and
extends an IP lease offer by sending a DHCPOFFER message to the client. This message contains the
client's MAC address, the IP address that the server is offering, the subnet mask, the lease duration, and the
IP address of the DHCP server making the offer.
DHCP request
In most companies, two DHCP servers provide fault tolerance of IP addressing if one server fails or must
be taken offline for maintenance. So client could receive DHCP offers from multiple servers, but it will
accept only one DHCP offer. In response to the offer Client requests the server. The client replies DHCP
Request, unicast to the server, requesting the offered address. DHCP acknowledgement
When the DHCP server receives the DHCPREQUEST message from the client, the configuration process
enters its final phase.
Company Name: - INFORMATICA Placement Drive

Book Index: 167-(D)

TECHNICAL INTERVIEW QUESTION

18. Write all the operations of stack. Now assume you have all these functions, using this, find out the
Maximum and Minimum in the stack.

Ans: An approach is discussed that supports minimum with O(1) extra space. We define a variable minEle that stores
the current minimum element in the stack. Now the interesting part is, how to handle the case when minimum
element is removed. To handle this, we push “2x – minEle” into the stack instead of x so that previous minimum
element can be retrieved using current minEle and its value stored in stack. Below are detailed steps and explanation
of working.
Push(x) : Inserts x at the top of stack.

 If stack is empty, insert x into the stack and make minEle equal to x.
 If stack is not empty, compare x with minEle. Two cases arise:
 If x is greater than or equal to minEle, simply insert x.
 If x is less than minEle, insert (2*x – minEle) into the stack and make minEle equal to x. For
example, let previous minEle was 3. Now we want to insert 2. We update minEle as 2 and insert 2*2 – 3 =
1 into the stack.
Pop() : Removes an element from top of stack.
 Remove element from top. Let the removed element be y. Two cases arise:
 If y is greater than or equal to minEle, the minimum element in the stack is still minEle.
 If y is less than minEle, the minimum element now becomes (2*minEle – y), so update (minEle =
2*minEle – y). This is where we retrieve previous minimum from current minimum and its value in stack.
For example, let the element to be removed be 1 and minEle be 2. We remove 1 and update minEle as 2*2
– 1 = 3.
Important Points:
 Stack doesn’t hold actual value of an element if it is minimum so far.
 Actual minimum element is always stored in minEle
Illustration
Push(x)

 Number to be Inserted: 3, Stack is empty, so insert 3 into


stack and minEle = 3.
 Number to be Inserted: 5, Stack is not empty, 5> minEle,
insert 5 into stack and minEle = 3.
 Number to be Inserted: 2, Stack is not empty, 2< minEle,
insert (2*2-3 = 1) into stack and minEle = 2.
 Number to be Inserted: 1, Stack is not empty, 1< minEle,
insert (2*1-2 = 0) into stack and minEle = 1.
 Number to be Inserted: 1, Stack is not empty, 1 = minEle,
insert 1 into stack and minEle = 1.
 Number to be Inserted: -1, Stack is not empty, -1 <
minEle, insert (2*-1 – 1 = -3) into stack and minEle = -1.
Pop()

 Initially the minimum element minEle in the stack is -1.


 Number removed: -3, Since -3 is less than the minimum element the original number being removed is
minEle which is -1, and the new minEle = 2*-1 – (-3) = 1
 Number removed: 1, 1 == minEle, so number removed is 1 and minEle is still equal to 1.
 Number removed: 0, 0< minEle, original number is minEle which is 1 and new minEle = 2*1 – 0 = 2.
 Number removed: 1, 1< minEle, original number is minEle which is 2 and new minEle = 2*2 – 1 = 3.
 Number removed: 5, 5> minEle, original number is 5 and minEle is still 3

19. Difference between Binary Tree and Binary search Tree.

Ans: Binary Tree : In a binary tree, each node can have a maximum
of 2 child nodes, and there is no ordering in terms of how the nodes
are organised in the binary tree. Nodes that do not have any child
nodes are called leaf nodes of the binary tree. Eg :
Binary Search Tree : Binary Search Tree is
essentially a binary tree, in terms of how many
child nodes a node in the binary search tree can
possibly have, but there is one important
difference between a binary tree and a binary
search tree : In a binary search tree there is a
relative ordering in how the nodes are organized,
while there is nothing of that sort in a binary tree.
In Binary search tree, all the nodes to the left of a
node have values less the value of the node, and
all the nodes to the right of a node have values
greater than the value of the node.

So, in a binary search tree we can efficiently perform operation which rely on orderly organization of nodes, as
compared to the binary tree. Examples of such operations are : find minimum / maximum value in the tree, find all
values greater / lesser than a particular value from the tree, traverse the tree from the least value to the max value,
etc. Performing such operations on plain binary tree wont be very efficient.

20. Static Block (Java)

Ans: static block includes code i.e. executed when a class is first loaded. Static block in java is executed before main
method. If we declare a Static block in java class it is executed when class loads. This is initialize with the static
variables. Static blocks is mostly used in JDBC. Static block in java is executed every time when a class loads. This
is also known as Static initialization block. Static block in javainitializes when class load into memory , it means
when JVM read the byte code. Initialization can be anything; it can be variable initialization or anything else which
should be shared by all objects of that class. Static block is a normal block of code enclosed in braces { } and is
preceded by static keyword.

Static Block in java Syntax:


static
{
…..
…..
}

Example of Static Block in Java:


StaticBlockDemo.java
class StaticBlockDemo
{
public static void main(String args[])
{
System.out.println(“This is main method”);
}
static
{
System.out.println(“This is static block in java”);
}
}
Output:
This is static block in java
This is main method

21. Polymorphism (both Static and Dynamic along with real life examples).

Ans: Compile time Polymorphism (or Static polymorphism): Polymorphism that is resolved during compiler
time is known as static polymorphism. Method overloading is an example of compile time polymorphism.
Method Overloading: This allows us to have more than one method having the same name, if the parameters of
methods are different in number, sequence and data types of parameters.
Runtime Polymorphism (or Dynamic polymorphism): It is also known as Dynamic Method Dispatch. Dynamic
polymorphism is a process in which a call to an overridden method is re solved at runtime, thats why it is called runtime
polymorphism.

22. Machine Learning and its types. explain it as if you’re explaining it to a 5 year old child.
Ans: Machine Learning is an branch of Artificial Intelligence. Generally, If We build a model without using
machine learning, It has a certain behavior. Even If you run that system for long term .There will be no change in
its behavior . In Opposite, If you build a model with machine learning , it will show different behavior with time.
As the time passes it will improve its accuracy . Now you must be thinking how it is possible . Actually In
Machine leaning models it does not have rigidity over logic written by developer . Instead of rigidity in
logic ,Model depends on data it has .

For Example in weather prediction , If you build the predictor with any machine learning algorithm . If you used
past 30 year data as training data set . At current you predict the temperature using decision tree implementation .
You will find some predicted value . Now you check your expected outcome with real outcome .Finally ,
calculate your accuracy . Now you add feed back of output to existed data set. If you continue your prediction
over the time, Your data set will increase . Lets see , if you go for prediction after 5 years you must have the data
of 35 years . It must give more accurate response than earlier.

Supervised Learning- In this style of Machine learning , We give some training to machine based on that we
test the accuracy of Machine Learning Algorithm on testing data . Suppose We have made Price prediction
algorithms based on machine learning and we have ten year past data of that Stocks . Now we can use three
years data for training to machine and rest 7 years data can be used to test and analyse the accuracy of our
algorithm.

Unsupervised Learning – In this style of learning We do not target any particular outcome . Machine try to
group different object based on the similar attribute they have based on its learning . For Example If you want
to Enhance the sale of Bread , You can use the pattern of related sold item with bread and put them
together .This will increase the sell of bread . To accomplish this issue you can use unsupervised machine
learning algorithm like K- mean.

Reinforcement Learning – This kind of learning is very different from other two type of machine
learning .Here we don’t train Machine , We write the algorithm in such a way that machine take decision and
improve outcomes until it reaches a accuracy level . Markov Decision Process is best example for Reinforcement
Machine Learning. Reinforcement Learning is used in Decision making process specially .

23. Inheritance.
Ans: Inheritance is a fundamental feature of an Object-Oriented programming. It is the process of creating a new
Class, called the Derived Class, from the existing class, called the Base Class. Inheritance is a very elegant way
to reuse and modify the data and functionality that has already been defined in the Base Class, also you can add
new data and functionality to the Derived Class. Since the Derived Class inherits all properties of the Base Class,
the Derived Class has a larger set of properties than the Base Class. However, the Derived Class may override
some or all the properties of the Base Class.

The Inheritance has many advantages, the most important of them being the reusability of code. Rather than
developing new Objects from scratch, new code can be based on the work of other developers, adding only the new
features that are needed. The reuse of existing classes saves time and effort. When you create a class to derive from
another class, the inherited class implicitly gains all the data and functionality of the base class, except for its
constructors and destructors.
From the above example, Cars and Trucks have certain common properties; all have engine, wheels, horns etc. Thus
they can be grouped under a Class called Vehicles. Apart from sharing these common features, each Derived Class
has its own particular features - Cars use petrol while Trucks use diesel.
1) Single Inheritance: Single inheritance is damn easy to understand. When a class
extends another one class only then we call it a single inheritance. The below flow diagram
shows that class B extends only one class which is A. Here A is a parent class of B and B
would be a child class of A.
Single Inheritance example program in Java
2) Multiple Inheritance: “Multiple Inheritance” refers to the concept of one
class extending (Or inherits) more than one base class. The inheritance we
learnt earlier had the concept of one base class or parent. The problem with
“multiple inheritance” is that the derived class will have to manage the
dependency on two base classes.

3) Multilevel Inheritance: Multilevel inheritance refers to a


mechanism in OO technology where one can inherit from a derived class,
thereby making this derived class the base class for the new class. As you can
see in below flow diagram C is subclass or child class of B and B is a child class of A.
For more details and example refer – Multilevel inheritance in Java.

4) Hierarchical Inheritance: In such kind of inheritance one class is inherited


by many sub classes. In below example class B,C and
D inherits the same class A. A is parent class (or base class) of B,C
& D. Read More at – Hierarchical Inheritance in java with example
program.

5) Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a
combination of Single and Multiple inheritance. A typical flow
diagram would look like below. A hybrid inheritance can be
achieved in the java in a same way as multiple inheritance can
be!! Using interfaces. yes you heard it right. By
using interfaces you can have multiple as well as hybrid
inheritance in Java.
24. Time Complexity of searching in BST.

Ans: The time complexity for a single search in a balanced binary search tree is O(log(n)). Maybe the
question requires you to do n searches in the binary tree, hence the total complexity is O(nlog(n)).
The worst case complexity for a single search in an unbalanced binary search tree is O(n). And similarly, if you
are doing n searches in the unbalanced tree, the total complexity will turn out to be O(n^2).

25. Internal functions of HashMap(Collection Interface) in Java.


Ans: There are four things you should know about HashMap before going into internal working of

HashMap works on the principal of hashing.

Map.Entry interface - This interface gives a map entry (key-value pair). HashMap in Java stores both key and
value object, in bucket, as an object of Node class which implements this nested interface Map.Entry. Read more
about Map.Entry interface here.
hashCode() - HashMap provides put(key, value) for storing and get(key) method for retrieving values from
HashMap. When put() method is used to store (Key, Value) pair, HashMap implementation calls hashcode on
Key object to calculate a hash that is used to find a bucket where Entry object will be stored.
When get() method is used to retrieve value, again key object (passed with the get() method) is used to calculate
a hash which is then used to find a bucket where that particular key is stored.
equals() - equals() method is used to compare objects for equality. In case of HashMap key object is used for
comparison, also using equals() method Map knows how to handle hashing collision (hashing collision means
more than one key having the same hash value, thus assigned to the same bucket). In that case objects are stored
in a linked list, refer figure for more clarity.

Where hashCode() method helps in finding the bucket where that key is stored, equals()method helps in finding
the right key as there may be more than one key-value pair stored in a single bucket.
** Bucket term used here is actually an index of array, that array is called table in HashMap implementation.
Thus table[0] is referred as bucket0, table[1] as bucket1 and so on.

How elements are stored internally in Java HashMap


HassMap class in Java uses an array called table of type Node to store the elements which is defined in the
HahsMap class as-

transient Node[] table;


Node is defined as a static class with in a Hashmap.
static class Node implements Map.Entry {
final int hash;
final K key;
V value;
Node next;
..
..
}

As you can see for each element four things are stored in the following fields-
• hash- For storing Hashcode calculated using the key.
• key- For holding key of the element.
• value- For storing value of the element.
• next- To store reference to the next node when a bucket has more than one element and a linkedlist is formed
with in a bucket to store elements.
Following image shows how Node(key-value pair) objects are stored internally in table array of the HashMap
class.

26. Database Connectivity in Java (steps).


Ans: To connect java application with the oracle database, we need to follow 5 following steps. In this example,
we are using Oracle 10g as the database. So we need to know following information for the oracle database:
1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is the driver,
localhost is the server name on which oracle is running, we may also use IP address, 1521 is the port
number and XE is the Oracle service name. You may get all these information from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle database.

Create a Table: Before establishing connection, let's first create a table in oracle database. Following is the SQL
query to create a table.

1. create table emp(id number(10),name varchar2(40),age number(3));

Example to Connect Java Application with Oracle database

In this example, we are connecting to an Oracle database and getting data from emp table. Here, system and oracle
are the username and password of the Oracle database.

1. import java.sql.*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. //step1 load the driver class
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7.
8. //step2 create the connection object
9. Connection con=DriverManager.getConnection(
10. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
11.
12. //step3 create the statement object
13. Statement stmt=con.createStatement();
14.
15. //step4 execute query
16. ResultSet rs=stmt.executeQuery("select * from emp");
17. while(rs.next())
18. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
19.
20. //step5 close the connection object
21. con.close();
22.
23. }catch(Exception e){ System.out.println(e);}
24.
25. }
26. }

The above example will fetch all the records of emp table.

To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.

Two ways to load the jar file:

1. paste the ojdbc14.jar file in jre/lib/ext folder

2. set classpath

1) paste the ojdbc14.jar file in JRE/lib/ext folder:

Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.

2) set classpath:

There are two ways to set the classpath:

 temporary
 permanent

How to set the temporary classpath:

Firstly, search the ojdbc14.jar file then open command prompt and write:

1. C:>set classpath=c:\folder\ojdbc14.jar;.;

How to set the permanent classpath:


Go to environment variable then click on new tab. In variable name write classpath and in variable value paste the
path to ojdbc14.jar by appending ojdbc14.jar;.; as C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;

27. Abstract class in java.

Ans: A class that is declared using “abstract” keyword is known as abstract class. It can have abstract
methods(methods without body) as well as concrete methods (regular methods with body). A normal class(non-
abstract class) cannot have abstract methods. In this guide we will learn what is a abstract class, why we use it and
what are the rules that we must remember while working with it in Java.

An abstract class can not be instantiated, which means you are not allowed to create an objectof it.

28. Difference between Abstract class and Interface.

Ans: Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods.
Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java
abstractmethods. 8, it can have default and static methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.

4) Abstract class can provide the implementation Interface can't provide the implementation of abstract
of interface. class.

5) The abstract keyword is used to declare The interface keyword is used to declare interface.
abstract class.

6) An abstract classcan extend another Java class An interface can extend another Java interface only.
and implement multiple Java interfaces.

7) An abstract classcan be extended using An interface classcan be implemented using keyword


keyword "extends". "implements".

8) A Javaabstract classcan have class members Members of a Java interface are public by default.
like private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).

29. Is Multiple Inheritance possible in Java? Why?

Ans: Java supports multiple inheritance through interfaces only. A class can implement any number of interfaces but
can extend only one class.

Multiple inheritance is not supported because it leads to deadly diamond problem. However, it can be solved but it
leads to complex system so multiple inheritance has been dropped by Java founders.

30. You are given a Binary Tree. Print the Mirror image of the tree. Write the code.
Ans: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes
interchanged.

Algorithm – Mirror(tree):

(1) Call Mirror for left-subtree i.e., Mirror(left-subtree)


(2) Call Mirror for right-subtree i.e., Mirror(right-subtree)
(3) Swap left and right subtrees.
temp = left-subtree
left-subtree = right-subtree
right-subtree = temp

// C program to convert a binary tree


// to its mirror
#include<stdio.h>
#include<stdlib.h>

/* A binary tree node has data, pointer


to left child and a pointer to right child */
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* newNode(int data)

{
struct Node* node = (struct Node*)
malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

/* Change a tree so that the roles of the left and


right pointers are swapped at every node.

So the tree...
4
/\
2 5
/\
1 3

is changed to...
4
/\
5 2
/\
3 1
*/
void mirror(struct Node* node)
{
if (node==NULL)
return;
else
{
struct Node* temp;

/* do the subtrees */
mirror(node->left);
mirror(node->right);

/* swap the pointers in this node */


temp = node->left;
node->left = node->right;
node->right = temp;
}
}
/* Helper function to print Inorder traversal.*/
void inOrder(struct Node* node)
{
if (node == NULL)
return;

inOrder(node->left);
printf("%d ", node->data);
inOrder(node->right);
}

/* Driver program to test mirror() */


int main()
{
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);

/* Print inorder traversal of the input tree */


printf("Inorder traversal of the constructed"
" tree is \n");
inOrder(root);

/* Convert tree to its mirror */


mirror(root);

/* Print inorder traversal of the mirror tree */


printf("\nInorder traversal of the mirror tree"
" is \n");
inOrder(root);

return 0;
}

Output :
Inorder traversal of the constructed tree is
42513
Inorder traversal of the mirror tree is
31524

31. Code to find the Loop in a Linked List.

Ans: Given a linked list, check if the the linked list has loop or not. Below diagram shows a linked list with a loop.
// C++ program to detect loop in a linked list
#include<bits/stdc++.h>
using namespace std;

/* Link list node */


struct Node
{
int data;
struct Node* next;
};

void push(struct Node** head_ref, int new_data)


{
/* allocate node */
struct Node* new_node = new Node;

/* put in the data */


new_node->data = new_data;

/* link the old list off the new node */


new_node->next = (*head_ref);

/* move the head to point to the new node */


(*head_ref) = new_node;
}

// Returns true if there is a loop in linked list


// else returns false.
bool detectLoop(struct Node *h)
{
unordered_set<Node *> s;
while (h != NULL)
{
// If this node is already present
// in hashmap it means there is a cycle
// (Because you we encountering the
// node for the second time).
if (s.find(h) != s.end())
return true;

// If we are seeing the node for


// the first time, insert it in hash
s.insert(h);

h = h->next;
}

return false;
}

/* Drier program to test above function*/


int main()
{
/* Start with the empty list */
struct Node* head = NULL;

push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 10);

/* Create a loop for testing */


head->next->next->next->next = head;

if (detectLoop(head))
cout << "Loop found";
else
cout << "No Loop";

return 0;
}

32. Reverse a Doubly Linked List. (Code)


Ans: See below diagrams for example.

* Program to reverse a doubly linked list */


#include <stdio.h>
#include <stdlib.h>

/* a node of the doubly linked list */


struct Node
{
int data;
struct Node *next;
struct Node *prev;
};

/* Function to reverse a Doubly Linked List */


void reverse(struct Node **head_ref)
{
struct Node *temp = NULL;
struct Node *current = *head_ref;

/* swap next and prev for all nodes of


doubly linked list */
while (current != NULL)
{
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}

/* Before changing head, check for the cases like empty


list and list with only one node */
if(temp != NULL )
*head_ref = temp->prev;
}

/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginging of the Doubly Linked List */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));

/* put in the data */


new_node->data = new_data;

/* since we are adding at the begining,


prev is always NULL */
new_node->prev = NULL;

/* link the old list off the new node */


new_node->next = (*head_ref);
/* change prev of head node to new node */
if((*head_ref) != NULL)
(*head_ref)->prev = new_node ;

/* move the head to point to the new node */


(*head_ref) = new_node;
}

/* Function to print nodes in a given doubly linked list


This function is same as printList() of singly linked lsit */
void printList(struct Node *node)
{
while(node!=NULL)
{
printf("%d ", node->data);
node = node->next;
}
}

/* Drier program to test above functions*/


int main()
{
/* Start with the empty list */
struct Node* head = NULL;

/* Let us create a sorted linked list to test the functions


Created linked list will be 10->8->4->2 */
push(&head, 2);
push(&head, 4);
push(&head, 8);
push(&head, 10);

printf("\n Original Linked list ");


printList(head);

/* Reverse doubly linked list */


reverse(&head);

printf("\n Reversed Linked list ");


printList(head);

getchar();
}

Time Complexity: O(n)

33. Inorder Successor in the Binary Tree. Write the code.


Ans: In Binary Tree, Inorder successor of a node is the next node in Inorder traversal of the Binary Tree. Inorder
Successor is NULL for the last node in Inoorder traversal.
In Binary Search Tree, Inorder Successor of an input node can also be defined as the node with the smallest key
greater than the key of input node. So, it is sometimes important to find next node in sorted order.

Method 1 (Uses Parent Pointer)


In this method, we assume that every node has parent pointer.
The Algorithm is divided into two cases on the basis of right subtree of the input node being empty or not.
Input: node, root // node is the node whose Inorder successor is needed.
output: succ // succ is Inorder successor of node.
1) If right subtree of node is not NULL, then succ lies in right subtree. Do following.
Go to right subtree and return the node with minimum key value in right subtree.
2) If right sbtree of node is NULL, then succ is one of the ancestors. Do following.
Travel up using the parent pointer until you see a node which is left child of it’s parent. The parent of such a node is
the succ.
Implementation
Note that the function to find InOrder Successor is highlighted (with gray background) in below code.

#include <stdio.h>
#include <stdlib.h>

/* A binary tree node has data, pointer to left child


and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
struct node* parent;
};

struct node * minValue(struct node* node);

struct node * inOrderSuccessor(struct node *root, struct node *n)


{
// step 1 of the above algorithm
if( n->right != NULL )
return minValue(n->right);
// step 2 of the above algorithm
struct node *p = n->parent;
while(p != NULL && n == p->right)
{
n = p;
p = p->parent;
}
return p;
}

/* Given a non-empty binary search tree, return the minimum data


value found in that tree. Note that the entire tree does not need
to be searched. */
struct node * minValue(struct node* node) {
struct node* current = node;

/* loop down to find the leftmost leaf */


while (current->left != NULL) {
current = current->left;
}
return current;
}

/* Helper function that allocates a new node with the given data and
NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
node->parent = NULL;

return(node);
}

/* Give a binary search tree and a number, inserts a new node with
the given number in the correct place in the tree. Returns the new
root pointer which the caller should then use (the standard trick to
avoid using reference parameters). */
struct node* insert(struct node* node, int data)
{
/* 1. If the tree is empty, return a new,
single node */
if (node == NULL)
return(newNode(data));
else
{
struct node *temp;
/* 2. Otherwise, recur down the tree */
if (data <= node->data)
{
temp = insert(node->left, data);
node->left = temp;
temp->parent= node;
}
else
{
temp = insert(node->right, data);
node->right = temp;
temp->parent = node;
}

/* return the (unchanged) node pointer */


return node;
}
}

/* Driver program to test above functions*/


int main()
{
struct node* root = NULL, *temp, *succ, *min;

//creating the tree given in the above diagram


root = insert(root, 20);
root = insert(root, 8);
root = insert(root, 22);
root = insert(root, 4);
root = insert(root, 12);
root = insert(root, 10);
root = insert(root, 14);
temp = root->left->right->right;

succ = inOrderSuccessor(root, temp);


if(succ != NULL)
printf("\n Inorder Successor of %d is %d ", temp->data, succ->data);
else
printf("\n Inorder Successor doesn't exit");

getchar();
return 0;
}

In the above diagram, inorder successor of 8 is 10, inorder successor of 10 is 12 and inorder successor of 14 is 20.

34. Write function to implement convert Integer to string and string to integer.

Ans: String to Integer Conversion in Java:


1) By using Intger.parseInt(String string-to-be-converted) method
This is my preferred way of converting an String to int in Java, Extremely easy and most flexible way of
converting String to Integer. Let see an example of String to int conversion:

//using Integer.parseInt
int i = Integer.parseInt("123");
System.out.println("i: " + i);

Integer.parseInt() method will throw NumberFormatException if String provided is not a proper number. Same
technique can be used to convert other data type like float and Double to String in Java. Java API provides static
methods like Float.parseFloat() and Double.parseDouble() to perform data type conversion.

2) Integer.valueOf() method
There is another way of converting String into Integer which was hidden to me for long time mostly because I
was satisfied with Integer.parseInt() method. This is an example of Factory method design pattern in Java and
known as Integer.valueOf(), this is also a static method like main and can be used as utility for string to int
conversion. Let’s see an example of using Integer.valueOf() to convert String into int in java.

//How to convert numeric string = "000000081" into Integer value = 81


int i = Integer.parseInt("000000081");
System.out.println("i: " + i);

How to convert Integer to String in Java: In the previous example of this String to int conversion we have seen
changing String value into int primitive type and this part of Java tutorial we will see opposite i.e. conversion of
Integer Object to String. In my opinion this is simpler than previous one. You can simply concatenate any number
with empty String and it will create a new String. Under the carpet + operator uses
either StringBuffer or StringBuilder to concatenate String in Java. anyway there are couple of more ways to convert
int into String and we will see those here with examples.

Int to String in Java using "+" operator


Anything could not be more easy and simple than this. You don't have to do anything special just
use "+" concatenation operator with String to convert intvariable into String object as shown in the following
example:

String price = "" + 123;

Simplicity aside, Using String concatenation for converting int to String is also one of the most poor way of doing it.
I know it's temptation because, it's also the most easiest way to do and that's the main reason of it polluting code.
When you write code like "" + 10 to convert numeric 10 to String, your code is translated into following :

new StringBuilder().append( "" ).append( 10 ).toString();

StringBuilder(String) constructor allocates a buffer containing 16 characters. So , appending upto to 16


characters to that StringBuilder will not require buffer reallocation, but appending more than 16 character will
expand StringBuiderbuffer. Though it's not going to happen because Integer.MAX_VALUE is2147483647,
which is less than 16 character. At the end,StringBuilder.toString() will create a new String object with a copy of
StringBuider buffer. This means for converting a single integer value to String you will need to allocate:
one StringBuilder, one char array char[16], one String and one char[] of appropriate size to fit your input value.
If you use String.vauleOf()will not only benefit from cached set of values but also you will at least avoid creating
a StringBuilder.

35. Volatile Keyword in Java.

1. And: Synchronization in Java is possible by using Java keywords synchronized and volatile and locks.
2. In Java, we can not have synchronized variable. Using synchronized keyword with a variable is illegal and
will result in compilation error. Instead of using the synchronized variable in Java, you can use the
java volatile variable, which will instruct JVM threads to read the value of volatile variable from main memory
and don’t cache it locally.
3. If a variable is not shared between multiple threads then there is no need to use the volatilekeyword.

36. Exception Handling.

Ans: Exception handling is the process of responding to the occurrence, during computation, of exceptions –
anomalous or exceptional conditions requiring special processing – often changing the normal flow
of program execution. It is provided by specialized programming language constructs, computer
hardware mechanisms like interrupts or operating systemIPC facilities like signals.
In general, an exception breaks the normal flow of execution and executes a pre-registered exception handler. The
details of how this is done depends on whether it is a hardware or software exception and how the software exception
is implemented. Some exceptions, especially hardware ones, may be handled so gracefully that execution can resume
where it was interrupted.
Alternative approaches to exception handling in software are error checking, which maintains normal program flow
with later explicit checks for contingencies reported using special return values or some auxiliary global variable
such as C's errno or floating point status flags; or input validation to preemptively filter exceptional cases.

37. Finally Block in Java

Ans: Java finally block is a block that is used to execute important code such as closing connection, stream etc. Java
finally block is always executed whether exception is handled or not.

38. Multi – Threading in Java.


Ans: Multithreading in java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are
used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate
separate memory area so saves memory, and context-switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple operations at the same
time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

TECHNICAL INTERVIEW QUESTION (CODING TEST)


1. Given the Linked List, Arrange it in the following order

Input: Head       
1 2 3 4 4 6 Given
Output: Head  1  6  2  5  3  4
Sol:
Algorithm is:

Find the middle point using tortoise and hare method.


2) Split the linked list into two halves using found middle point in step 1.
3) Reverse the second half.
4) Do alternate merge of first and second halves.

2. Given an array of integers and an integer n. Calculate the number of subsets having the sums n.
Sol:
// A Dynamic Programming solution for subset sum problem
#include<stdio.h>

// Returns true if there is a subset of set[] with sun equal to given sum
boolisSubsetSum(int set[], int n, int sum)
{
// The value of subset[i][j] will be true if there is a
// subset of set[0..j-1] with sum equal to i
bool subset[n+1][sum+1];

// If sum is 0, then answer is true


for (inti = 0; i<= n; i++)
subset[i][0] = true;

// If sum is not 0 and set is empty, then answer is false


for (inti = 1; i<= sum; i++)
subset[0][i] = false;

// Fill the subset table in botton up manner


for (inti = 1; i<= n; i++)
{
for (int j = 1; j <= sum; j++)
{
if(j<set[i-1])
subset[i][j] = subset[i-1][j];
if (j >= set[i-1])
subset[i][j] = subset[i-1][j] ||
subset[i - 1][j-set[i-1]];
}
}

/* // uncomment this code to print table


for (inti = 0; i<= n; i++)
{
for (int j = 0; j <= sum; j++)
printf ("%4d", subset[i][j]);
printf("n");
}*/

return subset[n][sum];
}

// Driver program to test above function


int main()
{
int set[] = {3, 34, 4, 12, 5, 2};
int sum = 9;
int n = sizeof(set)/sizeof(set[0]);
if (isSubsetSum(set, n, sum) == true)
printf("Found a subset with given sum");
else
printf("No subset with given sum");
return 0;
}

3. Given and array of integers and calculate the number of subsets having sum = 0.
Sol:
Above code is used with one condition if sum is zero that we count it.

4. Given an integer, you have to calculate the number of 7 in the digits of that integer.
Sol:
The integer entered by the user is stored in variable n. Then the while loop is iterated until the test expression n != 0
is evaluated to 0 (false).

After first iteration, the value of n will be 345 and the count is incremented to 1.
After second iteration, the value of n will be 34 and the count is incremented to 2.
After third iteration, the value of n will be 3 and the count is incremented to 3.
After fourth iteration, the value of n will be 0 and the count is incremented to 4.
Then the test expression is evaluated to false and the loop terminates.

// Iterative C program to count number of


// digits in a number
#include<stdio.h>

intcountDigit(long long n)
{
int count = 0;
while (n != 0) {
n = n / 10;
++count;
}
return count;
}

// Driver code
int main(void)
{
longlong n = 345289467;
printf("Number of digits : %d",
countDigit(n));
return 0;
}
Company Name: - FourKites
Book Index: 170-(D)

1. About Academic Projects done.


2. Implement the coding question asked in written test and tell the complexity for that.

Ques 3. Exception handling in java.


Ans: The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal
flow of the application can be maintained.
Types of Exception

There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception.
The sun microsystem says there are three types of exceptions:

Checked Exception
Unchecked Exception
Error

Difference between checked and unchecked exceptions


1) Checked Exception

The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions
e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-
time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

There are 5 keywords used in java exception handling.

try
catch
finally
throw
throws

Ques 4. Implement a thread in which you have to print simultaneously even and odd numbers.
Ans:
public class OddEvenPrintMain {

boolean odd;
int count = 1;
int MAX = 20;

public void printOdd() {


synchronized (this) {
while (count < MAX) {
System.out.println("Checking odd loop");

while (!odd) {
try {
System.out.println("Odd waiting : " + count);
wait();
System.out.println("Notified odd :" + count);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Odd Thread :" + count);
count++;
odd = false;
notify();
}
}
}

public void printEven() {

try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synchronized (this) {
while (count < MAX) {
System.out.println("Checking even loop");

while (odd) {
try {
System.out.println("Even waiting: " + count);
wait();
System.out.println("Notified even:" + count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Even thread :" + count);
count++;
odd = true;
notify();

}
}
}

public static void main(String[] args) {

OddEvenPrintMain oep = new OddEvenPrintMain();


oep.odd = true;
Thread t1 = new Thread(new Runnable() {

@Override
public void run() {
oep.printEven();

}
});
Thread t2 = new Thread(new Runnable() {

@Override
public void run() {
oep.printOdd();

}
});

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}
6. Question on data structures Trees, pre,post traversal for tree and what will be the complexity.
Ans:
Pre - Order Traversal ( root - leftChild - rightChild ): In Pre-Order traversal, the root node is visited before left
child and right child nodes. In this traversal, the root node is visited first, then its left child and later its right child.
This pre-order traversal is applicable for every root node of all subtrees in the tree.

In the above example of binary tree, first we visit root node 'A' then visit its left child 'B' which is a root for D and F.
So we visit B's left child 'D' and again D is a root for I and J. So we visit D's left child 'I' which is the left most child.
So next we go for visiting D's right child 'J'. With this we have completed root, left and right parts of node D and
root, left parts of node B. Next visit B's right child 'F'. With this we have completed root and left parts of node A. So
we go for A's right child 'C' which is a root node for G and H. After visiting C, we go for its left child 'G' which is a
root for node K. So next we visit left of G, but it does not have left child so we go for G's right child 'K'. With this we
have completed node C's root and left parts. Next visit C's right child 'H' which is the right most child in the tree. So
we stop the process.

That means here we have visited in the order of A-B-D-I-J-F-C-G-K-H using Pre-Order Traversal.

Pre-Order Traversal for above example binary tree is


A-B-D-I-J-F-C-G-K–H

Post - Order Traversal ( leftChild - rightChild - root ): In Post-Order traversal, the root node is visited after left
child and right child. In this traversal, left child node is visited first, then its right child and then its root node. This is
recursively performed until the right most node is visited.

Here we have visited in the order of I - J - D - F - B - K - G - H - C - A using Post-Order Traversal.

Post-Order Traversal for above example binary tree is


I-J-D-F-B-K-G-H-C-A

7. What is try, catch block in exception handling.


Ans: Java try block

Java try block is used to enclose the code that might throw an exception. It must be used within the method.

Java try block must be followed by either catch or finally block.


Syntax of java try-catch

try{
//code that may throw exception
}catch(Exception_class_Name ref){}

Java catch block

Java catch block is used to handle the Exception. It must be used after the try block only.
You can use multiple catch block with a single try.

8. Final, finally keyword.


Ans: Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final method
can't be overridden and final variable value can't be changed.
Java final example

class FinalExample{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}}
Java finally example Finally is used to place important code, it will be executed whether exception is handled or
not.

class FinallyExample{
public static void main(String[] args){
try{
int x=300;
}catch(Exception e){System.out.println(e);}
finally{System.out.println("finally block is executed");}
}}

Java finalize example Finalize is used to perform clean up processing just before object is garbage collected.

class FinalizeExample{
public void finalize(){System.out.println("finalize called");}
public static void main(String[] args){
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}}

9. Schema of your project. What tables you have made in this project.

Ques 10. Singleton class in java.


Ans:
In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at
a time.
After first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created.
So whatever modifications we do to any variable inside the class through any instance, it affects the variable of the
single instance created and is visible if we access that variable through any variable of that class type defined.
To design a singleton class:
Make constructor as private.
Write a static method that has return type object of this singleton class. Here, the concept of Lazy initialization in
used to write this static method.

11. Static block in java.


Ans. Java supports a special block, called static block (also called static clause) which can be used for static
initializations of a class. This code inside static block is executed only once: the first time you make an object of that
class or the first time you access a static member of that class (even if you never make an object of that class). For
example, check output of following Java program.
// filename: Main.java
class Test {
static int i;
int j;

// start of static block


static {
i = 10;
System.out.println("static block called ");
}
// end of static block
}

class Main {
public static void main(String args[]) {

// Although we don't have an object of Test, static block is


// called because i is being accessed in following statement.
System.out.println(Test.i);
}
}

Output:
static block called
Company Name: - MU SIGMA_TECHNICAL Placement Drive
Book Index: 172-(D)

TECHNICAL INTERVIEW QUESTIONS

1. Logic of the game 2048.

Ans: This is the model I chose by default.

1024 512 256 128


8 16 32 64
4 2 x x
xxxx
The chosen corner is arbitrary, you basically never press one key (the forbidden move), and if you do, you press
the contrary again and try to fix it. For future tiles the model always expects the next random tile to be a 2 and
appear on the opposite side to the current model (while the first row is incomplete, on the bottom right corner,
once the first row is completed, on the bottom left corner).
Here goes the algorithm

initiateModel();
while(!game_over)
{
checkCornerChosen(); // Unimplemented, but it might be an improvement to change the
reference point for each 3 possible move:
evaluateResult() execute move with best score if no move is available, execute
forbidden move and undo,
recalculateModel()
}
evaluateResult()
{
calculatesBestCurrentModel() calculates distance to chosen model stores result
}
calculateBestCurrentModel()
{
(according to the current highest tile acheived and their distribution)

2. Tell me the number of Red Swift Cars in Chandigarh and who will you calculate it.
Ans: With these kind of questions, the intent is not to necessarily get to the correct answer, but to demonstrate
your thought process on how you approach the problem. For example, one possible approach might be as
follows:
Let’s say the population of Delhi is 10 million
Let’s assume that translates to about 2.5 million families in delhi (Assuming 4 people to a family)
Assuming that every family has on average 1.5 cars (or some reasonable number)
Which means there are 3.75 million cars in Delhi
Now Maruti must have the biggest percentage of cars sold, so lets assume that is 30% of all cars sold, which is
approx 1 million cars
Of this, lets say they are split between Swift, X, Y and Z cars each at 20%
So 200,000 swift cars in delhi
Of this, 50% cars might be red or blue, or 25% would be just red, which leaves us with 50,000 red swift cars in
delhi
This is an example of a top down approach, starting with a large number, and then making reasonable
assumptions (or asking questions of the interviewer) to whittle it down to your final number.
Certain problems are also open to a bottom up answer, where you work it out in the reverse manner, from a small
number, adding up to your final value.

3. Puzzles  Hour Glass Puzzle, Bulb & Room Puzzle, etc


Sol:

At 0 minutes: start both hourglasses at the same time.

At 4 minutes: 4 minutes hourglass runs out and flip it. 7 minutes hourglass is left with 3 minutes.

At 7 minutes: 4 minutes hourglass is left with 1 minute. 7 minutes hourglass runs out and flip it.

At 8 minutes: 4 minutes hourglass runs out and 7 is filled with 6 minutes and 1 minute in other side. Flip it as the
sand is left with 1 minute.

At 9 minutes: 7 minutes hourglass becomes empty from above side.

There is a room with a door (closed) and three light bulbs. Outside the room there are three switches, connected
to the bulbs. You may manipulate the switches as you wish, but once you open the door you can’t change them.
Identify each switch with its bulb.

Let the bulbs be X, Y and Z

Turn on switch X for 5 to 10 minutes. Turn it off and turn on switch Y. Open the door and touch the light bulb.

1. if the light is on, it is Y

2. if the light is off and hot, it is X

3. if the light is off and cold, it is Z

Hence we measured 9 minutes.

4. What are the different libraries in Python? Name 6 of them.


Ans: Python library is a collection of functions and methods that allows you to perform lots of actions without
writing your own code. For example, if you are working with data, numpy, scipy, pandas, etc. are the libraries.

5. Different Classification Techniques


Ans: Several major kinds of classification algorithms including C4.5, ID3, k-nearest neighbor classifier, Naive
Bayes, SVM, and ANN are used for classification. Generally a classification technique follows three approaches
Statistical, Machine Learning and Neural Network for classification.

6. Which of the Classification Techniques was the most efficient and why?
7. Fibonacci Program.
Sol:
#include<stdio.h>
int main()
{
inti, n, t1 = 0, t2 = 1, nextTerm;
printf("Enter the number of terms: ");
scanf("%d", &n);
printf("Fibonacci Series: ");
for (i = 1; i<= n; ++i)
{ printf("%d, ", t1); nextTerm = t1 + t2; t1 = t2; t2 = nextTerm;
}
return 0;
}

8. How will calculate the overall consumption of Surf Excel by middle class families in India?
Sol:
The most important factor in these guesstimates is taking the right assumptions and backing them up with
appropriate logic. It essentially revolves around market sizing of products and can be solved with two
approaches:

1. Top-down
2. Bottom-up

I prefer going with the former one, as it is simpler to reduce a larger number into factions on sequentially
considering the factors which influence it. So, for estimating the amount of surf excel detergent used daily in
India:

Population of India updated as per 2013 = 1.2 billion = 1200 million.


(let's drop the units for convenience sake)

Now only 33% (1/3rd) among them are above the poverty line: 1200/3=400

It is unlikely that the rural population of India (mix of tier III places and villages) will occupy a large portion of
the 400 million.
Lets assume they constitute 25%, which leaves us with: 400*75%=300

Average family size in India = 5 ( as per Govt. of India 2012 data)


So, number of households we're targeting = 300/5 = 60

Say, Surf Excel only has 30% of the market due to cost-effectiveness and better penetration of competitors.
Hence, have 60*30%=18

Average daily consumption of surf excel per household: 10gm

So, average usage of Surf Excel in India per day is: 10*180,00,000/1000 = 180 tons.
Company Name: - CLICK LABS PVT LTD

Book Index: 177 (D)

TECHNICAL INTERVIEW QUESTIONS

1. Write algorithm to check whether a binary tree is BST or not?


Ans:
struct node
{
int data;
struct node* left;
struct node* right;
};

int isBSTUtil(struct node* node, int min, int max);

/* Returns true if the given tree is a binary search tree


(efficient version). */
int isBST(struct node* node)
{
return(isBSTUtil(node, INT_MIN, INT_MAX));
}

/* Returns true if the given tree is a BST and its


values are >= min and <= max. */
int isBSTUtil(struct node* node, int min, int max)
{
/* an empty tree is BST */
if (node==NULL)
return 1;

/* false if this node violates the min/max constraint */


if (node->data < min || node->data > max)
return 0;

/* otherwise check the subtrees recursively,


tightening the min or max constraint */
return
isBSTUtil(node->left, min, node->data-1) && // Allow only distinct values
isBSTUtil(node->right, node->data+1, max); // Allow only distinct values
}

2. What are linear and non linear data Structures?


Ans: In computer science, Data Structure is classified into two categories :

 Linear Data Structure


 Non Linear Data Structure

Types of Data Structure


Classifications of Data Structure

Linear Data Structures: The data structure where data items are organized sequentially or linearly where
data elements attached one after another is called linear data structure. Data elements in a liner data
structure are traversed one after the other and only one element can be directly reached while traversing.
All the data items in linear data structure can be traversed in single run.

These kind of data structures are very easy to implement because memory of computer is also organized
in linear fashion.

 Examples of linear data structures are Arrays, Stack, Queue and Linked List.

An arrays is a collection of data items having the same data types. A Stack is a LIFO (Last In First Out)
data structure where element that added last will be deleted first. All operations on stack are performed
from on end called TOP. A Queue is a FIFO (First In First Out) data structure where element that added
first will be deleted first. In queue, insertion is performed from one end called REAR and deletion is
performed from another end called FRONT. A Linked list is a collection of nodes, where each node is
made up of a data element and a reference to the next node in the sequence.

Non Linear Data Structures: The data structure where data items are not organized sequentially is called
non linear data structure. In other words, A data elements of the non linear data structure could be
connected to more than one elements to reflect a special relationship among them. All the data elements in
non linear data structure can not be traversed in single run.

 Examples of non linear data structures are Trees and Graphs.

A tree is collection of nodes where these nodes are arranged hierarchically and form a parent child
relationships. A Graph is a collection of a finite number of vertices and an edges that connect these
vertices. Edges represent relationships among vertices that stores data elements.

3. Algorithm for Merge Sort and its complexity?


Ans:
MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)

Time Complexity: Sorting arrays on different machines. Merge Sort is a recursive algorithm and time
complexity can be expressed as following recurrence relation.
T(n) = 2T(n/2) + \Theta(n)

The above recurrence can be solved either using Recurrence Tree method or Master method. It falls in case II
of Master Method and solution of the recurrence is \Theta(nLogn).
Time complexity of Merge Sort is \Theta(nLogn) in all 3 cases (worst, average and best) as merge sort always
divides the array in two halves and take linear time to merge two halves.
Auxiliary Space: O(n)

4. Algorithm for Quick Sort and its complexity?


Ans: Algorithm
quickSort(arr[], low, high)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is now
at right place */
pi = partition(arr, low, high);

quickSort(arr, low, pi - 1); // Before pi


quickSort(arr, pi + 1, high); // After pi
}
}
quickSort(arr[], low, high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
pi = partition(arr, low, high);

quickSort(arr, low, pi - 1); // Before pi


quickSort(arr, pi + 1, high); // After pi
}
}
partition (arr[], low, high)
{
// pivot (Element to be placed at right position)
pivot = arr[high];

i = (low - 1) // Index of smaller element

for (j = low; j <= high- 1; j++)


{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++; // increment index of smaller element
swap arr[i] and arr[j]
}
}
swap arr[i + 1] and arr[high])
return (i + 1)
}

Time Complexity : theta(nLogn)


5. What are the different clauses in DBMS?

Ans: SQL Clauses


DISTINCT Clause Retrieve unique records
FROM Clause List tables and join information
WHERE Clause Filter results
ORDER BY Clause Sort query results
GROUP BY Clause Group by one or more columns
HAVING Clause Restrict the groups of returned rows

6. Write the sql query for DML Commands?

Ans:
DML(Data Manipulation Language) : The SQL commands that deals with the manipulation of data
present in database belong to DML or Data Manipulation Language and this includes most of the SQL
statements.

Examples of DML:
SELECT – is used to retrieve data from the a database.
INSERT – is used to insert data into a table.
UPDATE – is used to update existing data within a table.
DELETE – is used to delete records from a database table.
Queries:
SELECT * FROM table_name;1

INSERT INTO Student VALUES ('5','HARSH','WEST BENGAL','8759770477','19');

UPDATE Student SET NAME = 'PRATIK', ADDRESS = 'SIKKIM' WHERE ROLL_NO = 1;

DELETE FROM Student WHERE Age = 20;


Company Name: - Micro Focus Placement Drive
Book Index: 178-(D)

1. Hash function f is defined as f(key) = key mod 7. If linear probing is used to insert the key 37, 38, 72, 48, 98,
11, 56 into a table indexed from 0 to 6. 11 will be stored at the location
A. 3 B. 4 C. 5 D. 6

Answer: C
Explanation:
Hash function = f(key) = key mod 7
insertion order= 37, 38, 72, 48, 98, 11, 56
Insert 37: 37 mod 7 = 2
Insert 38: 38 mod 7 = 3
Insert 72: 72 mod 7 = 2, but already occupied, so after linear probing it would occupy index 4.
Insert 48: 48 mod 7 = 6
Insert 98: 98 mod 7 = 0
Insert 11: 11 mod 7 = 4, but already occupied, after linear probing it would get into index 5.
So, option (C) is correct.

2. File *f = fopen ( filename, “r” ) ;


readData( f ) ;
if ( ???? )
{
Puts( “End of file was reached” ) ;
}

Which one of the following can replace the ???? in the code above to determine if the end of a file has been
reached?
A. f = = EOF
B. feof( f )
C. eof( f )
D. f = = NULL
E. !f

Answer: B
Explanation:
In C/C++, getc() returns EOF when end of file is reached. getc() also returns EOF when it fails. So, only
comparing the value returned by getc() with EOF is not sufficient to check for actual end of file.To solve this
problem, C provides feof() which returns non-zero value only if end of file has reached, otherwise it returns 0.

For example, consider the following C program to print contents of file test.txt on screen. In the program, returned
value of getc() is compared with EOF first, then there is another check using feof(). By putting this check, we
make sure that the program prints “End of file reached” only if end of file is reached. And if getc() returns EOF
due to any other reason, then the program prints “Something went wrong”.

#include <stdio.h>
int main()
{
FILE *fp = fopen("test.txt", "r");
int ch = getc(fp);
while (ch != EOF)
{
/* display contents of file on screen */
putchar(ch);

ch = getc(fp);
}

if (feof(fp))
printf("\n End of file reached.");
else
printf("\n Something went wrong.");
fclose(fp);

getchar();
return 0;
}

3. Which algorithm solves all pair shortest path problem


A. Dijkstra’s algorithm
B. Floyd’s algorithm
C. Prim’s algorithm
D. Warshal’s algorithm

Answer: B
Explanation:
Dijkstra's algorithm solves single source shortest path problem. Warshall's algorithm finds transitive closure of a
given graph. Prim's algorithm constructs a minimum cost spanning tree for a given weighted graph.

4. Given the following code, which statement is true about the minimum number of test cases required for full
statement and branch coverage?
Read p
Read q
IF p+q> 100
THEN Print “Large”
ENDIF
IF p > 50
THEN Print “p Large”
ENDIF

A. 1 test for statement coverage, 2 for branch coverage


B. 2 test for statement coverage, 1 for branch coverage
C. 2 test for statement coverage, 2 for branch coverage
D. 1 test for statement coverage, 1 for branch coverage

Answer: A
Explanation:
To calculate Statement Coverage, find out the shortest
number of paths following
which all the nodes will be covered. Here by traversing
through path 1A-2C-3D-E-4G-5H all
the nodes are covered. So by traveling through only one path
all the nodes 12345 are covered,
so the Statement coverage in this case is 1.
Branch Coverage (BC):
To calculate Branch Coverage, find out the minimum number of
paths which will
ensure covering of all the edges. In this case there is no
single path which will ensure coverage
of all the edges at one go. By following paths
1A-2C-3D-E-4G-5H, maximum numbers of
edges (A, C, D, E, G and H) are covered but edges B and F
are left. To covers these edges we can follow 1A-2B-E-4F. By
the combining the above two paths we can ensure of traveling
through all the paths. Hence Branch Coverage is 2. The aim
is to cover all possible true/false
decisions.
5. Complete the sentence:
#include<iostream>
Using namespace std;
int main()
{
char *ptr = NULL;
{
char ch = ‘a’;
ptr = &ch;
}
// line no. K
return 0;
}
Int the above program, ptr on line no. K is ____________.
A. ‘a’
B. NULL
C. This program produces compile-time error.
D. A dangling pointer

Answer: B
Explanation:

Character ‘ch’ has a local scope which is only visible within the inner block. Outside the inner block the pointer PTR
has NULL value.

6. The Memory Management Unit is responsible for


A. The calculation of effective addresses for instruction operands that must be accessed from memory
B. Keeping track of the blocks that are currently loaded into the cache memory
C. The translation of virtual addresses into physical addresses
D. All of the above

Answer:
Core Subject Question

7. Hardware cache memories exploit spatial locality of reference


A. By remembering which pieces of data have been accessed recently
B. When data items are re – accessed frequently
C. By remembering which cache blocks ( lines ) have been written to
D. Only if cache block ( lines ) Size is greater than 1 byte

Answer:
Core Subject Question

8. For what values of x and xmin will the following program segment output -5?
{
(if (abs(x) < xmin) x = ((x>0)? xmin : -xmin);
printf (“%d “, x);
}

A. x = -4 xmin = 5
B. x = -4 xmin = -5
C. x = 4 xmin = 5
D. x = 4 xmin = -5

Answer: C
Explanation:
Abs(4) < 5 is true.

x>0 will be evaluate as true for option C, then x will be assigned value of xmin i.e. x=5.
Final output will be 5.

9. What is the result of the following array declaration and initializtion?


int a[2][2] = { 1, 2} ;
A. a [0] [0] =1, a [0] [1] =1, a [1] [0] =2, a [1] [1] =2
B. a [0] [0] =1, a [0] [1] =2 a [1] [0] =0, a [1] [1] = 0
C. a [0] [0] =1, a [0] [1] = 0 a [1] [0] =2, a [1] [1] = 0
D. a [0] [0] =1, a [0] [1] = 2 a [1] [0] =2, a [1] [1] = 2

Answer: B
Explanation:

Initialize all Array elements but initialization is much straight forward. All values are assigned sequentially and row-
wise.
Consider the below example program –

#include <stdio.h>

int main() {
int i, j;
int a[3][2] = { 1, 4, 5, 2, 6, 5 };

for (i = 0; i < 3; i++) {


for (j = 0; j < 2; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}

Output :
14
52
65

10. The folowing C function takes a singly-linked list of integers as a parameter and rearranges the elemets of the
list. The list is represented as a pointer to a structure. The functionis called with the list containing the integers
1,2,3,4,5,6,7 in the given order. What will be the contents of the list after the function completes execution?

struct node {int value; sturct node *next;};


voide rearrange (struct node *list){
struct node *p, *q; int temp;
if ( ! list l l !list - > next )
p = list ; q = list - > next ;
while (q) {
temp = p - > value; p- > value = q - > value;
q - > value = temp; p = q - > next;
q = p ? p- > next : 0 ;
}
}
A. 1,2,3,4,5,6,7
B. 2,1,4,3,6,5,7
C. 1,3,2,5,4,7,6
D. 2,3,4,5,6,7,1

Answer: B
Explanation:
The function rearrange () exchanges data of every node with its next node. It starts exchanging data
from the first node itself.

11. Can we have multiple classes in same java file?


A. True B. False

Answer: A
Explanation:
Yes, it can. However, there can only be one public top-level class per .java file, and public top-level classes must
have the same name as the source file.

The purpose of including multiple classes in one source file is to bundle related support functionality (internal data
structures, support classes, etc) together with the main public class. Note that it is always OK not to do this--the only
effect is on the readability (or not) of your code.

12. EvilBank’s admin Mr. Perkins is sittin near a seashore. He found N sealed containers of brickson the shore.
He is not sure how many bricks each container contains. However, there is a note written pointing the
following information:
 The total number of bricks each container contains. However, there is a note written pointing the
following information:
 An integer array high[] of size N will be given. For each i in high, container I (0-based index) contains
between 0 and high [1] bricks, inclusive.
You know that Mr. Perkins uses bricks as follows: first he chooses a subset of the containers, then he opens
them and uses all the bricks he found inside. He wants to use at least X bricks. And as he is smart, he will
always choose a subset of containers for which he is sure that they contain at least X bricks.
You are given the N, C and X, and the int [] high, Print the smallest number of containers Mr. Perkins may
choose.
Constraints:
1 ≤ N ≤ 50
1 ≤ high [i] ≤
1 ≤ C ≤ sumOf(high[i])
1≤X≤C
Input Format:
First line contains three space separated integers N, C, X respectively.
Second line contains three space separted integers, i th integer denoting high [i].
Output Format:
Print the smallest number of containers Mr. Perkins may choose.
Sample Input #00:
1 10 10
20
Sample Output #00:
1
Explantation #00: Mr. Perkins uses the subset (20). These are the minimum number of container at least X
bricks.
Sample Input #01:
5 10 7
33333
Sample Output #01:
4
Explantion #01: Mr. Perkins uses the subset (3,3,3,3). These are the minimum number of containers to be
choose such that the subset selected by Mr. Perkins contains at least X bricks.
Sample Input #02:
5 100 63
12 34 23 45 34
Sample Output #02:
3
Explanation #02: Mr. Perkins uses the subset (34,34,45). These are the minimum number of containers to be
choose such that the subset selected by Mr. Perkins contains at least X Bricks.
Answer:
Not an objective type question

13. Novell is working on creating a new mail server. You are writing part of a spam detection system. Your job is
to analyze the subject lines of e-mail messages and return a count of know spam signalling keywords in the
subject lines. Your task is made more difficult by the spammers who try to hide the keywords in several ways.
Here we will consider just one obfuscation technique: duplicating characters. Duplicating characters means
taking an existing character in a word and inserting more copies of that charcter into the same place in the
word. This process can then be repeated on a different character in the word. The spam signalling keyword
“credit” might be modified to “creddiT”, “CreddittT” or “ccrreeeddiitt”, etc., but not “credict”.
For the purposes of this problem we will consider subject lines which contain only letters and spaces. The
“words” in the subject line are delimited by spaces. A word in the subject line is cosidered a “match” if th etire
word is the same as at least one etire keyword, after possibly removing some duplicated characters from the
subject word. A keyword that matches only part of a subject word or a subject word that matches only part of a
keyword does not count. Note that if a keyword contains a double letter, the subject word must also contain (at
least) a double letter in the same position to match (“double letter” means two consecutive letters in the word
that are the same). For this application, all matches ( and the use of the term “same”) are case insensitive.
Given a subject line and a list of keywords, return the count of words in the subject line which “match” words
in the keyword list. If multiple words in the subject line match the same keyword, they are each counted , but a
word in the subject line that matches multiple keywords is only counted once.
Constraints
- subjectLine will contain between 0 and 50 characters, inclusive.
- subjectLine will include only letter (‘a’ to ‘z’ and ‘A’ to ‘Z’) and space (‘ ’) characters.
- keywords will have between 0 and 50 elements, inclusive.
- each element of keywords will contain between 1 and 50 characters, inclusive.
- each element of keywords will consist of onley letters (‘a’ to ‘z’ and ‘A’ to ‘Z’).
- The same letter (ignoring case) never appears more that twice consecutively in any element of keywords.
(ie. “aabbAAbb” is ok, but “aaAbb” is not allowed.)
Example 1
subjectLine = “LooW INTEREST RATES available don’t BE slow”
keywords = {“interest”, “rates”, “loan”, “available”, “LOW”}
Returns:4
“INTEREST” , “RATES” , “available”, and “Loow” match. Note that “slow” does not match, even
though it contains the substring “low” which is a keyword.
Example 2
subjectLine = “Dear Richard Get Rich Quick no risk”
keywords = {“rich”, “risk”, “Quicken”, “wealth”, “SAVE”}
Returns: 2
Don’t match “Richard”
Exmaple 3
subjectLine = “in debbtt againn and aAgain and AGAainIN”
keyWords = {“AGAIN”, “again”, “again”}
Returns:3

Answer:
Not an objective type question

14. HTTP (Hyper Text transfer protocol) has similarities to both ………. and …….
A. FTP:SNMP B. FTP:SMTP C. FTP:MTV D. FTP:URL

Answer : A.

Explanation: HTTP functions like a combination of FTP and SMTP . It is similar to FTP because it transfers files and
uses the services of TCP. However , it is much simpler than FTP because it uses only one TCP connection. HTTP is
like SMTP because the data transferred between the client and the server look like SMTP messages.

15. A problem encountered in multitasking when a process is perpetually denied necessary resources is called
A. Deadlock B. Starvation C. Inversion D. Aging

Answer: B
Explanantion: Starvation is a problem encountered in concurrent computing where a process is perpetually
denied necessary resources to process its work. Starvation may be caused by errors in a scheduling or mutual
exclusion algorithm, but can also be caused by resource leaks, and can be intentionally caused via a denial-of-
service attack such as a fork bomb.

16. In a depth-first traversal of a graph G with N vertices, K edges are marked as tree edges. The number of
connected components in G is
A. K B. K+1 C. N-K-1 D. N-K

Answer: D

Explanation: Tree edges are the edges that are part of DFS tree. If there are x tree edges in a tree, then
x+1 vertices in the tree.
The output of DFS is a forest if the graph is disconnected.

17. A CPU time slice is


A. A single stage in a pipelined CPU
B. The time taken to handle a timer interrupt
C. The cycle time to the CPU clock
D. The time unit of round robin process scheduling

Answer D
Explanantion: Round-robin (RR) is one of the algorithms employed by process and network schedulers in
computing. As the term is generally used, time slices (also known as time quanta) are assigned to each
process in equal portions and in circular order, handling all processes without priority (also known as cyclic
executive). Round-robin scheduling is simple, easy to implement, and starvation-free .

18. Heap allocation is required for languages


A. That support recursion
B. That support dynamic data structures
C. That use dynamic scoping rules
D. None of the above

Answer: B
Explanation: Heap allocation is needed for dynamic data structures like tree, linked list, etc. OR
To use dynamic data structures we need to use heap allocation or dynamic allocation of memory.

19. A set of processes is deadlock if


a) each process is blocked and will remain so forever
b) each process is terminated
c) all processes are trying to kill each other
d) none of the mentioned

Answer: A
Explanation: A deadlock is a situation in which two computer programs sharing the same resource are effectively
preventing each other from accessing the resource, resulting in both programs ceasing to function.

20. An interrupt vector is


A. A bit in the processor status word indicating whether or not interrupts are disabled
B. A set of bits in the processor status word indicating which interrupts have been masked
C. A CPU register containing status of interrupts that have occurred but not handled yet
D. A memory address associated with one or more I / O devices

Answer: C

Explanantion:An interrupt vector is the memory location of an interrupt handler, which prioritizes interrupts and
saves them in a queue if more than one interrupt is waiting to be handled.

21. The most relevant addressing mode to write position independent code is
A. auto – increment mode
B. direct mode
C. indexed mode
D. relative mode

Answer: D
Explanantion: -relative addressing mode can be used to load a register with a value stored in program memory
a short distance away from the current instruction. It can be seen as a special case of the "base plus offset"
addressing mode, one that selects the program counter (PC) as the "base register".

22. Which of the following statements is false?


A. A tree with N nodes has (N – 1) edges
B. A labeled rooted binary tree can be uniquely constructed given its postorder and preorder traversal results
C. A complete binary tree with N internal nodes has ( N + 1 ) leaves
D. The maximum number of nodes in a binary tree of height H is ( 2^ ( H + 1 ) -1) (^is the exponentiation
operator)

Answer: B C

Explanation: Both option (A) and (D) are correct. But option (B) is false because “a labeled rooted binary tree
can not be uniquely constructed given using its postorder and preorder traversal results”. It need inorder and
preorder/postorder for uniquely constructed binary tree.
Option (C) is also false, take counter example in given tree :

23. The most relevant addressing mode to write position independent code is
A. Auto – increment mode
B. Direct mode
C. Indexed mode
D. Relative mode

Answer: Same Question 8

24. Hardware cache memories exploit spatial locality of reference


A. By remembering which pieces of data have been accessed recently
B. When data items are re - accessed frequently
C. By remembering which cache blocks ( lines ) have been written to
D. Only if cache block ( line ) Size is greater than 1 byte
Answer: D

Explanantion:
A) It tells about time.
B) Same as A.
C) It does not remember the lines which are written only.
Suppose you read byte number 5, which also is cache line number 5, if only one byte is in one cache line.
Spatial locality says nearby bytes of accessed data is likely to be accessed next. Now there is NO bytes in
cache line number 5 which can be cached to get the benefit of locality. Had it been more than 1 byte, say 2 or
3, you would have copied that whole cache line and next accessed byte, say number 6 or 7 would have been
in cache, getting the benefit of spatial locality.

Technical

25. Which of the following is a thread safe?


A. StringBuilder B. StringBuffer
C. Both of the above D. None of the above

Answer:B

26. Which of the following is true about String?


A. String is a data type B. String is mutable
C. String is immutable D. None of the above

Answer:B

27. Which of the following is a marker interface?


A. Cloneable B. Comparable
C. Serializable D. None of the above

There are 2 correct options A,C

28. What will happen if you try to run the following code?
String str = “Java Learners”;
StringBuffer sb = new StringBuffer();
for(int i=0; i < str. Length(); i++)
sb.aoppend(str.charAt(i));
System.out.print1n(sb);
A. It will not print anything B. It will print “srenraeL avaj”
C. It will print “Java Learners” D. Error

Answer:D
Explanation: sb.append() should be there.

29. Under what situations do you obtain a default constructor?


A. When you define any class
B. When the class has no other constructors
C. When you define at least one constructor
D. None of the above
Answer:B

30. Is it possible to create an object of an empty class type such as:


Class xyz
{};
If so, what is the size of such an object?
A. Yes, it is possible, and its size is zero.
B. Yes, it is possible, and its size is greater than zero.
C. No, it is not possible to create an empty class; it results in a compiler error.
D. No, it results in a runtime error.

Answer:B(Size of the object will be 1Byte, 1 byte is the smallest memory unit that can be used as a
placeholder, and it cannot give zero size as it will not be possible to create an array of objects .)

31. What is the output of following program?


#include<iostream>
Using namespace std;
Char mem[100];
Class Base
{
Public
Base()
{
cout<<”1”;
}
-Base()
{
cout<<”2”;
}
Void* operator new (size_t bytes)
{
cout<<”3”;
return mem;
}
Void operator delete(void*q)
{
cout<<”4”;
}

};

Int main()
{
Base*b = new Base;
delete b;
return 0;
}

A. 3124 B. 1342 C. 3142 D. 1324

Answer:A
32. What does the following program print out?
main()
{
int array [] [3] = {1, 2, 3, 4, 5, 6};
int (*ptr)[3] = array;

printf(“%d %d” , (*ptr) [1], (*ptr) [2] );


++ptr;
printf(“%d %d” , (*ptr) [1], (*ptr) [2] );
}

A. 2 3 5 6 B. 2 3 4 5 C. 4 5 0 0 D. None of the above

Answer:A

33. Assume the following C declaration:


int *A[10], B[10][10];
Of the following expressions which one will not give compile-time errors if used as the left hand side
of an assignment statement in a C program?
I. A[2]
II. A[2][3]
III. B[1]
IV. B[2][3]

A. I, II and IV only B. II, III, and IV only


C. II and IV only D. IV only

Answer:A

I is valid, assigning value to pointer A[2],


II is valid, possible due to array styled indexing of pointers
IV is valid, simple assignment to 2-dimensional array

34. The following function itoa written to convert an integer into a string
Void itoa ( int n, char string[] )
{

static int i;

if ( n / 10 )
itoa ( n/10, string) ;

else {
i = 0;
if (n < 0)
string [ i++] = ‘-‘ ;
}

string [i++] = abs(n) % 10 + ‘0’ ‘


string [i] = ‘\0’ ;
}
A. Incorrectly inserts the digits from right to left
B. Is infinitely recursive for negative values
C. Uses the wrong parameters in the recursive call
D. Works correctly

Answer:D
Company Name: - BA CONTINUUM
Book Index: 179-(D)

Computer Programming

Chose the correct option


1. A programmer writes a program to find an element in the array A[5] with the elements: 8 30 40 45 70. The
program is run to find a number “X”, that is found in the first iteration of binary search. What is the value of
“X”?
A. 40 B. 8 C. 70 D. 30

Answer: A
Explanation:

In the first iteration, mid will be computed as 40. So, 40 is the element to be searched.

2. How can a call to an overloaded function be ambiguous?


A. The name of the function might have been misspelled
B. There might be two or more functions with the same name
C. There might be two or more functions with equally appropriate signatures
D. None of the above

Answer: C
Explanation:

Making a call to an overloaded function results in one of three possible outcomes:

1) A match is found. The call is resolved to a particular overloaded function.


2) No match is found. The arguments cannot be matched to any overloaded function.
3) An ambiguous match is found. The arguments matched more than one overloaded function.

A function's signature includes the function's name and the number, order and type of its formal parameters.

 Two overloaded functions must not have the same signature.


 The return value is not part of a function's signature.
 These two functions have the same signature

int Divide (int n, int m) ;

double Divide (int n, int m) ;

3.
Passage:
function MyBinarySearch(array arr, integer low, integer high, integer item)
{
if ( low > high )
}
return -1
{

integer mid = (low + high)/2

if ( arr[mid] equals item )


{
return mid
}
else if ( arr[mid]> item )
{
return //missing statement 1
}
else
{
return //missing statement 2
}
}

Chose the correct option:


A pseudo-code is used which is self explanatory.
//in pseudo code is refers to comment
Harshul uses the given code to implement Binary Search recursively. Find the statement that will replace missing
statement 2 in the given code such that it works efficiently.
A. MyBinarySearch(arr, mid+1, high, item)
B. MyBinarySearch(arr, low+1, mid-1, item)
C. MyBinarySearch(arr, low, mid-1, item)
D. MyBinarySearch(arr, mid+1, high-1, item)
Choose the correct option

Answer: A
Explanation:

We basically ignore half of the elements just after one comparison.


1. Compare x with the middle element.
2. If x matches with middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in right half sub-array after the mid element. So
we recur for right half.
4. Else (x is smaller) recur for the left half.

4. A language has 28 different letters in total. Each word in the language consists of a maximum of 7 letters. A
programmer wants to create a data type to store a word of this language. She decides to store the word as an
array of letters. How many bits should she assign to the data type to store all kinds of words of the language?
A. 7 B. 35 C. 28 D. 196

Answer: B
Explanation:
1 bit -> 2 possible states
2 bits -> 4 possible states
3 bits -> 8 possible states
4 bits -> 16 possible states
5 bits -> 32 possible states

You need 5 bits to represent all possible letters in the language (28 > 16 & 28 < 32). Since you are told you are
storing an array of letters, you will need a total of 5*7 bits = 35 bits to represent all words in the language.

5. Which of the given statements is TRUE about a breadth first search?


A. Beginning from a node, all the adjacent nodes are traversed first
B. Beginning from a node, each adjacent node is fully explored before traversing the next adjacent node
C. Beginning from a node, the nodes are traversed in cyclic order
D. None of the above

Answer: A
Explanation:
Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at
the tree root (or some arbitrary node of a graph, sometimes referred to as a 'search key’), and explores all of the
neighbor nodes at the present depth prior to moving on to the nodes at the next depth level.
6. A function in the base class is redefined in the inherited class. What is the term used to describe
7. this situation?
A. Inheritance
B. Overriding
C. Overloading
D. Encapsulation
Answer: B
Explanation:

Function Overriding (achieved at run time)


It is the redefinition of base class function in its derived class with same signature i.e return type and parameters.

It can only be done in derived class.


Example:

Class a
{
public:
virtual void display(){ cout << "hello"; }
}

Class b:public a
{
public:
void display(){ cout << "bye";};
}

8. The function given below takes an even integer “n” as the input and calculates the sum of first “n” even natural
numbers. The function is called by the statement “sum (30)”. How many times will the function “sum” be called
to compute the sum?

function sum(n)
{
if (n equals 2)
return 2
else
return(n + sum(n-2))

end
}

A. 1 B. 30 C. 15 D. 16

Answer: C
Explanation:

The function sum ( ) will only be called for even numbers between 30 & 1.There are total 15 even numbers between
30 and 1.So sum will be called 15 times.
The function calling hierarchy will be as follows:
Sum (30)
Sum (28)
Sum (26)
Sum (24)
Sum (22)
Sum (20)
.
.
.
Sum (4)
Sum (2)

9. What is the output of the program given below?


integer i = 0, j
while (i<2)
{
j = 0;
while (j<=3*i)
{
print j
print blank space
j=j+3
}
print end-of-line //takes the cursor to the next line
i=i+1
}

A. 0
03
B. 0 3
036
C. 0
036
0369
D. 0 3 6
0369
0 3 6 9 12
Answer: A
Explanation:

For i=0, j will be printed as 0.


For i=1, j will be printed as 0 and 3.

10. Code A contains a set of eight lines that occur ten times in different points of the program. This code is passed to
a programmer who puts the set of eight lines in a function definition and calls them at the ten points in the
program. Assume this new code to be Code B. Which code will run faster using an interpreter?
A. Code A
B. Code B
C. Both the codes would run at the same speed
D. None of the above
Answer: C
Explanation:

An interpreter translates code like a compiler but reads the code and immediately executes on that code, and
therefore is initially faster than a compiler. Thus, interpreters are often used in software development tools as
debugging tools, as they can execute a single in of code at a time. Compilers translate code all at once and the
processor then executes upon the machine language that the compiler produced. If changes are made to the code after
compilation, the changed code will need to be compiled and added to the compiled code (or perhaps the entire
program will need to be re-compiled.) But an interpreter, although skipping the step of compilation of the entire
program to start, is much slower to execute than the same program that’s been completely compiled. Interpreters,
however, have usefulness in areas where speed doesn’t matter (e.g., debugging and training) and it is possible to take
the entire interpreter and use it on another ISA, which makes it more portable than a compiler when working
between hardware architectures.

11. What is the minimum number of stacks of size “n” required to implement a queue of size “n”?
A. 1 B. 2 C. 3 D. 4

Answer: B
Explanation:
A queue can be implemented using two stacks. Let queue to be implemented be q and stacks used to implement q be
stack1 and stack2. q can be implemented in two ways:

Method 1 (By making enQueue operation costly)


This method makes sure that newly entered element is always at the top of stack 1, so that deQueue operation just
pops from stack1. To put the element at top of stack1, stack2 is used.

enQueue(q, x)
1) While stack1 is not empty, push everything from satck1 to stack2.
2) Push x to stack1 (assuming size of stacks is unlimited).
3) Push everything back to stack1.

dnQueue(q)
1) If stack1 is empty then error
2) Pop an item from stack1 and return it

Method 2 (By making deQueue operation costly)


In this method, in en-queue operation, the new element is entered at the top of stack1. In de-queue operation, if
stack2 is empty then all the elements are moved to stack2 and finally top of stack2 is returned.

enQueue(q, x)
1) Push x to stack1 (assuming size of stacks is unlimited).

deQueue(q)
1) If both stacks are empty then error.
2) If stack2 is empty
While stack1 is not empty, push everything from satck1 to stack2.
3) Pop the element from stack2 and return it.

12. Grace writes a recursive algorithm. But she forgot to add a termination condition and hence entered an infinite
recursion. What will this situation lead to?
A. Overflow of runtime stack
B. Underflow of runtime stack
C. Underflow of usage of registers
D. Overflow of memory I/O

Answer: A
Explanation:

Recursion is a function calling itself, repeatedly. Due to calling itself, it uses STACK memory to store the
intermediate results (intermediate functions), mostly known as activation records. Every time Recursion process will
PUSH one activation record to top of the stack. Here in our algorithm, recursion is calling infinitely. So it will do
many PUSH operations into stack. STACK has limited space to store. So after some recursive calls stack will
completely FULL. When some nth recursive call trying make PUSH operation into stack, it gives "Stack Over Flow"
or "Segmentation fault"-core dumped. Here you are trying to access an address which is not available.

13. A data type is stored as a 6-bit signed integer. Which of the given options cannot be represented by this data
type?
A. -12 B. 0 C. 32 D. 18

Answer: C
Explanation:

For n bits, the range of 2’s complement signed integers that are allowed is -2^ (n-1) to (2^ (n-1))-1.

The range of 6 bit signed integers is -32 to +31 (both numbers included). Hence, 32 cannot be represented by using 6
bits.

14. What does the following function do?


function operation (int a , int b)
{
if (a>b)
{ return operation(b, a) }
else
{ return a; }
}
A. Always returns the first parameter
B. Returns the min of (a,b)
C. Returns the max of (a,b)
D. Loops forever

Answer: B
Explanation:

It returns the smaller of the two integers passed to it. If both the integers are equal, it returns the equal value.

This is how it works. First, if condition check whether a is greater than b. If a is indeed greater than b, the function
calls itself, this time with the arguments interchanged. Otherwise, (this means a is less than or equal to b), it returns a
(hence returning the smaller-or-equal number).

15. A programmer writes an efficient program to sum two square diagonal matrices (matrices with elements only on
the diagonal positions). The size of each matrix is n X n. What is the time complexity of the algorithm?
A. Θ(n2)
B. Θ(n)
C. Θ(n^ log(n))
D. None of the above

Answer: B
Explanation:
O(n), where n is the size of the matrix. One just loops from 0 to n, and performs the addition.

for(i=0;i<n;i++)
{ c[i][i]=a[i][i] + b[i][i];
}

16. Two programmers, X and Y, are asked to write a code to evaluate the following expression:
a –b + c/(a-b) + (a-b)2

X writes the following code statements (Code A):


print (a-b) + c/(a-b) + (a-b)*(a-b)
Y writes the following code statements (Code B):
d = (a-b)
print d + c/d + d*d

Which statement is TRUE if the taken to load a value in a variable for addition, multiplication or division
between two operands is the same?
A. Code A uses lesser memory and is slower than Code B.
B. Code A uses lesser memory and is faster than Code B.
C. Code A uses more memory and is faster than Code B.
D. Code A uses more memory and is slower than Code B.

Answer: A
Explanation:

Code A does not stores the intermediate results and re-computes similar operations again. For example:
(a-b) is computed twice. Code B stores the result of similar operations in variable d and avoids re-computation.
Therefore, Code B is faster. Code B uses some extra variables for storage; therefore it uses more memory in
comparison to code A.

17. Which of the given systems does the job of executing a program?
A. Linker B. Compiler C. Interpreter D. Loader

Answer: D
Explanation:

A loader is the part of an operating system that is responsible for loading programs and libraries. It is one of the
essential stages in the process of starting a program, as it places programs into memory and prepares them for
execution.

18. What will be returned if f(a,b) is called in the following functions?


function g(int n)
{
if (n>0) return 1;
else return -1;
}

function f(int a, int b)


{
if (a>b) return g(a-b);
if (a<b) return g(b-a);
return 0;
}
A. 1 if a>b, -1 if a<b, 0 otherwise
B. Always +1
C. 0 if a equals b, +1 otherwise
D. -1 if a>b, 1 if a<b, 0 otherwise

Answer: C
Explanation:

Function f (a, b) will return 0 if a=b. g (a-b) and g (b-a) will always return a positive value equal to 1.

19. What best describes the space complexity of a program?


A. Amount of hard disk space required to store the program
B. Amount of hard disk space required to compile the program
C. Amount of memory required for the program to run
D. Amount of memory required for the program to compile

Answer: C
Explanation:

Space Complexity of an algorithm is total space taken by the algorithm with respect to the input size. Space
complexity includes both Auxiliary space and space used by input.
Auxiliary Space is the extra space or temporary space used by an algorithm.

20. Which of the given statements is TRUE about a “bipartite graph” with “n” nodes?
A. It contains n edges.
B. It contains a cycle of odd length.
C. It contains no cycle of odd length.
D. It contains n2 edges.
Answer: C
Explanation:

A bipartite graph (or bi-graph) is a graph whose vertices can be divided into two disjoint and independent sets and
such that every edge connects a vertex in to one in. Vertex sets and are usually called the parts of the graph.
Equivalently, a bipartite graph is a graph that does not contain any odd-length cycles.

21. A librarian has to rearrange the library books on a shelf in a proper order at the end of each day. Which sorting
technique should be the librarian’s ideal choice?
A. Bubble sort
B. Insertion sort
C. Selection sort
D. Heap sort

Answer: B
Explanation:
Library sort, or gapped insertion sort is a sorting algorithm that uses an insertion sort, but with gaps in the array to
accelerate subsequent insertions. The name comes from an analogy:
Suppose a librarian were to store his books alphabetically on a long shelf, starting with the As at the left end, and
continuing to the right along the shelf with no spaces between the books until the end of the Zs. If the librarian
acquired a new book that belongs to the B section, once he finds the correct space in the B section, he will have to
move every book over, from the middle of the Bs all the way down to the Zs in order to make room for the new
book. This is an insertion sort. However, if he were to leave a space after every letter, as long as there was still space
after B, he would only have to move a few books to make room for the new one. This is the basic principle of the
Library Sort.

22. A tree has 5 levels and each node has either 4 or no children. All nodes on the same level have the same number
of children. How many nodes are there in the tree?
(Note: The root is at level 1.)
A. 341 B. 256 C. 1024 D. None of the above

Answer: A
Explanation:

Height of the given tree is 4 and k=4.


No. of nodes=
(4^5-1)/4-1= 341

23. How are protected members of a base class accessed in the derived class when inherited privately in C++?
A. Privately B. Publicly C. Protectedly D. Not inherited

Answer: A
Explanation:
class base
{
public:
int x;
protected:
int y;
private:
int z;
};

class publicDerived: public base


{
// x is public
// y is protected
// z is not accessible from publicDerived
};

class protectedDerived: protected base


{
// x is protected
// y is protected
// z is not accessible from protectedDerived
};

class privateDerived: private base


{
// x is private
// y is private
// z is not accessible from privateDerived
}
24. What will be the input to the second pass, if the list before starting the Radix Sort is: 729, 150, 123, 931, 348,
517?
A. 150, 123, 348, 517,729, 931
B. 150, 931, 123, 517, 348, 729
C. 517, 729, 123, 931, 348, 150
D. 123, 150, 348, 517, 729, 931
Answer: B
Explanation:
Original, unsorted list:
729, 150, 123, 931, 348, 517
Sorting by least significant digit (1s place) gives:
150, 931, 123, 517, 348, 729
Therefore, the input to the second pass will be:

150, 931, 123, 517, 348, 729

25. What is the maximum number of edges in an undirected graph with “n” vertices?
A. n*(n-1)/2 B. n*(n+1)/2 C. n*n D. 2*n

Answer: A
Explanation:
In an undirected graph, each edge is specified by its two endpoints and order doesn't matter. The number of edges is
therefore the number of subsets of size 2 chosen from the set of vertices. Since the set of vertices has size n, the
number of such subsets is given by the binomial coefficient C(n,2) (also known as "n choose 2"). Using the formula
for binomial coefficients, C(n,2) = n(n-1)/2.

26. Which of the given sorting methods is stable?


A. Straight insertion sort B. Binary insertion sort
C. Shell sort D. Heap sort

Answer: A
Explanation:

The key step of any insertion sorting algorithm involves the insertion of an item into a sorted sequence. There are
two aspects to an insertion--finding the correct position in the sequence at which to insert the new element and
moving all the elements over to make room for the new one. Straight insertion sorting uses a linear search to locate
the position at which the next element is to be inserted.

9. Given 2 arrays of unsorted integers. Tell me which of the following process is efficient and why:
a) Sort the arrays and then merge them.
b) Merge the arrays and sort them.
Compare their complexities and given the logic of the option you do not choose.

Explanation:

Method 1 (first Concatenate then Sort)


In this case, we first append the two unsorted lists. Then we simply sort the concatenated list.
// CPP program to merge two unsorted lists
// in sorted order
#include <bits/stdc++.h>
using namespace std;

// Function to merge array in sorted order


void sortedMerge(int a[], int b[], int res[], int n, int m)
{
// Concatenate two arrays
int i = 0, j = 0, k = 0;
while (i < n) {
res[k] = a[i];
i += 1;
k += 1;
}
while (j < m) {
res[k] = b[j];
j += 1;
k += 1;
}

// sorting the res array


sort(res, res + n + m);
}
// Driver code
int main()
{
int a[] = { 10, 5, 15 };
int b[] = { 20, 3, 2, 12 };
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[0]);

// Final merge list


int res[n + m];
sortedMerge(a, b, res, n, m);

cout << "Sorted merged list :";


for (int i = 0; i < n + m; i++)
cout << " " << res[i];
cout << "n";

return 0;
}
Output :

Sorted merged list : 2 3 5 10 12 15 20

Time Complexity : O ( (n + m) (log(n + m)) )

Auxiliary Space : O ( (n + m) )

Method 2 (First Sort then Merge)


 We first sort both the given arrays separately. Then we simply merge two sorted arrays.

// CPP program to merge two unsorted lists


// in sorted order
#include <bits/stdc++.h>
using namespace std;

// Function to merge array in sorted order


void sortedMerge(int a[], int b[], int res[], int n, int m)
{
// Sorting a[] and b[]
sort(a, a + n);
sort(b, b + m);

// Merge two sorted arrays into res[]


int i = 0, j = 0, k = 0;
while (i < n && j < m) {
if (a[i] <= b[j]) {
res[k] = a[i];
i += 1;
k += 1;
} else {
res[k] = b[j];
j += 1;
k += 1;
}
}
while (i < n) { // Merging remaining
// elements of a[] (if any)
res[k] = a[i];
i += 1;
k += 1;
}
while (j < m) { // Merging remaining
// elements of b[] (if any)
res[k] = b[j];
j += 1;
k += 1;
}
}

// Driver code
int main()
{
int a[] = { 10, 5, 15 };
int b[] = { 20, 3, 2, 12 };
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[0]);

// Final merge list


int res[n + m];

sortedMerge(a, b, res, n, m);

cout << "Sorted merge list :";


for (int i = 0; i < n + m; i++)
cout << " " << res[i];
cout << "n";

return 0;
}
Output :

Sorted merge list : 2 3 5 10 12 15 20

Time Complexity : O (nlogn + mlogm + (n + m))

Space Complexity : O ( (n + m) )

Method 2 is better than method 1.

TECHNICAL INTERVIEW QUESTION


1. What is functional interface?
Answer:
A functional interface is an interface that contains only one abstract method. They can have only one
functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance
of a functional interface. A functional interface can have any number of default methods. Runnable,
ActionListener,Comparable are some of the examples of functional interfaces.
Before Java 8, we had to create anonymous inner class objects or implement these interfaces.
Java program to demonstrate functional interface

class Test
{
public static void main(String args[])
{
// create anonymous inner class object
new Thread(new Runnable()
{
@Override
public void run()
{
System.out.println("New thread created");
}
}).start();
}
}

2. What are JDK 1.8 features?

Answer:
Java 8 provides following features for Java Programming:

 Lambda expressions,
 Method references,
 Functional interfaces,
 Stream API,
 Default methods,
 Base64 Encode Decode,
 Static methods in interface,
 Optional class,
 Collectors class,
 ForEach() method,
 Parallel array sorting,
 Nashorn JavaScript Engine,
 Parallel Array Sorting,
 Type and Repating Annotations,
 IO Enhancements,
 Concurrency Enhancements,
 JDBC Enhancements etc.

3. Abstract Class?
Answer:
A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract
and non-abstract methods (method with the body).
Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract
methods. It needs to be extended and its method implemented. It cannot be instantiated.

 An abstract class must be declared with an abstract keyword.


 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the method.

4. String Class in java?


Answer:
The java.lang.String class provides a lot of methods to work on string. By the help of these methods, we can
perform operations on string such as trimming, concatenating, converting, comparing, replacing strings etc.

Java String is a powerful concept because everything is treated as a string if you submit any form in window
based, web based or mobile application.

Java String Methods such as:


String charAt()
String compareTo()
String concat()
String contains()
String endsWith()
String equals()
equalsIgnoreCase()
String format()
String getBytes() etc.

5. Linked List Implementation?


Answer:
: Algorithm for inserting elements in linked list:
Inserting At Beginning of the list

We can use the following steps to insert a new node at beginning of the single linked list...

Step 1: Create a newNode with given value.


Step 2: Check whether list is Empty (head == NULL)
Step 3: If it is Empty then, set newNode→next = NULL and head = newNode.
Step 4: If it is Not Empty then, set newNode→next = head and head = newNode.

Inserting At End of the list

We can use the following steps to insert a new node at end of the single linked list...

Step 1: Create a newNode with given value and newNode → next as NULL.
Step 2: Check whether list is Empty (head == NULL).
Step 3: If it is Empty then, set head = newNode.
Step 4: If it is Not Empty then, define a node pointer temp and initialize with head.
Step 5: Keep moving the temp to its next node until it reaches to the last node in the list (until temp → next
is equal to NULL).
Step 6: Set temp → next = newNode.

6. What is polymorphism?
Answer:
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We
can perform polymorphism in java by method overloading and method overriding.

If you overload a static method in Java, it is the example of compile time polymorphism.
Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is
resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference variable.

Example of Java Runtime Polymorphism

In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and
overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it
refers to the subclass object and subclass method overrides the Parent class method, the subclass method is
invoked at runtime.
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){


Bike b = new Splendor();//upcasting
b.run();
}
}

7. What is data abstraction?

Answer:
Data Abstraction is the property by virtue of which only the essential details are displayed to the user.
The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather
than its individual components.

Data Abstraction may also be defined as the process of identifying only the required characteristics of an
object ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other
objects of similar type and also help in classifying/grouping the objects.

Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators
will increase the speed of car or applying brakes will stop the car but he does not know about how on
pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of
the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is.
Abstract classes and Abstract methods :

 An abstract class is a class that is declared with abstract keyword.


 An abstract method is a method that is declared without an implementation.
 An abstract class may or may not have all abstract methods. Some of them can be concrete methods
 A method defined abstract must always be redefined in the subclass,thus making overriding compulsory
OR either make subclass itself abstract.
 Any class that contains one or more abstract methods must also be declared with abstract keyword.
 There can be no object of an abstract class. That is, an abstract class can not be directly instantiated with
the new operator.
 An abstract class can have parameterized constructors and default constructor is always present in an
abstract class.

8.Each and every detail about the project candidate made in Depth?

Answer:
Depends

9. How much SQL you know?

Answer:
Depends , Student can tell about queries known which is main.

11. Inheritance Concepts of Java?

Answer:
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you
can add new methods and fields in your current class also.
Why use inheritance in java

For Method Overriding (so runtime polymorphism can be achieved).


For Code Reusability.

Terms used in Inheritance


Class: A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class,
extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called
a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new class. You can use the same fields and methods already
defined in the previous class.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.

12. About Data Mining?


Answer:
Data mining is the process of discovering patterns in large data sets involving methods at the intersection of
machine learning, statistics, and database systems.[1] Data mining is an interdisciplinary subfield of
computer science with an overall goal to extract information (with intelligent methods) from a data set and
transform the information into a comprehensible structure for further use.[1][2][3][4] Data mining is the
analysis step of the "knowledge discovery in databases" process, or KDD.[5] Aside from the raw analysis
step, it also involves database and data management aspects, data pre-processing, model and inference
considerations, interestingness metrics, complexity considerations, post-processing of discovered structures,
visualization, and online updating.

Data mining involves six common classes of tasks:

Anomaly detection (outlier/change/deviation detection) – The identification of unusual data records, that
might be interesting or data errors that require further investigation.
Association rule learning (dependency modelling) – Searches for relationships between variables. For
example, a supermarket might gather data on customer purchasing habits. Using association rule learning,
the supermarket can determine which products are frequently bought together and use this information for
marketing purposes. This is sometimes referred to as market basket analysis.
Clustering – is the task of discovering groups and structures in the data that are in some way or another
"similar", without using known structures in the data.
Classification – is the task of generalizing known structure to apply to new data. For example, an e-mail
program might attempt to classify an e-mail as "legitimate" or as "spam".
Regression – attempts to find a function which models the data with the least error that is, for estimating the
relationships among data or datasets.
Summarization – providing a more compact representation of the data set, including visualization and
report generation.

13. Scheduling algorithms in Operating Systems.

Answer:
To decide which process to execute first and which process to execute last to achieve maximum CPU
utilisation, computer scientists have defined some algorithms, they are:

 First Come First Serve(FCFS) Scheduling


 Shortest-Job-First(SJF) Scheduling
 Priority Scheduling
 Round Robin(RR) Scheduling
 Multilevel Queue Scheduling
 Multilevel Feedback Queue Scheduling

First Come First Serve Scheduling

In the "First come first serve" scheduling algorithm, as the name suggests, the process which arrives first,
gets executed first, or we can say that the process which requests the CPU first, gets the CPU allocated first.

First Come First Serve, is just like FIFO(First in First out) Queue data structure, where the data element
which is added to the queue first, is the one who leaves the queue first.
This is used in Batch Systems.
It's easy to understand and implement programmatically, using a Queue data structure, where a new process
enters through the tail of the queue, and the scheduler selects process from the head of the queue.
A perfect real life example of FCFS scheduling is buying tickets at ticket counter.
Problems with FCFS Scheduling

Below we have a few shortcomings or problems with the FCFS scheduling algorithm:

It is Non Pre-emptive algorithm, which means the process priority doesn't matter.

If a process with very least priority is being executed, more like daily routine backup process, which takes
more time, and all of a sudden some other high priority process arrives, like interrupt to avoid system crash,
the high priority process will have to wait, and hence in this case, the system will crash, just because of
improper process scheduling.
Not optimal Average Waiting Time.
Resources utilization in parallel is not possible, which leads to Convoy Effect, and hence poor
resource(CPU, I/O etc) utilization.

Shortest Job First(SJF) Scheduling

Shortest Job First scheduling works on the process with the shortest burst time or duration first.

This is the best approach to minimize waiting time.


This is used in Batch Systems.
It is of two types:
Non Pre-emptive
Pre-emptive
To successfully implement it, the burst time/duration time of the processes should be known to the processor
in advance, which is practically not feasible all the time.
This scheduling algorithm is optimal if all the jobs/processes are available at the same time. (either Arrival
time is 0 for all, or Arrival time is same for all)

Priority Scheduling

Priority is assigned for each process.


Process with highest priority is executed first and so on.
Processes with same priority are executed in FCFS manner.
Priority can be decided based on memory requirements, time requirements or any other resource
requirement.
14. Given a relation, make sure it follows the 3-NF rule?

Answer:
Third Normal Form –

A relation is in third normal form, if there is no transitive dependency for non-prime attributes is it is in
second normal form.
A relation is in 3NF iff at least one of the following condition holds in every non-trivial function dependency
X –> Y

X is a super key.
Y is a prime attribute (each element of Y is part of some candidate key).

Consider relation R(A, B, C, D, E)


A -> BC,
CD -> E,
B -> D,
E -> A
All possible candidate keys in above relation are {A, E, CD, BC} All attribute are on right sides of all
functional dependencies are prime. So this is in 3rd Normal Form.

15. What is normalization in RDBMS?

Answer:
Normalization is the process of minimizing redundancy from a relation or set of relations. Redundancy in
relation may cause insertion, deletion and updation anomalies. So, it helps to minimize the redundancy in
relations. Normal forms are used to eliminate or reduce redundancy in database tables.
First Normal Form –

If a relation contain composite or multi-valued attribute, it violates first normal form or a relation is in first
normal form if it does not contain any composite or multi-valued attribute. A relation is in first normal form
if every attribute in that relation is singled valued attribute.

Second Normal Form –

To be in second normal form, a relation must be in first normal form and relation must not contain any
partial dependency. A relation is in 2NF iff it has No Partial Dependency, i.e., no non-prime attribute
(attributes which are not part of any candidate key) is dependent on any proper subset of any candidate key
of the table.

Third Normal Form –

A relation is in third normal form, if there is no transitive dependency for non-prime attributes is it is in
second normal form.
A relation is in 3NF iff at least one of the following condition holds in every non-trivial function dependency
X –> Y

X is a super key.
Y is a prime attribute (each element of Y is part of some candidate key).

Boyce-Codd Normal Form (BCNF) –

A relation R is in BCNF if R is in Third Normal Form and for every FD, LHS is super key. A relation is in
BCNF iff in every non-trivial functional dependency X –> Y, X is a super key.

16. Provide an algorithm to reverse a linked list without using recursion.

Answer:
Initialize three pointers prev as NULL, curr as head and next as NULL.
Iterate trough the linked list. In loop, do following.
// Before changing next of current,
// store next node
next = curr->next

// Now change next of current


// This is where actual reversing happens
curr->next = prev

// Move prev and curr one step forward


prev = curr
curr = next

17. Differentiate between C and C++.

Answer:
Following are some of the differences between C and C++.
 When compared to C++, C is a subset of C++. All valid C programs are valid C++ programs.
 C is a structural or procedural programming language, while C++ is an object oriented
programming language.
 In C, Functions are the fundamental building blocks, while in C++, Objects are the fundamental
building blocks.
 C doesn't have variable references, while C++ has variable references.
 C uses malloc and free for memory allocation while C++ uses new and delete for memory
allocation.
 C does not provide direct support for error handling, while C++ supports exception handling that
helps in error detection and smooth handling.
 C does not support function and operator overloading, while C++ supports both function and
operator overloading.
 C doesn't support Generic programming, while templates in C++ allow to write generic programs.
 C doesn't support namespaces while C++ supports them.

18. What is the usage of transponders?

Answer:
A passive transponder allows a computer or robot to identify an object. Magnetic labels, such as those on
credit cards and store items, are common examples. A passive transponder must be used with an active
sensor that decodes and transcribes the data the transponder contains. The transponder unit can be physically
tiny, and its information can be sensed up to several feet away.

Simple active transponders are employed in location, identification, and navigation systems for commercial
and private aircraft. An example is an RFID (radio-frequency identification) device that transmits a coded
signal when it receives a request from a monitoring or control point. The transponder output signal is
tracked, so the position of the transponder can be constantly monitored. The input (receiver) and output
(transmitter) frequencies are preassigned. Transponders of this type can operate over distances of thousands
of miles.

19. What are the different memories you know about? Which of them takes the shortest access time?

Answer:
In computer architecture, the memory hierarchy separates computer storage into a hierarchy based on
response time. Since response time, complexity, and capacity are related, the levels may also be
distinguished by their performance and controlling technologies.[1] Memory hierarchy affects performance
in computer architectural design, algorithm predictions, and lower level programming constructs involving
locality of reference.

Designing for high performance requires considering the restrictions of the memory hierarchy, i.e. the size
and capabilities of each component. Each of the various components can be viewed as part of a hierarchy of
memories (m1,m2,...,mn) in which each member mi is typically smaller and faster than the next highest
member mi+1 of the hierarchy. To limit waiting by higher levels, a lower level will respond by filling a
buffer and then signaling to activate the transfer.

There are four major storage levels.

Internal – Processor registers and cache.


Main – the system RAM and controller cards.
On-line mass storage – Secondary storage.
Off-line bulk storage – Tertiary and Off-line storage.
Internal memory i.e. registers and cache take shortest access time.
20. What are the different replacement policies?

Answer:
In a operating systems that use paging for memory management, page replacement algorithm are needed to
decide which page needed to be replaced when new page comes in. Whenever a new page is referred and not
present in memory, page fault occurs and Operating System replaces one of the existing pages with newly
needed page. Different page replacement algorithms suggest different ways to decide which page to replace.
The target for all algorithms is to reduce number of page faults.

Page Fault – A page fault is a type of interrupt, raised by the hardware when a running program accesses a
memory page that is mapped into the virtual address space, but not loaded in physical memory.

Page Replacement Algorithms :

 First In First Out (FIFO) –


 Optimal Page replacement –
 Least Recently Used –

21.Define Zombie process. How is it different from orphan process?

Answer:
Zombie Process:

A process which has finished the execution but still has entry in the process table to report to its parent
process is known as a zombie process. A child process always first becomes a zombie before being removed
from the process table. The parent process reads the exit status of the child process which reaps off the child
process entry from the process table.
Orphan Process:

A process whose parent process no more exists i.e. either finished or terminated without waiting for its child
process to terminate is called an orphan process.

22. What is a semaphore? What are the different types of semaphores?

Answer:
Semaphore is a simply a variable. This variable is used to solve critical section problem and to achieve
process synchronization in the multi processing environment.
The two most common kinds of semaphores are counting semaphores and binary semaphores. Counting
semaphore can take non-negative integer values and Binary semaphore can take the value 0 & 1. only.
Some point regarding P and V operation

P operation is also called wait, sleep or down operation and V operation is also called signal, wake-up or up
operation.
Both operations are atomic and semaphore(s) is always initialized to one.
A critical section is surrounded by both operations to implement process synchronization.See below
image.critical section of Process P is in between P and V operation.

Semaphores are of two types −


Binary semaphore

Counting semaphore

Binary Semaphore

Binary semaphore is a semaphore with the integer value ranges over 0 and 1 whereas the counting
semaphore's integer value ranges over unrestricted domain.

Binary semaphores are easier to implement comparing with the counting semaphore.

Binary semaphore allows only one thread to access the resource at a time. But counting semaphore allows N
accesses at a time. The 2 operations that are defined for binary semaphores are take and release.

Take:Taking a binary semaphore brings it in the “taken” state, trying to take a semaphore that is already
taken enters the invoking thread into a waiting queue.

Release:Releasing a binary semaphore brings it in the “not taken” state if there are not queued threads. If
there are queued threads then a thread is removed from the queue and resumed, the binary semaphore
remains in the “taken” state. Releasing a semaphore that is already in its “not taken” state has no effect.

Counting Semaphore:

Counting Semaphore may have value to be greater than one, typically used to allocate resources from a pool
of identical resources.

A counting semaphore is a synchronization object that can have an arbitrarily large number of states. The
internal state is defined by a signed integer variable, the counter.

The counter value (N) has a precise meaning:

a. Negative, there are exactly -N threads queued on the semaphore.

b. Zero, no waiting threads, a wait operation would put in queue the invoking thread.

c. Positive, no waiting threads, a wait operation would not put in queue the invoking thread.

Two operations are defined for counting semaphores:

• Wait (chSemWait() in ChibiOS/RT). This operation decreases the semaphore counter; if the result is
negative then the invoking thread is queued.

• Signal (chSemSignal() in ChibiOS/RT). This operation increases the semaphore counter, if the result is
non-negative then a waiting thread is removed from the queue and resumed.

23. Define a good platform along with its qualities.

Answer:
Question is not clear
24. Define red-black trees.

Answer:
Red-Black Tree is a self-balancing Binary Search Tree (BST) where every node follows following rules.
RedBlackTree
1) Every node has a color either red or black.

2) Root of tree is always black.

3) There are no two adjacent red nodes (A red node cannot have a red parent or red child).

4) Every path from root to a NULL node has same number of black nodes.

Why Red-Black Trees?


Most of the BST operations (e.g., search, max, min, insert, delete.. etc) take O(h) time where h is the height
of the BST. The cost of these operations may become O(n) for a skewed Binary tree. If we make sure that
height of the tree remains O(Logn) after every insertion and deletion, then we can guarantee an upper bound
of O(Logn) for all these operations. The height of a Red-Black tree is always O(Logn) where n is the number
of nodes in the tree.

25. What is the procedure to insert an element into a sorted array?


Ans: int insertSorted(int arr[], int n, int key, int capacity)
{
// Cannot insert more elements if n is already
// more than or equal to capcity
if (n >= capacity)
return n;

int i;
for (i=n-1; ( i >= 0 && arr[i] > key); i--)
arr[i+1] = arr[i];

arr[i+1] = key;

return (n+1);
}

26. What is a web server? What are the load limits in it?

Answer:
Web server refers to server software, or hardware dedicated to running said software, that can serve contents
to the World Wide Web. A web server processes incoming network requests over HTTP and several other
related protocols.
The primary function of a web server is to store, process and deliver web pages to clients. The
communication between client and server takes place using the Hypertext Transfer Protocol (HTTP). Pages
delivered are most frequently HTML documents, which may include images, style sheets and scripts in
addition to the text content.

A web server (program) has defined load limits, because it can handle only a limited number of concurrent
client connections (usually between 2 and 80,000, by default between 500 and 1,000) per IP address (and
TCP port) and it can serve only a certain maximum number of requests per second (RPS, also known as
queries per second or QPS) depending on:

its own settings,


the HTTP request type,
whether the content is static or dynamic,
whether the content is cached, and
the hardware and software limitations of the OS of the computer on which the web server runs.

When a web server is near to or over its limit, it becomes unresponsive.

27. Devise a program to sort an array using bubble sort.

Answer:
int main()
{
int array[100], n, c, d, swap;

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

for (c = 0 ; c < n - 1; c++)


{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}

printf("Sorted list in ascending order:\n");

for (c = 0; c < n; c++)


printf("%d\n", array[c]);

return 0;
}

28. What is piggy backing?


Answer:
In two-way communication, wherever a frame is received, the receiver waits and does not send the control
frame (acknowledgement or ACK) back to the sender immediately.The receiver waits until its network layer
passes in the next data packet. The delayed acknowledgement is then attached to this outgoing data frame.
This technique of temporarily delaying the acknowledgement so that it can be hooked with next outgoing
data frame is known as piggybacking.

Whenever party A wants to send data to party B, it will send the data along with this ACK field. Considering
the sliding window here of size 8 bits, if A has send frames up to 5 correctly (from B), and wants to send
frames starting from frame 6, it will send ACK6 with the data.

Three rules govern the piggybacking data transfer.

If station A wants to send both data and an acknowledgment, it keeps both fields there.
If station A wants to send just the acknowledgment, then a separate ACK frame is sent.
If station A wants to send just the data, then the last acknowledgment field is sent along with the data.
Station B simply ignores this duplicate ACK frame upon receiving .

29. Given an array of integers, devise a program to replace every element with the next greatest element on
the right side in the array. Also, replace the last element with 5 as there no element on the right side of it.
Ans: void nextGreatest(int arr[], int size)
{
// Initialize the next greatest element
int max_from_right = arr[size-1];

// The next greatest element for the rightmost element


// is always -1
arr[size-1] = -1;

// Replace all other elements with the next greatest


for(int i = size-2; i >= 0; i--)
{
// Store the current element (needed later for updating
// the next greatest element)
int temp = arr[i];

// Replace current element with the next greatest


arr[i] = max_from_right;

// Update the greatest element, if needed


if(max_from_right < temp)
max_from_right = temp;
}
}

30. What is garbage collection in Java?

Answer:
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is
a way to destroy the unused objects.
Advantage of Garbage Collection

It makes java memory efficient because garbage collector removes the unreferenced objects from heap
memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

How can an object be unreferenced?

There are many ways:

By nulling the reference


By assigning a reference to another
By anonymous object etc.

31. What are pointers in C? Give an example where to illustrate their significance.

Answer:
: A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory
location. Like any variable or constant, you must declare a pointer before using it to store any variable
address. The general form of a pointer variable declaration is −

type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer
variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in
this statement the asterisk is being used to designate a variable as a pointer.
int main () {

int var = 20; /* actual variable declaration */


int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */


printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */


printf("Value of *ip variable: %d\n", *ip );

return 0;
}

32. What is HTTP? Give some of its methods.

Answer:
The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative,
hypermedia information systems. This is the foundation for data communication for the World Wide Web
(i.e. internet) since 1990. HTTP is a generic and stateless protocol which can be used for other purposes as
well using extensions of its request methods, error codes, and headers.
Basically, HTTP is a TCP/IP based communication protocol, that is used to deliver data (HTML files, image
files, query results, etc.) on the World Wide Web. The default port is TCP 80, but other ports can be used as
well. It provides a standardized way for computers to communicate with each other. HTTP specification
specifies how clients' request data will be constructed and sent to the server, and how the servers respond to
these requests.
Basic Features

There are three basic features that make HTTP a simple but powerful protocol:

HTTP is connectionless: The HTTP client, i.e., a browser initiates an HTTP request and after a request is
made, the client disconnects from the server and waits for a response. The server processes the request and
re-establishes the connection with the client to send a response back.

HTTP is media independent: It means, any type of data can be sent by HTTP as long as both the client and
the server know how to handle the data content. It is required for the client as well as the server to specify
the content type using appropriate MIME-type.

HTTP is stateless: As mentioned above, HTTP is connectionless and it is a direct result of HTTP being a
stateless protocol. The server and client are aware of each other only during a current request. Afterwards,
both of them forget about each other. Due to this nature of the protocol, neither the client nor the browser can
retain information between different requests across the web pages.
HTTP Method and Description
1 GET:The GET method is used to retrieve information from the given server using a given URI. Requests
using GET should only retrieve data and should have no other effect on the data.

2 HEAD:Same as GET, but transfers the status line and header section only.

3 POST:A POST request is used to send data to the server, for example, customer information, file upload,
etc. using HTML forms.

4 PUT:Replaces all current representations of the target resource with the uploaded content.

5 DELETE:Removes all current representations of the target resource given by a URI.

6 CONNECT:Establishes a tunnel to the server identified by a given URI.

7 OPTIONS:Describes the communication options for the target resource.

8 TRACE:Performs a message loop-back test along the path to the target resource.

33. Briefly describe a B+ tree. What is bulk loading in it?

Answer:
A B+ tree is an N-ary tree with a variable but often large number of children per node. A B+ tree consists of
a root, internal nodes and leaves.The root may be either a leaf or a node with two or more children.
A B+ tree can be viewed as a B-tree in which each node contains only keys (not key–value pairs), and to
which an additional level is added at the bottom with linked leaves.

The primary value of a B+ tree is in storing data for efficient retrieval in a block-oriented storage context —
in particular, filesystems. This is primarily because unlike binary search trees, B+ trees have very high
fanout (number of pointers to child nodes in a node, typically on the order of 100 or more), which reduces
the number of I/O operations required to find an element in the tree.

Bulk-loading

Given a collection of data records, we want to create a B+ tree index on some key field. One approach is to
insert each record into an empty tree. However, it is quite expensive, because each entry requires us to start
from the root and go down to the appropriate leaf page. An efficient alternative is to use bulk-loading.

The first step is to sort the data entries according to a search key in ascending order.
We allocate an empty page to serve as the root, and insert a pointer to the first page of entries into it.
When the root is full, we split the root, and create a new root page.
Keep inserting entries to the right most index page just above the leaf level, until all entries are indexed.

34. What are literals in C++?

Answer:
:Constants refer to fixed values that the program may not alter and they are called literals.Constants can be of
any of the basic data types and can be divided into Integer Numerals, Floating-Point Numerals, Characters,
Strings and Boolean Values.

Again, constants are treated just like regular variables except that their values cannot be modified after their
definition.
Integer Literals

An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or
0X for hexadecimal, 0 for octal, and nothing for decimal.
212
215u

Floating-point Literals

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can
represent floating point literals either in decimal form or exponential form.
3.14159
314159E-5L

Boolean Literals

There are two Boolean literals and they are part of standard C++ keywords −

A value of true representing true.

A value of false representing false

Character Literals
Character literals are enclosed in single quotes. If the literal begins with L (uppercase only), it is a wide
character literal (e.g., L'x') and should be stored in wchar_t type of variable . Otherwise, it is a narrow
character literal (e.g., 'x') and can be stored in a simple variable of char type.

String Literals

String literals are enclosed in double quotes. A string contains characters that are similar to character literals:
plain characters, escape sequences, and universal characters.
"hello, dear"

35. Describe the merge sort principle and what will be its time complexity?
Ans: Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the
two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The
merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two
sorted sub-arrays into one.

MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)

Time Complexity: Sorting arrays on different machines. Merge Sort is a recursive algorithm and time
complexity can be expressed as following recurrence relation.

T(n) = 2T(n/2) +
The above recurrence can be solved either using Recurrence Tree method or Master method. It falls in case

II of Master Method and solution of the recurrence is .

Time complexity of Merge Sort is in all 3 cases (worst, average and best) as merge sort
always divides the array in two halves and take linear time to merge two halves.
Company Name: NEXT SCM
Book Index: 181-(D)

TECHNICAL INTERVIEW

1. Write a java program snippet for thread synchronisation concept.


Ans: Following is an example of multi threading with synchronized.
// A Java program to demonstrate working of
// synchronized.
import java.io.*;
import java.util.*;

// A Class used to send a message


class Sender
{
public void send(String msg)
{
System.out.println("Sending\t" + msg );
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}

// Class for send a message using Threads


class ThreadedSend extends Thread
{
private String msg;
private Thread t;
Sender sender;

// Recieves a message object and a string


// message to be sent
ThreadedSend(String m, Sender obj)
{
msg = m;
sender = obj;
}

public void run()


{
// Only one thread can send a message
// at a time.
synchronized(sender)
{
// synchronizing the snd object
sender.send(msg);
}
}
}

// Driver class
class SyncDemo
{
public static void main(String args[])
{
Sender snd = new Sender();
ThreadedSend S1 =
new ThreadedSend( " Hi " , snd );
ThreadedSend S2 =
new ThreadedSend( " Bye " , snd );

// Start two threads of ThreadedSend type


S1.start();
S2.start();

// wait for threads to end


try
{
S1.join();
S2.join();
}
catch(Exception e)
{
System.out.println("Interrupted");
}
}
}

Output:

Sending Hi

Hi Sent
Sending Bye

Bye Sent

The output is same every-time we run the program.


In the above example, we chose to synchronize the Sender object inside the run() method of the
ThreadedSend class. Alternately, we could define the whole send() block as synchronized and it
would produce the same result. Then we don’t have to synchronize the Message object inside
the run() method in ThreadedSend class.
// An alternate implementation to demonstrate
// that we can use synchronized with method also.
class Sender
{
public synchronized void send(String msg)
{
System.out.println("Sending\t" + msg );
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}

We do not always have to synchronize a whole method. Sometimes it is preferable


to synchronize only part of a method. Java synchronized blocks inside methods makes this
possible.
// One more alternate implementation to demonstrate
// that synchronized can be used with only a part of
// method
class Sender
{
public void send(String msg)
{
synchronized(this)
{
System.out.println("Sending\t" + msg );
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("Thread interrupted.");
}
System.out.println("\n" + msg + "Sent");
}
}
}

2. Basic functionality of my project


Ans: Depends on student’s Project and IDEA.

3. Explain software development life cycle.


Ans: The software development life cycle (SDLC) is a framework defining tasks performed at
each step in the software development process. SDLC is a structure followed by a development
team within the software organization. It consists of a detailed plan describing how to develop,
maintain and replace specific software. The life cycle defines a methodology for improving the
quality of software and the overall development process.
The software development life cycle is also known as the software development process.
SDLC consists of following activities:
1. Planning: The most important parts of software development, requirement gathering or
requirement analysis are usually done by the most skilled and experienced software
engineers in the organization. After the requirements are gathered from the client, a scope
document is created in which the scope of the project is determined and documented.
2. Implementation: The software engineers start writing the code according to the client's
requirements.
3. Testing: This is the process of finding defects or bugs in the created software.
4. Documentation: Every step in the project is documented for future reference and for the
improvement of the software in the development process. The design documentation may
include writing the application programming interface (API).
5. Deployment and maintenance: The software is deployed after it has been approved for
release.
6. Maintaining: Software maintenance is done for future reference. Software improvement
and new requirements (change requests) can take longer than the time needed to create
the initial development of the software.

4. Explain SDLC model.


Ans: There are several software development models followed by various organizations:

 Waterfall Model: This model involves finishing each phase completely before commencing
the next one. When each phase is completed successfully, it is reviewed to see if the
project is on track and whether it is feasible to continue.
 V-Shaped Model: This model focuses on the execution of processes in a sequential
manner, similar to the waterfall model but with more importance placed on testing. Testing
procedures are written even before the commencement of writing code. A system plan is
generated before starting the development phase.
 Incremental Model: This life cycle model involves multiple development cycles. The cycles
are divided up into smaller iterations. These iterations can be easily managed and go
through a set of phases including requirements, design, implementation and testing. A
working version of the software is produced during the first iteration, so working software is
created early in the development process.

5. SQL date function and sysdate function.

Ans: In SQL, dates are complicated for newbies, since while working with database, the format of the date in table
must be matched with the input date in order to insert. In various scenarios instead of date, datetime (time is also
involved with date) is used.

The DATE() function extracts the date part of a date or date/time expression.

Syntax
DATE(date)

Where date is a valid date expression.


Example

Assume we have the following "Orders" table:

OrderId ProductName OrderDate

1 Jarlsberg Cheese 2014-11-22 13:23:44.657


The following SELECT statement:
SELECT ProductName, DATE(OrderDate) AS OrderDate
FROM Orders
WHERE OrderId=1

will result in this:

ProductName OrderDate

Jarlsberg Cheese 2014-11-22

SYSDATE()

MySQL SYSDATE() returns the current date and time in YYYY-MM-DD HH:MM:SS or
YYYYMMDDHHMMSS.uuuuuu format depending on the context of the function.

Note: For example codes using SYSDATE(), your output may vary from the output shown.

Syntax:

SYSDATE()

Example:

The following statement will return current date and time.

Code:

SELECT SYSDATE();

Sample Output:

mysql> SELECT SYSDATE();


+---------------------+
| SYSDATE() |
+---------------------+
| 2015-04-14 12:50:44 |
+---------------------+
1 row in set (0.00 sec)

6. Round () function in SQL.

Ans: The ROUND() Function


The ROUND() function is used to round a numeric field to the number of decimals specified.

Note: Many database systems do rounding differently than you might expect. When rounding a number with a
fractional part to an integer, our school teachers told us to round .1 through .4 DOWN to the next lower integer,
and .5 through .9 UP to the next higher integer. But if all the digits 1 through 9 are equally likely, this introduces a
slight bias towards infinity, since we always round .5 up. Many database systems have adopted the IEEE 754
standard for arithmetic operations, according to which the default rounding behavior is "round half to even." In this
scheme, .5 is rounded to the nearest even integer. So, both 11.5 and 12.5 would be rounded to 12.

7. Difference between abstract class and interface.


Ans: An Interface contains only the definition / signature of functionality, and if we have some common
functionality as well as common signatures, then we need to use an abstract class. By using an abstract class, we
can provide behavior as well as functionality both in the same time. Another developer inheriting abstract class
can use this functionality easily, as they would only need to fill in the blanks.

8. Difference between union and unionAll.

Ans: UNION

UNION combines the result set of two or more queries into a single result set. This result set includes all the
rows that belong to all queries in the UNION.
The following points need to be considered when using the UNION operator:

 The number of columns and sequence of columns must be the same in all queries
 The data types must be compatible.

Syntax

1. Select Col1, Col2, Clo3 from Table1


2. UNION
3. Select Col1, Col2, Clo3 from Table2

Example

Consider the following example. I have two tables that have Id, name and phone number columns.

1. DECLARE @Table1 AS Table (ID INT, Name VARCHAR(10), PhoneNumber VARCHAR(12))


2. DECLARE @Table2 AS Table (ID INT, Name VARCHAR(10), PhoneNumber VARCHAR(12))
3.
4. INSERT INTO @Table1 VALUES(1,'Tejas', '88996655')
5. INSERT INTO @Table1 VALUES(2,'Jignesh', '99986655')
6.
7. INSERT INTO @Table2 VALUES(1,'Rakesh', '88446655')
8. INSERT INTO @Table2 VALUES(2,'Purvi', '99986655')
9.
10. SELECT * FROM @Table1
11. UNION
12. SELECT * FROM @Table2

Output

UNION ALL

UNION ALL is very similar to UNION. It also includes duplicate rows in the result set.

Behavior of UNION / UNION ALL operator with Duplicate Data

UNION always returns distinct rows. In other words it eliminates duplicate rows from the result set.

Example

Consider the following example. I have two tables and both has two rows. One row is common to both tables.
When we union these two tables it returns three rows (removes duplicate rows from the result set).
1. DECLARE @Table1 AS Table (ID INT, Name VARCHAR(10), PhoneNumber VARCHAR(12))
2. DECLARE @Table2 AS Table (ID INT, Name VARCHAR(10), PhoneNumber VARCHAR(12))
3.
4. INSERT INTO @Table1 VALUES(1,'Tejas', '88996655')
5. INSERT INTO @Table1 VALUES(2,'Jignesh', '99986655')
6.
7. INSERT INTO @Table2 VALUES(1,'Rakesh', '88446655')
8. INSERT INTO @Table2 VALUES(2,'Jignesh', '99986655')
9.
10. SELECT * FROM @Table1
11. UNION
12. SELECT * FROM @Table2

Output

9. Difference between Arraylist and Vector

Ans: ArrayList and Vector both implements List interface and maintains insertion order.

But there are many differences between ArrayList and Vector classes that are given below.

ArrayList Vector

1) ArrayList is not synchronized. Vector is synchronized.

2) ArrayList increments 50% of current Vector increments 100% means


array size if number of element exceeds doubles the array size if total number
from its capacity. of element exceeds than its capacity.

3) ArrayList is not a legacy class, it is Vector is a legacy class.


introduced in JDK 1.2.

4) ArrayList is fast because it is non- Vector is slow because it is


synchronized. synchronized i.e. in multithreading
environment, it will hold the other
threads in runnable or non-runnable
state until current thread releases the
lock of object.
5) ArrayList uses Iterator interface to Vector uses Enumeration interface to
traverse the elements. traverse the elements. But it can use
Iterator also.

10. In between Arraylist and vector which one is better.

Ans: Always ArrayList will shows better performance compared to Vector, except
Synchronization both are almost same in their performance. Vector is Synchronized means
thread safe, only 1 thread can access so its very slow compared to ArrayList, because in our
real time projects we should not require synchronized methods always.

What am saying is always try to use ArrayList rather Vector if its not required
any Synchronization in your requirements, even if so you know how to make ArrayList as
synchronized right (just like above).

11. Explain string function


Ans: C – String functions
12. Explain types of polymorphism

Ans: The word polymorphism means having many forms. In simple words, we can define polymorphism as the
ability of a message to be displayed in more than one form.
Real life example of polymorphism, a person at a same time can have different characteristic. Like a man at a same
time is a father, a husband, a employee. So a same person posses have different behavior in different situations. This
is called polymorphism.
Polymorphism is considered as one of the important features of Object Oriented Programming.
In C++ polymorphism is mainly divided into two types:
 Compile time Polymorphism
 Runtime Polymorphism
1. Compile time polymorphism: This type of polymorphism is achieved by function overloading or operator
overloading.

Function Overloading: When there are multiple functions with same name but different parameters then these
functions are said to be overloaded. Functions can be overloaded by change in number of
arguments or/and change in type of arguments.
Rules of Function Overloading
// C++ program for function overloading
#include <bits/stdc++.h>

using namespace std;


class Geeks
{
public:

// function with 1 int parameter


void func(int x)
{
cout << "value of x is " << x << endl;
}

// function with same name but 1 double parameter


void func(double x)
{
cout << "value of x is " << x << endl;
}

// function with same name and 2 int parameters


void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y << endl;
}
};

int main() {

Geeks obj1;

// Which function is called will depend on the parameters passed


// The first 'func' is called
obj1.func(7);
// The second 'func' is called
obj1.func(9.132);

// The third 'func' is called


obj1.func(85,64);
return 0;
}

Output:

value of x is 7

value of x is 9.132

value of x and y is 85, 64

In the above example, a single function named func acts differently in three different situations which is the property
of polymorphism.

1.
 Operator Overloading: C++ also provide option to overload operators. For example, we can make
the operator (‘+’) for string class to concatenate two strings. We know that this is the addition
operator whose task is to add to operands. So a single operator ‘+’ when placed between integer
operands , adds them and when placed between string operands, concatenates them.
 Example:
// CPP program to illustrate
// Operator Overloading
#include<iostream>
using namespace std;

class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}

// This is automatically called when '+' is used with


// between two Complex objects
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
 Run on IDE

 Output:

 12 + i9

 In the above example the operator ‘+’ is overloaded. The operator ‘+’ is an addition operator and can
add two numbers(integers or floating point) but here the operator is made to perform addition of two
imaginary or complex numbers. To learn operator overloading in details visit this link.
2. Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.
 Function overriding on the other hand occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.
// C++ program for function overriding

#include <bits/stdc++.h>
using namespace std;

class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }

void show ()
{ cout<< "show base class" <<endl; }
};

class derived:public base


{
public:
void print () //print () is already virtual function in derived class, we could
{ cout<< "print derived class" <<endl; }

void show ()
{ cout<< "show derived class" <<endl; }
};

//main function
int main()
{
base *bptr;
derived d;
bptr = &d;

//virtual function, binded at runtime (Runtime polymorphism)


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();

return 0;
}

Output:

print base class

show derived class

13. Difference between checked and unchecked error?


Ans:
CHECKED EXCEPTION UNCHECKED EXCEPTION

The compiler checks the checked exception. The compiler does not check the Unchecked

exception.

Except "RuntimeException" class all the child "RuntimeException" class and its child classes,

classes of the class "Exception", and the "Error" are"Unchecked Exceptions".

class and its child classes are Checked Exception.

If we do not handle the checked exception, then the Even if we do not handle the unchecked

compiler objects. exception, the compiler doesn't object.

The program doesn't compile if there is an The program compiles successfully even if

unhandled checked exception in the program code. there is an unhandled unchecked exception in

the program code.

14. What if we directly use run method to start a thread?


Ans:

o Each thread starts in a separate call stack.


o Invoking the run() method from main thread, the run() method goes onto
the current call stack rather than at the beginning of a new call stack.

class TestCallRun1 extends Thread{


public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestCallRun1 t1=new TestCallRun1();
t1.run();//fine, but does not start a separate call stack
}
}
Test it Now
Output:running...

Problem if you direct call run() method


class TestCallRun2 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e)
{System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestCallRun2 t1=new TestCallRun2();
TestCallRun2 t2=new TestCallRun2();

t1.run();
t2.run();
}
}
Test it Now
Output:1
2
3
4
5
1
2
3
4
5
As you can see in the above program that there is no context-switching because
here t1 and t2 will be treated as normal object not thread object.

15. What is different in extend Thread class and implement Runnable interface?
Ans:Java provides multithreading to parallelize execution of tasks (code) and you need threads to run multiple things
in parallel e.g. download a file in the background and show the progress bar at front-end. There are two ways to
create a Thread in Java, first by extending java.lang.Thread class and second by implementing
the java.lang.Runnable interface. Since interviewer loves comparison based questions, what is the difference
between extending thread and implementing Runnable is also a popular Java thread question. In this article, I'll tell
you how to answer this question by explaining the difference between extending the Thread class and implementing
the Runnable interface, and which one is the better way to create threads In Java. Both approaches have their pros
and cons and there is a situation when extending Thread is logical but in most cases implementing Runnable is the
better option. Let's see the difference between extends Thread and implements Runnable in Java.

Extends Thread vs implements Runnable


In order to download a file in the background and show the progress bar in GUI you need two threads, first one
to download the file and second one to show the progress bar. Even though Java provides Thread class and
multi-threading it's programmer's responsibility to create and manage threads. Though, JDK 5 also
provides Executor framework which can handle creation and management of threads but as a Java developer,
you should know how to create, start, stop, and pause thread by yourself.

As I said, there are two main ways to create a thread in Java, by extending Thread class and
overriding run() method or by implementing Runnable interface and overriding run() method, let's see the
advantages and disadvantage and differences between these two approaches.

1) The first and most important difference between extending Thread and implementing Runnable comes from
the fact that a class can only extend one class in Java. So if you extend the Thread class then your class lose
that option and it cannot extend another class, but if you implement Runnable then your Thread class can still
extend another class e.g. Canvas. It's a common pattern in Java GUI programming that your class
extends Canvas and implements Runnable, EventListener etc.

2) The second difference between extends Thread and implements Runnable is that using the Runnable instance
to encapsulate the code which should run in parallel provides better reusability. You can pass that Runnable to
any other thread or thread pool.

3) The third difference comes from OOP perspective. In case, you implement Runnable, both Task and Executor
( a thread which execute the task) are loosely coupled but if you extend Thread then they are tightly coupled.
4) Another difference between Thread and Runnable comes from the fact that you are extending Thread class
just for run() method but you will get overhead of all other methods which come from Thread class. So, if your
goal is to just write some code in run() method for parallel execution then use Runnable instead of
extending Thread class.

5) The fifth difference between extending Thread and implementing Runnable also comes from OOP
perspective. In Object oriented programming you extend a class to enhance it, to put some new features on it. So,
if you just want to reuse the run() method, then stick with implementing the Runnable interface rather than
extending Thread class.
6) It's easier to maintain code encapsulated in Runnable interface because you only need to make the change in
one place but if that code is scattered around multiple Thread class, you need to make the change at multiple
places.

7) Last but not the least difference between extends Thread and implements Runnable is that it's good coding
practice to use Runnable for the specifying task as you can reuse it on Thread as well as on Executor framework.

16. Explain inner join and outer join.


Ans:Inner join - An inner join using either of the equivalent queries gives the intersection of the two tables, i.e.
the two rows they have in common.
Left outer join - A left outer join will give all rows in A, plus any common rows in B.
Full outer join - A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B.
If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa.

17.

Difference between left join and right join


Ans:LEFT JOIN: Return all rows from the left table, and the matched rows from the right table

RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table

18. Explain OOPs Concepts.


Ans: Object Oriented programming is a programming style that is associated with the concept of Class, Objects and
various other concepts revolving around these two, like Inheritance, Polymorphism, Abstraction, Encapsulation etc.

Class
Here we can take Human Being as a class. A class is a blueprint for any functional entity which defines its
properties and its functions. Like Human Being, having body parts, and performing various actions.

Inheritance
Considering HumanBeing a class, which has properties like hands, legs, eyes etc, and functions like walk, talk, eat,
see etc. Male and Female are also classes, but most of the properties and functions are included in HumanBeing,
hence they can inherit everything from class HumanBeing using the concept of Inheritance.

Objects
My name is Abhishek, and I am an instance/object of class Male. When we say, Human Being, Male or Female, we
just mean a kind, you, your friend, me we are the forms of these classes. We have a physical existence while a class
is just a logical definition. We are the objects.

Abstraction
Abstraction means, showcasing only the required things to the outside world while hiding the details. Continuing our
example, Human Being's can talk, walk, hear, eat, but the details are hidden from the outside world. We can take
our skin as the Abstraction factor in our case, hiding the inside mechanism.

Encapsulation
This concept is a little tricky to explain with our example. Our Legs are binded to help us walk. Our hands, help us
hold things. This binding of the properties to functions is called Encapsulation.

Polymorphism
Polymorphism is a concept, which allows us to redefine the way something works, by either changing how it is done
or by changing the parts using which it is done. Both the ways have different terms for them.

If we walk using our hands, and not legs, here we will change the parts used to perform something. Hence this is
called Overloading.

And if there is a defined way of walking, but I wish to walk differently, but using my legs, like everyone else. Then I
can walk like I want, this will be called as Overriding

19. Overloading and overriding


Ans:

1. Overloading happens at compile-time while Overriding happens at runtime: The binding of overloaded
method call to its definition has happens at compile-time however binding of overridden method call to its
definition happens at runtime.
2. Static methods can be overloaded which means a class can have more than one static method of same name.
Static methods cannot be overridden, even if you declare a same static method in child class it has nothing to
do with the same method of parent class.
3. The most basic difference is that overloading is being done in the same class while for overriding base and
child classes are required. Overriding is all about giving a specific implementation to the inherited method of
parent class.
4. Static binding is being used for overloaded methods and dynamic binding is being used for
overridden/overriding methods.
5. Performance: Overloading gives better performance compared to overriding. The reason is that the binding
of overridden methods is being done at runtime.
6. private and final methods can be overloaded but they cannot be overridden. It means a class can have more
than one private/final methods of same name but a child class cannot override the private/final methods of
their base class.
7. Return type of method does not matter in case of method overloading, it can be same or different. However
in case of method overriding the overriding method can have more specific return type (refer this).
8. Argument list should be different while doing method overloading. Argument list should be same in method
Overriding.

20. What is stream


Ans: A stream is an abstraction that represents a device on which input and ouput operations are performed. A
stream can basically be represented as a source or destination of characters of indefinite length.

Streams are generally associated to a physical source or destination of characters, like a disk file, the keyboard,
or the console, so the characters gotten or written to/from our abstraction called stream are physically
input/output to the physical device. For example, file streams are C++ objects to manipulate and interact with
files; Once a file stream is used to open a file, any input or output operation performed on that stream is
physically reflected in the file.
To operate with streams, C++ provides the standard iostream library

21. Multiple inheritance


Ans:Multiple Inheritance in Java is nothing but one class extending more than one class. Previous versions of
Java(until JDk 7) doesn’t support Multiple Inheritancebecause it causes a famous problem called “Diamond
Problem“ and hence indirectly Multiple Inheritance in Java is achieved using Interfaces. After the introduction
of Default Methods in Java 8, even the interfaces can also have the method bodies

22. Array
Ans:When there is a need to use many variables then There is a big problem because we will Conflict with name of
variables So that in this Situation where we wants to Operate on many numbers then we can use array . The Number
of Variables also increases the complexity of the Program. So that we uses Arrays.
Arrays are Set of Elements having same data type or we can Say that Arrays are Collection of Elements having same
name and same data type But Always Remember Arrays are Always Start From its index value and the index of
array is start From 0 to n-1.

Suppose we wants to Access 5th Element of array then we will use 4th Element Because Arrays are Start From 0 and
arrays are always stored in Continuous Memory Locations The Number of Elements and Types of array are
Identified by Subscript of array Elements. The Various types of Array those are provided by c as Follows:-

1. Single Dimensional Array

2. Two Dimensional Array

3. Three Dimensional array

4. Character Array or Strings.

A dimensional is used representing the elements of the array for example


int a[5]
The [] is used for dimensional or the sub-script of the array that is generally used for declaring the elements of the
array For Accessing the Element from the array we can use the Subscript of the Array like this
a[3]=100
This will set the value of 4th element of array
So there is only the single bracket then it called the Single Dimensional Array
This is also called as the Single Dimensional Array

23. Character array

Ans:You can have an array of any data type: integer, float, double etc. You can even have character arrays which
can store strings. A string is an array of characters terminated by the null character (‘\0’). For example, if we store
the word "hello" in a character array, the individual characters of "hello" will be stored and the last character of the
array will be a null character (‘\0’). It is the null character that denotes the end of the string (this is very important
when doing string operations –without the null character we will not be able to identify the end of the string in
memory). The character data type can store only a single character but a character array can take in a consecutive
series of characters depending on the size of the character array.

Example:

char word[6]={'h','e','l','l','o','\0'};

You have to provide space to accommodate the null character. You can also assign a string constant directly as
below:

char word[6]="Hello";

"Hello" is called a string constant and the compiler will automatically add the null character to the array.

The following declaration:

char word[6]="Helloo"; //ERROR

is incorrect and will produce a compile error because there is no space for adding the null character. But if you don’t
specify the size of the array then it is acceptable:

char word[ ]="Helloo";

In this case while compiling the compiler will set the size of the array and provide space for the null character also.

Beware: You can assign a string literal to a character array only at the time of declaration. You cannot use:

word[6]="Helloo"; //WRONG

Another Example:

char name[10];

The above declaration declares an array of character type that can store 10 characters. The name of the array is
‘name’.

// A program for getting the name of a person and displaying the name
# include <iostream.h>
int main ( )
{
char name[15];
cout<< "Enter your name : ";
cin>> name;
cout<< "Your name is "<<name;
return 0;
}

24. Database

Ans:: Database is a systematic collection of data. Databases support storage and manipulation of data. Databases
make data management easy. Let's discuss few examples.

An online telephone directory would definitely use database to store data pertaining to people, phone numbers, other
contact details, etc.

Your electricity service provider is obviously using a database to manage billing , client related issues, to handle
fault data, etc.

Let's also consider the facebook. It needs to store, manipulate and present data related to members, their friends,
member activities, messages, advertisements and lot more.

We can provide countless number of examples for usage of databases .

25. Try and catch

Ans: Errors can be broadly categorized into two types. We will discuss them one by one.

1. Compile Time Errors

2. Run Time Errors


Compile Time Errors – Errors caught during compiled time is called Compile time errors. Compile time errors
include library reference, syntax error or incorrect class import.

Run Time Errors - They are also known as exceptions. An exception caught during run time creates serious issues.

Errors hinder normal execution of program. Exception handling is the process of handling errors and exceptions in
such a way that they do not hinder normal execution of the system. For example, User divides a number by zero, this
will compile successfully but an exception or run time error will occur due to which our applications will be crashed.
In order to avoid this we'll introduce exception handling technics in our code.

In C++, Error handling is done by three keywords:-

 Try

 Catch

 Throw

Syntax:
Try
{
//code
throw parameter;
}
catch(exceptionname ex)
{
//code to handle exception
}

Try
Try block is intended to throw exceptions, which is followed by catch blocks. Only one try block.

Catch
Catch block is intended to catch the error and handle the exception condition. We can have multiple catch blocks.

Throw
It is used to throw exceptions to exception handler i.e. it is used to communicate information about error. A throw
expression accepts one parameter and that parameter is passed to handler.
Drive Name: EPAM
Book Index: 183-(D)
TECHNICAL INTERVIEW

2. What is runtime polymorphism or dynamic method dispatch?

Explanation:
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is
resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a super class. The determination of
the method to be called is based on the object being referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting:-

When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:

class A{}

class B extends A{}

A a=new B();//upcasting

Example of Runtime Polymorphism:-

In this example, we are creating two classes vehical and pulsor. pulsor class extends vehical class and overrides its
run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass
object and subclass method overrides the Parent class method, subclass method is invoked at runtime.

note: Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism

class vehical{

void run(){System.out.println("running");}

class pulsor extends vehical{

void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){

vehical b = new pulsor(); //upcasting

b.run();

}
}

3. What is the difference between abstract classes and interfaces?

Explanation:

The main differences between abstract class and interface are given bellow.

Abstract class
1)abstract class can extend only one class or one
abstract class at a time Interface
2)A class can extend only one abstract class 1)Interface can extend any number of interfaces at a
3)abstract class can have protected , public and public time
abstract methods 2)A class can implement any number of interfaces
4)abstract class can have static methods 3)Interface can have only public abstract methods i.e.
5) Abstract class can have constructor. by default
6)abstract class can have both abstract and concrete 4)Interface cannot have static methods.
methods 5)Interface cannot have constructor.
7)An abstract class can have method body (non-abstract 6)interface can have only abstract methods
methods). 7)Interface have only abstract methods.
8)An abstract class can have instance variables. 8)An interface cannot have instance variables.
9)In abstract class keyword ‘abstract’ is mandatory to 9)In an interface keyword ‘abstract’ is optional to
declare a method as an abstract declare a method as an abstract

5. What are wrapper classes?


Explanation:

A Wrapper class is a class whose object wraps or contains a primitive data types. When we create an object to a
wrapper class, it contains a field and in this field, we can store a primitive data types. In other words, we can wrap a
primitive value into a wrapper class object.
Need of Wrapper Classes
1. They convert primitive data types into objects. Objects are needed if we wish to modify the arguments
passed into a method (because primitive types are passed by value).
2. The classes in java.util package handle only objects and hence wrapper classes help in this case also.
3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference
types) and not primitive types.
4. An object is needed to support synchronization in multithreading.

6. Why Java is platform independent?

Explanation:

The meaning of platform independent is that, the java source code can run on all operating systems.

A program is written in a language which is a human readable language. It may contain words, phrases etc which
the machine does not understand. For the source code to be understood by the machine, it needs to be in a
language understood by machines, typically a machine-level language. So, here comes the role of a compiler.
The compiler converts the high-level language (human language) into a format understood by the machines.
Therefore, a compiler is a program that translates the source code for another program from a programming
language into executable code.

This executable code may be a sequence of machine instructions that can be executed by the CPU directly, or it
may be an intermediate representation that is interpreted by a virtual machine. This intermediate representation
in Java is the Java Byte Code.

7. What are constructors in Java?

Explanation:

The points given below explain what a Constructor is in detail:


 When a new object is created in a program a constructor gets invoked corresponding to the class.
 The constructor is a method which has the same name as class name.
 If a user doesn’t create a constructor implicitly a default constructor will be created.
 The constructor can be overloaded.
 If the user created a constructor with a parameter then he should create another constructor explicitly without
a parameter.

8. Can you override a private or static method in Java?

Explanation:

No, you cannot override private method; hence the method is called private so that no class extending that
class has any access to the private method. Private methods are not visible to child classes.

Static methods also cannot be overridden, because static methods are a part of the Class itself, and not a part
of any instance (object) of that class. You however can declare same static method with same signature in child
classes, but that would not be considered as runtime polymorphism (override of methods).

So the answer is no for both the cases.

9. What is composition in Java?

Explanation:

The association between two objects is known as Composition, when one class owns other class and other class
cannot meaningfully exist, when it's owner destroyed, for example, Human class is a composition of several
body parts including Hand, Leg and Heart. When human object dies, all it's body part ceased to exist
meaningfully, this is one example of Composition.

Another example of Composition is Car and it's part e.g. engines, wheels etc. Individual parts of the car cannot
function when a car is destroyed.

10. What is multiple in heritance? Is it supported by Java?


Explanation:
If a child class inherits the property from multiple classes is known as multiple inheritance.
Java does not allow to extend multiple classes but to overcome this problem it allows to implement
multiple Interfaces.
Example: The following Sports interface is extended by Hockey and Football interfaces.
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}

11. What is method overloading and method overriding?


METHOD OVERRIDING:
Method overriding happens if the sub class method satisfies the below conditions with the Super class method:
Method name should be same
Argument should be same
Return type also should be same
The key benefit of overriding is that the Sub class can provide some specific information about that sub class
type than the super class.
Example:
public class Manipulation{ //Super class
public void add(){
………………
}
}
Public class Addition extends Manipulation(){
Public void add(){
………..
}
Public static void main(String args[]){
Manipulation addition = new Addition(); //Polimorphism is applied
addition.add(); // It calls the Sub class add() method
}
}
addition.add() method calls the add() method in the Sub class and not the parent class. So it overrides the
Super class method and is known as Method Overriding.
METHOD OVERLOADING:
Method overloading happens for different classes or within the same class.
For method overloading, subclass method should satisfy the below conditions with the Super class method (or)
methods in the same class itself:
Same method name
Different argument type
May have different return types
Example:
public class Manipulation{ //Super class
public void add(String name){ //String parameter
………………
}
}

Public class Addition extends Manipulation(){


Public void add(){//No Parameter
………..
}
Public void add(int a){ //integer parameter

}
Public static void main(String args[]){
Addition addition = new Addition();
addition.add();
}
}
Here the add() method having different parameters in the Addition class is overloaded in the same class as
well as with the super class.
Note: Polymorphism is not applicable for method overloading.

12. What is singleton class and how can we make a class singleton?

Explanation:

In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at
a time.

After first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created.
So whatever modifications we do to any variable inside the class through any instance, it affects the variable of the
single instance created and is visible if we access that variable through any variable of that class type defined.
To design a singleton class:
1. Make constructor as private.
2. Write a static method that has return type object of this singleton class. Here, the concept of Lazy
initialization in used to write this static method.

Implementing Singleton class with getInstance() method

// Java program implementing Singleton class

// with getInstance() method

class Singleton

// static variable single_instance of type Singleton


private static Singleton single_instance = null;

// variable of type String

public String s;

// private constructor restricted to this class itself

private Singleton()

s = "Hello I am a string part of Singleton class";

// static method to create instance of Singleton class

public static Singleton getInstance()

if (single_instance == null)

single_instance = new Singleton();

return single_instance;

// Driver Class

class Main

public static void main(String args[])

// instantiating Singleton class with variable x

Singleton x = Singleton.getInstance();

// instantiating Singleton class with variable y

Singleton y = Singleton.getInstance();

// instantiating Singleton class with variable z

Singleton z = Singleton.getInstance();

// changing variable of instance x

x.s = (x.s).toUpperCase();
System.out.println("String from x is " + x.s);

System.out.println("String from y is " + y.s);

System.out.println("String from z is " + z.s);

System.out.println("\n");

// changing variable of instance z

z.s = (z.s).toLowerCase();

System.out.println("String from x is " + x.s);

System.out.println("String from y is " + y.s);

System.out.println("String from z is " + z.s);

Output:

String from x is HELLO I AM A STRING PART OF SINGLETON CLASS

String from y is HELLO I AM A STRING PART OF SINGLETON CLASS

String from z is HELLO I AM A STRING PART OF SINGLETON CLASS

String from x is hello i am a string part of singleton class

String from y is hello i am a string part of singleton class


Company Name: BluePi
Book Index: 186-(D)

TECHNICAL INTERVIEW QUESTIONS

Core Java based technical telephonic interview

1. What is the difference between JDK, JRE, and JVM?


Ans: To understand the difference between these three, let us consider the following diagram.

1. JDK – Java Development Kit (in short JDK) is Kit which provides the environment to develop and
execute(run) the Java program. JDK is a kit(or package) which includes two things
1. Development Tools(to provide an environment to develop your java programs)
2. JRE (to execute your java program).
Note : JDK is only used by Java Developers.
2. JRE – Java Runtime Environment (to say JRE) is an installation package which provides environment
to only run(not develop) the java program(or application)onto your machine. JRE is only used by them
who only wants to run the Java Programs i.e. end users of your system.
3. JVM – Java Virtual machine(JVM) is a very important part of both JDK and JRE because it is contained
or inbuilt in both. Whatever Java program you run using JRE or JDK goes into JVM and JVM is responsible
for executing the java program line by line hence it is also known as interpreter.

2. Why java is pure object oriented language?


Ans:
Pure Object Oriented Language or Complete Object Oriented Language are Fully Object
Oriented Language which supports or have features which treats everything inside program as
objects. It doesn’t support primitive datatype(like int, char, float, bool, etc.). There are seven
qualities to be satisfied for a programming language to be pure Object Oriented. They are:
1. Encapsulation/Data Hiding
2. Inheritance
3. Polymorphism
4. Abstraction
5. All predefined types are objects
6. All user defined types are objects
7. All operations performed on objects must be only through methods exposed at the objects.
Example: Smalltalk

Java supports property 1, 2, 3, 4 and 6 but fails to support property 5 and 7 given above. Java
language is not a Pure Object Oriented Language as it contain these properties:
 Primitive Data Type ex. int, long, bool, float, char, etc as Objects: Smalltalk is a “pure” object-
oriented programming language unlike Java and C++ as there is no difference between values which are
objects and values which are primitive types. In Smalltalk, primitive values such as integers, booleans and
characters are also objects.
In Java, we have predefined types as non-objects (primitive types).
 int a = 5;

 System.out.print(a);

 The static keyword: When we declares a class as static then it can be used without the use of an object
in Java. If we are using static function or static variable then we can’t call that function or variable by using
dot(.) or class object defying object oriented feature.
 Wrapper Class: Wrapper class provides the mechanism to convert primitive into object and object into
primitive. In Java, you can use Integer, Float etc. instead of int, float etc. We can communicate with objects
without calling their methods. ex. using arithmetic operators.
 String s1 = "ABC" + "A" ;

Even using Wrapper classes does not make Java a pure OOP language, as internally it will use the operations
like Unboxing and Autoboxing. So if you create instead of int Integer and do any mathematical operation on it,
under the hoods Java is going to use primitive type int only.

public class BoxingExample


{
public static void main(String[] args)
{
Integer i = new Integer(10);
Integer j = new Integer(20);
Integer k = new Integer(i.intValue() + j.intValue());
System.out.println("Output: "+ k);
}
}
1. While creating Integer class you are using primitive type “int” i.e. numbers 10, 20.
2. While doing addition Java is using primitive type “int”.

3. What is Byte code?


Ans:
Bytecode is object-oriented programming (OOP) code compiled to run on a virtual machine (VM)
instead of a central processing unit (CPU). The VM transforms program code into readable
machine language for the CPU because platforms utilize different code interpretation techniques.
A VM converts bytecode for platform interoperability, but bytecode is not platform-specific.
Bytecode is in a compiled Java programming language format and has the .class extension
executed by Java Virtual Machine (JVM).
This term is also known as portable code (p-code) and intermediate code.

4. How many types of memory areas are allocated by JVM?


Ans: There are six main types of memory areas that are allocated by JVM. These include:
1. Class loader – a subsystem of JVM that is used to load class files.
2. Class (Method) Area – stores per-class structures such as the runtime constant pool,
field and method data, the code for methods.
3. Heap - is the runtime data area in which objects are allocated.
4. Stack - stores frames and holds local variables and partial results. Participates in method
invocation and return.
5. Program Counter (PC) Register - contains the address of the JVM instruction that is
currently being executed.
6. Native Method Stack - contains all native methods used in the application.
5. What is JIT compiler?
Ans: In the Java programming language and environment, a just-in-time (JIT) compiler is a program that turns
Java bytecode (a program that contains instructions that must be interpreted) into instructions that can be sent
directly to the processor. After you've written a Java program, the source language statements are compiled by
the Java compiler into bytecode rather than into code that contains instructions that match a particular hardware
platform's processor (for example, an Intel Pentium microprocessor or an IBM System/390 processor). The
bytecode is platform-independent code that can be sent to any platform and run on that platform.

6. What is class loader?


Ans: Class loaders are responsible for loading Java classes during runtime dynamically to the JVM (Java Virtual
Machine). Also, they are part of the JRE (Java Runtime Environment). Hence, the JVM doesn’t need to know about
the underlying files or file systems in order to run Java programs thanks to class loaders.
Also, these Java classes aren’t loaded into memory all at once, but when required by an application. This is where
class loaders come into the picture. They are responsible for loading classes into memory.
In this tutorial, we’re going to talk about different types of built-in class loaders, how they work and an introduction
to our own custom implementation.

7. What if I write static public void instead of public static void?


Ans: If you write static public void main instead of public static void main, then it will
make no difference. Program compiles properly and runs. But if you change the sequence
of main, then it will you give a compiler error.

Sometimes interviewer also ask : Explain the meaning of each word in public static void
main? it is also a important one.

Public : is an Access Specifier, which defines who can access this Method. Public means that
this Method will be accessible by any Class(If other Classes are able to access this Class.).

Static : is a keyword which identifies the class related thing. This means the given Method or
variable is not instance related but Class related. It can be accessed without creating the instance
of a Class.

Void : is used to define the Return Type of the Method. It defines what the method can return.
Void means the Method will not return any value.

main: is the name of the Method. This Method name is searched by JVM as a starting point for
an application with a particular signature only.

String[] args : is the parameter to the main Method. you can put any name instead of args.

8. What is the default value of the local variables?


Ans: The local variables are not initialized to any default values. We should
not use local variables with out initialization. Even the java compiler
throws error.

9. What is the purpose of a default constructor?


Ans: Default constructors allow you to create objects with known, default settings and behavior. If you call a
constructor with arguments, you are creating a custom object. But calling the default constructor will create
objects with identical properties every time it is used.

10. What is the difference between static (class) method and instance method?
Ans:
 Instance method can access the instance methods and instance variables directly.
 Instance method can access static variables and static methods directly.
 Static methods can access the static variables and static methods directly.
 Static methods can’t access instance methods and instance variables directly. They must use reference to
object. And static method can’t use this keyword as there is no instance for ‘this’ to refer to.

11. What is the Inheritance?


Ans: Inheritance is a mechanism wherein a new class is derived from an existing class. In Java,
classes may inherit or acquire the properties and methods of other classes.
A class derived from another class is called a subclass, whereas the class from which a subclass
is derived is called a superclass. A subclass can have only one superclass, whereas a
superclass may have one or more subclasses.

12. Which class is the super class for all the classes?
Ans: Object class is the Super class of every class. when you create a java program java.lang.* package
automatically imported to you program so that you do not need to import it explicitely.
For example throwable class is super class of all error and exceptions.

13. Why is multiple in heritance not supported in java?


Ans: Main issues is that if you have two parent classes, they might have different
implementations of the same feature — or possibly two different features with the same
name, as in my instructor's example. Then you have to deal with deciding which one
your subclass is going to use. There are ways of handling this, certainly — C++ does so
— but the designers of Java felt that this would make things too complicated.

With an interface, though, you're describing something the class is capable of doing,
rather than borrowing another class's method of doing something. Multiple interfaces are
much less likely to cause tricky conflicts that need to be resolved than are multiple
parent classes.

14. Why does Java not support pointers?


Ans: Java doesn't have pointers (in the C/C++ sense) because it doesn't need them for general
purpose OOP programming. Furthermore, adding pointers to Java would undermine security and
robustness and make the language more complex.

15. Can you use this () and super () both in a constructor?

Ans: this(...) will call another constructor in the same class whereas super() will call a
super constructor. If there is no super() in a constructor the compiler will add one
implicitly.
Thus if both were allowed you could end up calling the super constructor twice.
Example (don't look for a sense in the parameters):

class A {
public A() {
this( false );
}

public A(boolean someFlag) {


}
}

class B extends A {
public B() {
super();
}

public B( boolean someFlag ) {


super( someFlag );
}

public B ( int someNumber ) {


this(); //
}
}

Now, if you call new B(5) the following constructors are invoked:

this( false);
A() ---------------> A(false)
^
|
| super();
|
| this();
B() <--------------- B(5) <--- you start here

Update:
If you were able to use this() and super() you could end up with something like this:
(Attention: this is meant to show what could go wrong, if you were allowed to do that -
which you fortunately aren't)

this( false);
A() ---------------> A(false)
^ ^
| |
| super(); | super( true ); <--- Problem: should the parameter be true or false?
| |
| this(); |
B() <--------------- B(5) <--- you start here

As you can see, you'd run into a problem where the A(boolean) constructor could be
invoked with different parameters and you'd now have to somehow decide which should
be used. Additionally the other constructors (A() and B()) could contain code that now
might not get called correctly (i.e. out of order etc.) since the call to super( true ) would
circumvent them while this() wouldn't.

16. What is method overloading?


Ans:: Method Overloading is a feature that allows a class to have more than one method having
the same name, if their argument lists are different. It is similar to constructor overloading in
Java, that allows a class to have more than one constructor having different argument lists.
17. Can we overload the main () method?
Ans: Yes, you can overloading, nothing stops from overloading, but JVM will always call the original main
method, it will never call your overloaded main method. we will learn this in little more detail later, now
coming to next question, can you override the main method in Java? the answer is No because main is a
static method and static method cannot be overridden in Java.

18. What is method overriding:


Ans: In any object-oriented programming language, Overriding is a feature that allows a subclass
or child class to provide a specific implementation of a method that is already provided by one of
its super-classes or parent classes. When a method in a subclass has the same name, same
parameters or signature and same return type(or sub-type) as a method in its super-class, then
the method in the subclass is said to override the method in the super-class.

Method overriding is one of the way by which java achieve Run Time Polymorphism.The version
of a method that is executed will be determined by the object that is used to invoke it. If an object
of a parent class is used to invoke the method, then the version in the parent class will be
executed, but if an object of the subclass is used to invoke the method, then the version in the
child class will be executed.In other words, it is the type of the object being referred to (not the type
of the reference variable) that determines which version of an overridden method will be
executed.

19. What is the final variable?


Ans: In Java, when final keyword is used with a variable of primitive data types (int, float, .. etc),
value of the variable cannot be changed.

For example following program gives error because i is final.


public class Test {
public static void main(String args[]) {
final int i = 10;
i = 30; // Error because i is final.
}
}

When final is used with non-primitive variables (Note that non-primitive variables are always
references to objects in Java), the members of the referred object can be changed. final for non-
primitive variables just mean that they cannot be changed to refer to any other object
class Test1 {
int i = 10;
}

public class Test2 {


public static void main(String args[]) {
final Test1 t1 = new Test1();
t1.i = 30; // Works
}
}

20. What is the Collection framework in Java?


Ans: Java Collections Framework is the fundamental aspect of java programming
language. It’s one of the important topic for java interview questions. Here I am listing
some important java collections interview questions and answers for helping you in
interview. This is directly coming from my 12+ year of experience in java programming.

21. What is the difference between Array List and Vector?


Explanation: Array List and Vector both use Array as a data structure internally. However there are few
differences in the way they store and process the data. In this post we will discuss the difference and
similarities between ArrayList and Vector.
ArrayList Vs Vector:

1) Synchronization: ArrayList is non-synchronized which means multiple threads can work on ArrayList at
the same time. For e.g. if one thread is performing an add operation on ArrayList, there can be an another
thread performing remove operation on ArrayList at the same time in a multithreaded environment

while Vector is synchronized. This means if one thread is working on Vector, no other thread can get a hold
of it. Unlike ArrayList, only one thread can perform an operation on vector at a time.
2) Resize: Both ArrayList and Vector can grow and shrink dynamically to maintain the optimal use of
storage, however the way they resized is different. ArrayList grow by half of its size when resized while
Vector doubles the size of itself by default when grows.

3) Performance: ArrayList gives better performance as it is non-synchronized. Vector operations gives poor
performance as they are thread-safe, the thread which works on Vector gets a lock on it which makes other
thread wait till the lock is released.

4) fail-fast: First let me explain what is fail-fast: If the collection (ArrayList, vector etc) gets structurally
modified by any means, except the add or remove methods of iterator, after creation of iterator then the
iterator will throw ConcurrentModificationException. Structural modification refers to the addition or
deletion of elements from the collection.

As per the Vector javadoc the Enumeration returned by Vector is not fail-fast. On the other side the iterator
and listIterator returned by ArrayList are fail-fast.

5) Who belongs to collection framework really? The vector was not the part of collection framework, it has
been included in collections later. It can be considered as Legacy code. There is nothing about Vector which
List collection cannot do. Therefore Vector should be avoided. If there is a need of thread-safe operation
make ArrayList synchronized as discussed in the next section of this post or use CopyOnWriteArrayList
which is a thread-safe variant of ArrayList.

22. What is the difference between Hash Set and Hash Map?
Explanation: Differences:

HashSet HashMap

HashSet class implements the Set


HashMap class implements the Map interface
interface

In HashSet we store HashMap is used for storing key & value pairs. In short it
objects(elements or values) e.g. If maintains the mapping of key & value (The HashMap class is
we have a HashSet of string roughly equivalent to Hashtable, except that it is unsynchronized
elements then it could depict a set and permits nulls.) This is how you could represent HashMap
of HashSet elements: {“Hello”, “Hi”, elements if it has integer key and value of String type: e.g. {1-
“Bye”, “Run”} >”Hello”, 2->”Hi”, 3->”Bye”, 4->”Run”}

HashSet does not allow duplicate


HashMap does not allow duplicate keys however it allows to have
elements that means you can not
duplicate values.
store duplicate values in HashSet.

HashSet permits to have a single null


HashMap permits single null key and any number of null values.
value.
23. What is the Dictionary class?
Explanation: The java.util.Dictionary class is the abstract parent of any class, such as Hashtable, which
maps keys to values.Following are the important points about Dictionary − In this class every key and every
value is an object. In his class object every key is associated with at most one value.

24. When to use Array List and Linked List?


Explanation: It's elements can be accessed directly by using the get and set methods, since ArrayList is
essentially an array. LinkedList is implemented as a double linked list. Its performance on add and remove is
better than Arraylist, but worse on get and set methods. Vector is similar with ArrayList, but it is
synchronized.

25. What is JDBC?


Explanation: Java Database Connectivity (JDBC) is an application program interface (API) specification for
connecting programs written in Java to the data in popular databases. The application program interface lets
you encode access request statements in Structured Query Language (SQL) that are then passed to the
program that manages the database. It returns the results through a similar interface. JDBC is very similar to
the SQL Access Group's Open Database Connectivity (ODBC) and, with a small "bridge" program, you can
use the JDBC interface to access databases through the ODBC interface. For example, you could write a
program designed to access many popular database products on a number of operating system platforms.
When accessing a database on a PC running Microsoft's Windows 2000 and, for example, a Microsoft
Access database, your program with JDBC statements would be able to access the Microsoft Access
database.

26. How can we store the file in the Oracle database?


Explanation: import java.io.*;
import java.sql.*;

public class StoreFile {


public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

PreparedStatement ps=con.prepareStatement(
"insert into filetable values(?,?)");

File f=new File("d:\\myfile.txt");


FileReader fr=new FileReader(f);

ps.setInt(1,101);
ps.setCharacterStream(2,fr,(int)f.length());
int i=ps.executeUpdate();
System.out.println(i+" records affected");

con.close();

}catch (Exception e) {e.printStackTrace();}


}
}
27. What is Exception Handling?
Explanation: Exception handling is the process of responding to the occurrence, during computation, of
exceptions – anomalous or exceptional conditions requiring special processing – often changing the normal
flow of program execution. It is provided by specialized programming language constructs, computer
hardware mechanisms like interrupts or operating system IPC facilities like signals.

28. What is the difference between throw and throws?


Explanation: The main difference between throw and throws is like "One declares it and the other one
actually does it." throw keyword is used to throw exception explicitly from any method or static block while
throws keyword is used in method declaration, denoted which exception can possible be thrown by this
method.

29. What is Garbage Collection?


Explanation: In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is
a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is performed
automatically. So, java provides better memory management.
Advantage of Garbage Collection

It makes java memory efficient because garbage collector removes the unreferenced objects from heap
memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

30. What is the difference between final, finally and finalize?


Explanation: Final class can't be inherited, final method can't be overridden and final variable value can't be
changed. Finally is used to place important code, it will be executed whether exception is handled or not.
Finalize is used to perform clean up processing just before object is garbage collected.

31. What are wrapper classes?


Explanation: Wrapper class in java provides the mechanism to convert primitive into object and object into
primitive.

Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive
automatically. The automatic conversion of primitive into object is known as autoboxing and vice-versa
unboxing.

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte
short Short

int Integer

long Long

float Float

double Double

32. What is an applet?


Explanation: n applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.

There are some important differences between an applet and a standalone Java application, including the
following −

An applet is a Java class that extends the java.applet.Applet class.

A main() method is not invoked on an applet, and an applet class will not define main().

Applets are designed to be embedded within an HTML page.

When a user views an HTML page that contains an applet, the code for the applet is downloaded to the user's
machine.

A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate
runtime environment.

The JVM on the user's machine creates an instance of the applet class and invokes various methods during
the applet's lifetime.

Applets have strict security rules that are enforced by the Web browser. The security of an applet is often
referred to as sandbox security, comparing the applet to a child playing in a sandbox with various rules that
must be followed.

Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

33. What is Locale?


Explanation: Locale may refer to:

Locale (computer software), a set of parameters that defines the user's language, region and any special
variant preferences that the user wants to see in their user interface. Usually a locale identifier consists of at
least a language identifier and a region identifier.
Locale (computer hardware), an abstraction of the concept of a localized set of hardware resources which are
close enough to enjoy uniform memory access.

34. What is the thread?


Explanation: Java is a multi-threaded application that allows multiple thread execution at any particular time.
In a single-threaded application, only one thread is executed at a time because the application or program can
handle only one task at a time. For example, a single-threaded application may allow for the typing of words.

35. Differentiate between process and thread?


Explanation: Threads are used for small tasks, whereas processes are used for more 'heavyweight' tasks –
basically the execution of applications. Another difference between a thread and a process is that threads
within the same process share the same address space, whereas different processes do not.

Both processes and threads are independent sequences of execution. The typical difference is that threads (of
the same process) run in a shared memory space, while processes run in separate memory spaces.
DRIVE NAME: NEWGEN
Book Index: 187-(D)

TECHNICAL INTERVIEW
1. What is Servlet?
Sol:

A servlet is a JavaTM technology-based Web component, managed by a container that generates


dynamic content. Like other Java technology-based components, servlets are platform-independent
Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and
run by a Java technology-enabled Web server. Containers, sometimes called servlet engines, are Web
server extensions that provide servlet functionality. Servlets interact with Web clients via a
request/response paradigm implemented by the servlet container.

2. Difference between JSP and Servlet.


Sol: Servlet is html in java whereas JSP is java in html. Servlets run faster compared to JSP. ... JSP is a
webpage scripting language that can generate dynamic content while Servlets are Java programs that are
already compiled which also creates dynamic web content. In MVC, jsp acts as a view and servletacts as a
controller.

3. How we connect database in Java.


Sol:
Example to Connect Java Application with mysql database
 import java.sql.*;
 classMysqlCon{
 public static void main(String args[]){
 try{
 Class.forName("com.mysql.jdbc.Driver");
 Connection con=DriverManager.getConnection(
 //here sonoo is database name, root is username and password.
 Statement stmt=con.createStatement();

4. What are different types of joins in SQL.


Sol:
Different Types of SQL JOINs

Here are the different types of the JOINs in SQL:

 (INNER) JOIN: Returns records that have matching values in both tables
 LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the
right table
 RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the
left table
 FULL (OUTER) JOIN: Return all records when there is a match in either left or right table

5. Triggers in SQL.
Sol: A trigger is a special type of stored procedure that automatically executes when an event occurs in the
database server. DML triggers execute when a user tries to modify data through a data manipulation
language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view.

6. Overriding in Java.
Sol: Overriding in Java. In any object-oriented programming language, Overriding is a feature that allows a
subclass or child class to provide a specific implementation of a method that is already provided by one of
its super-classes or parent classes.

7. Final keyword used in Java.


Sol:
final keyword is used in different contexts. First of all, final is a non-access modifier applicable only to a
variable, a method or a class.Following are different contexts where final is used.

8. Array list in Java.


Sol: Java ArrayList is one of the most widely used Collection class. java.util.ArrayList class
implements java.util.List interface. Java ArrayList also implements RandomAccess, Cloneableand
Serializable interfaces. Java ArrayList class extends AbstractList class that is the skeleton implementation
of List interface.

9. Exception handling in Cpp and Java.


Sol: 1) In C++, all types (including primitive and pointer) can be thrown as exception. But in Java only
throwable objects (Throwable objects are instances of any subclass of the Throwable class) can be thrown
as exception. ... 5) In Java, a new keyword throws is used to list exceptions that can be thrown by a
function.

10. Queries related to updation in SQL.


Sol: The SQL UPDATE Query is used to modify the existing records in a table. You can use the WHERE
clause with the UPDATE query to update the selected rows, otherwise all the rows would be affected.

Syntax
The basic syntax of the UPDATE query with a WHERE clause is as follows −

UPDATE table_name SET column1 = value1, column2 = value2....,columnN = valueN WHERE


[condition];
You can combine N number of conditions using the AND or the OR operators.

Example
The following query will update the ADDRESS for a customer whose ID number is 6 in the table.

SQL> UPDATE CUSTOMERS SET ADDRESS ='Pune' WHERE ID =6;

If you want to modify all the ADDRESS and the SALARY column values in the CUSTOMERS table, you
do not need to use the WHERE clause as the UPDATE query would be enough as shown in the following
code block.

SQL> UPDATE CUSTOMERS SET ADDRESS ='Pune', SALARY =1000.00;

11. Abstract class


Sol:
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract
classes cannot be instantiated, but they can be sub classed. An abstract class may have static fields and
static methods.

12. Difference between Interface and abstract class?


Sol:
1.Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A
Java abstract class can have instance methods that implements a default behavior. 2.Variables declared in
a Java interface is by default final. An abstract class may contain non-final variables.

13. Round robin algorithm in operating system?


Sol: Round Robin Scheduling
 Round Robin is the preemptive process scheduling algorithm.
 Each process is provided a fix time to execute, it is called a quantum.
 Once a process is executed for a given time period, it is preempted and other process executes for a
given time period.
 Context switching is used to save states of preempted processes.
Drive Name: CAPGEMINI
Book Index: 189-(D)

Technical Interview questions

1. Tell me something about yourself along with your technical skills and projects undertaken in
detail.
Sol:
I’m really excited to join this practicing page to improve and practice my English. I’m a second year
Software engineering student. I have a very good computer skills using Microsoft office and
programming using C++,Java and C# . I don’t have a job experience yet, but I’m a fast learner, team
sprite and hardworking that looking for this position to utilize my proven and developing programming
skills.

2. What do you mean by interface?


Sol: A boundary across which two independent systems meet and act on or communicate with each other.
In computer technology, there are several types of interfaces. user interface - the keyboard, mouse, menus
of a computer system. The user interface allows the user to communicate with the operating system. Also
see GUI.

3. What is the difference between = = and equals ()?


Sol:
In general both equals() and “==” operator in Java are used to compare objects to check equality but
here are some of the differences between the two: Main difference between .equals() method and ==
operator is that one is method and other is operator. ... Both s1 and s2 refers to different objects.

4. What is an LCR circuit? Draw its arrangement sequence?


Sol:
Electronics

5. Which circuit is used in fans?


Sol:
Electronics

6. What is critical angle?


Sol:
Electronics

7. What if I don’t hire you?


Sol: soft skills

8. What if I hire you?


Sol: soft skills
9. Do you have problem in relocating to Chennai?
Sol: soft skills
DRIVE NAME: GRAY B
Book Index: 190-(D)

TECHNICAL INTERVIEW

1. What are patents and why are they important?


Sol:
Why Are Patents Important? A patent is important because it can help safeguard your invention. It can
protect any product, design or process that meets certain specifications according to its originality,
practicality, suitability, and utility. In most cases, a patent can protect an invention for up to 20 years

2. What is patent infringement?


Sol:
Patent infringement is the commission of a prohibited act with respect to a patented invention without
permission from the patent holder. Permission may typically be granted in the form of a license. The
definition of patent infringement may vary by jurisdiction, but it typically includes using or selling the
patented invention. In many countries, a use is required to be commercial (or to have a commercial
purpose) to constitute patent infringement

3. What are Neural Networks?


Sol: A neural network is a series of algorithms that endeavors to recognize underlying relationships in a set
of data through a process that mimics the way the human brain operates. Neural networks can adapt to
changing input so the network generates the best possible result without needing to redesign the output
criteria. The conception of neural networks is swiftly gaining popularity in the area of trading
system development.

4. What is the difference between strong AI and weak AI?


Sol:
The distinction between Weak and Strong AI refers to claims about the capabilities of computers. Popular
uses of the terms 'Weak AI' and 'Strong AI' are less carefully defined than their academic uses. ... Weak
AI is the hypothesis that a powerful enough computer could simulate any aspect of the human mind.

5. What is machine learning?


Sol: Machine learning is an application of artificial intelligence (AI) that provides systems the ability to
automatically learn and improve from experience without being explicitly programmed. Machine learning
focuses on the development of computer programs that can access data and use it learn for themselves.

The process of learning begins with observations or data, such as examples, direct experience, or
instruction, in order to look for patterns in data and make better decisions in the future based on the
examples that we provide. The primary aim is to allow the computers learn automatically without human
intervention or assistance and adjust actions accordingly.

Some machine learning methods


Machine learning algorithms are often categorized as supervised or unsupervised.

 Supervised machine learning algorithms can apply what has been learned in the past to new data
using labeled examples to predict future events. Starting from the analysis of a known training
dataset, the learning algorithm produces an inferred function to make predictions about the output
values. The system is able to provide targets for any new input after sufficient training. The learning
algorithm can also compare its output with the correct, intended output and find errors in order to
modify the model accordingly.
 In contrast, unsupervised machine learning algorithms are used when the information used to train
is neither classified nor labeled. Unsupervised learning studies how systems can infer a function to
describe a hidden structure from unlabeled data. The system doesn’t figure out the right output, but
it explores the data and can draw inferences from datasets to describe hidden structures from
unlabeled data.
 Semi-supervised machine learning algorithms fall somewhere in between supervised and
unsupervised learning, since they use both labeled and unlabeled data for training – typically a
small amount of labeled data and a large amount of unlabeled data. The systems that use this
method are able to considerably improve learning accuracy. Usually, semi-supervised learning is
chosen when the acquired labeled data requires skilled and relevant resources in order to train it /
learn from it. Otherwise, acquiring unlabeled data generally doesn’t require additional resources.
 Reinforcement machine learning algorithms is a learning method that interacts with its environment
by producing actions and discovers errors or rewards. Trial and error search and delayed reward are
the most relevant characteristics of reinforcement learning. This method allows machines and
software agents to automatically determine the ideal behavior within a specific context in order to
maximize its performance. Simple reward feedback is required for the agent to learn which action is
best; this is known as the reinforcement signal.

Machine learning enables analysis of massive quantities of data. While it generally delivers faster, more
accurate results in order to identify profitable opportunities or dangerous risks, it may also require
additional time and resources to train it properly. Combining machine learning with AI and cognitive
technologies can make it even more effective in processing large volumes of information.
Drive Name: NIIT

Book Index: 203-(D)

TECHNICLA INTERVIEW QUESTIONS

1. What is the difference between unique key and primary key?


Ans: Primary Key is used to identify a row (record) in a table, whereas Unique-key is to prevent duplicate
values in a column (with the exception of a null entry). 2. Indexing: By default SQL-engine creates Clustered
Index on primary-key if not exists and Non-Clustered Index on Unique-key.
2. Write a code to reverse text.
Ans: #include <stdio.h>

/* function prototype for utility function to


reverse a string from begin to end */
void reverse(char* begin, char* end);

/*Function to reverse words*/


void reverseWords(char* s)
{
char* word_begin = s;
char* temp = s; /* temp is for word boundry */

/*STEP 1 of the above algorithm */


while (*temp) {
temp++;
if (*temp == '\0') {
reverse(word_begin, temp - 1);
}
else if (*temp == '') {
reverse(word_begin, temp - 1);
word_begin = temp + 1;
}
} /* End of while */

/*STEP 2 of the above algorithm */


reverse(s, temp - 1);
}

/* UTILITY FUNCTIONS */
/*Function to reverse any sequence starting with pointer
begin and ending with pointer end */
void reverse(char* begin, char* end)
{
char temp;
while (begin < end) {
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}

/* Driver function to test above functions */


int main()
{
char s[] = "i like this program very much";
char* temp = s;
reverseWords(s);
printf("%s", s);
getchar();
return 0;
}

3. What was your role in projects-ethics and values?


Ans: Depends on student’s response

4. What all technical skills you have?


Ans: Depends on student’s response

5. Which language you are comfortable in?


Ans: Depends on student’s response

6. What all technical skills do you like to improve?


Ans: Depends on student’s response

7. What are your academic achievements?


Ans: Depends on student’s response

8. How to build strings from the second strings?


Ans: #include <bits/stdc++.h>

using namespace std;

vector<string> split_string(string);

/*
* Complete the buildString function below.
*/
int buildString(int a, int b, string s) {
/*
* Write your code here.
*/

int main()
{
ofstream fout(getenv("OUTPUT_PATH"));

int t;
cin >> t;
cin.ignore(numeric_limits<streamsize>::max(), '\n');

for (int t_itr = 0; t_itr < t; t_itr++) {


string nab_temp;
getline(cin, nab_temp);

vector<string> nab = split_string(nab_temp);

int n = stoi(nab[0]);

int a = stoi(nab[1]);

int b = stoi(nab[2]);

string s;
getline(cin, s);

int result = buildString(a, b, s);


}

fout.close();

return 0;
}

vector<string> split_string(string input_string) {


string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y)
{
return x == y and x == '';
});

input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == '') {
input_string.pop_back();
}

vector<string> splits;
char delimiter = '';

size_t i = 0;
size_t pos = input_string.find(delimiter);

while (pos != string::npos) {


splits.push_back(input_string.substr(i, pos - i));

i = pos + 1;
pos = input_string.find(delimiter, i);
}

splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));

return splits;
}

9. Explain some querries based on Database Tables.


Ans: SELECT column1, column2, columnN FROM table_name;
CUSTOMERS table having the following records −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
SELECT ID, NAME, SALARY FROM CUSTOMERS;
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+

10. How you can add validation while coding for password?
Ans: <div class="container">
<form action="/action_page.php">
<label for="usrname">Username</label>
<input type="text" id="usrname" name="usrname" required>

<label for="psw">Password</label>
< input type="password" id="psw" name="psw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must
contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters"
required>

<input type="submit" value="Submit">


</form>
</div>

<div id="message">
<h3>Password must contain the following:</h3>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
</div>
11. Have you implemented database in your project?
Ans : Depends what project is.

12. What all projects you have made?


Ans : Depends on student’s response

13. What were the SQL tables used in your project?


Ans: Depends on student’s response

14. Print every third element of the string.


Ans: def iterctr(items, n):
ctr = 0
for item in items:
ctr += 1
if ctr % 3 == 0:
print ctr
yield item

15. Two strings are given, how many times first string is being repeated in second string.
Ans: #include<iostream>
#include<cstring>
using namespace std;

// Returns true if str1[] is a subsequence of str2[]. m is


// length of str1 and n is length of str2
bool isSubSequence(char str1[], char str2[], int m, int n)
{
// Base Cases
if (m == 0) return true;
if (n == 0) return false;

// If last characters of two strings are matching


if (str1[m-1] == str2[n-1])
return isSubSequence(str1, str2, m-1, n-1);

// If last characters are not matching


return isSubSequence(str1, str2, m, n-1);
}

// Driver program to test methods of graph class


int main()
{
char str1[] = "gksrek";
char str2[] = "geeksforgeeks";
int m = strlen(str1);
int n = strlen(str2);
isSubSequence(str1, str2, m, n)? cout <<"Yes ":
cout <<"No";
return 0;
}

16. Any two programs on to the array.


Ans: 1,
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}
2,
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;

// If the element is present at the middle


// itself
if (arr[mid] == x)
return mid;

// If element is smaller than mid, then


// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid-1, x);

// Else the element can only be present


// in right subarray
return binarySearch(arr, mid+1, r, x);
}

// We reach here when element is not


// present in array
return -1;
}

17. How to reverse a string?


Ans: #include <stdio.h>

int main()
{
char s[1000], r[1000];
int begin, end, count = 0;

printf("Input a string\n");
gets(s);

// Calculating string length

while (s[count] != '\0')


count++;

end = count - 1;
for (begin = 0; begin < count; begin++) {
r[begin] = s[end];
end--;
}

r[begin] = '\0';

printf("%s\n", r);

return 0;
}

18. Concepts of joins in the database?


Ans: An SQL join clause - corresponding to a join operation in relational algebra - combines columns from one
or more tables in a relational database. It creates a set that can be saved as a table or used as it is. A JOIN is a
means for combining columns from one (self-join) or more tables by using values common to each.

19. What is the value of DBMS in market?


Ans: The statistic shows the size of the database market worldwide, from 2012 to 2017. In 2017, the global
database market is expected to reach 50 billion U.S. dollars in size. The majority of the market comprises
proprietary databases, with traditional, relational databases making up the lion's share. However, the market
share of open source databases as well as newer approaches to databases, such as Hadoop, continue to grow.

20. How many maximum rows and columns can be there when you create a table?
Ans: It's true that if you use an INT or BIGINT as your primary key, you can only have as many rows as the
number of unique values in the data type of your primary key, but you don't have to make your primary key an
integer, you could make it a CHAR(100). You could also declare the primary key over more than one column.
There are other constraints on table size besides number of rows. For instance you could use an operating system
that has a file size limitation. Or you could have a 300GB hard drive that can store only 300 million rows if each
row is 1KB in size.

21. What is the latest SQL version?


Ans: 14.0version 2017 SQL Server 2017

22. How many marks will you give yourself on the basis of your knowledge of DBMS?
Ans: Depends on student’s response
23. What is the latest of DBMS?
Ans: Oracle database is the most widely used object-relational database management software. The latest version of
this tool is 12c where c means cloud computing. It supports multiple Windows, UNIX, and Linux versions

24. Explain the concept of trigger?


Ans: In a DBMS, a trigger is a SQL procedure that initiates an action (i.e., fires an action) when an event (INSERT,
DELETE or UPDATE) occurs. Since triggers are event-driven specialized procedures, they are stored in and
managed by the DBMS. ... Each trigger is attached to a single, specified table in the database.
25. Create a progress for login form with the help of database.
Ans: $(document).ready(function(){
$("#login").click(function(){
var email = $("#email").val();
var password = $("#password").val();
// Checking for blank fields.
if( email =='' || password ==''){
$('input[type="text"],input[type="password"]').css("border","2px solid red");
$('input[type="text"],input[type="password"]').css("box-shadow","0 0 3px red");
alert("Please fill all fields...!!!!!!");
}else {
$.post("login.php",{ email1: email, password1:password},
function(data) {
if(data=='Invalid Email.......') {
$('input[type="text"]').css({"border":"2px solid red","box-shadow":"0 0 3px red"});
$('input[type="password"]').css({"border":"2px solid #00F5FF","box-shadow":"0 0 5px #00F5FF"});
alert(data);
}else if(data=='Email or Password is wrong...!!!!'){
$('input[type="text"],input[type="password"]').css({"border":"2px solid red","box-shadow":"0 0 3px red"});
alert(data);
} else if(data=='Successfully Logged in...'){
$("form")[0].reset();
$('input[type="text"],input[type="password"]').css({"border":"2px solid #00F5FF","box-shadow":"0 0 5px
#00F5FF"});
alert(data);
} else{
alert(data);
}
});
}
});
});
26. Create a program for Swapping of two numbers without using third variables.
Ans: int main()
{
int x, y, t;

printf("Enter two integers\n");


scanf("%d%d", &x, &y);

printf("Before Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y);

t = x;
x = y;
y = t;

printf("After Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y);

return 0;
}
27. Create a program swapping of two characters without using third variable.
Ans: int main()
{
int a, b;

printf("Input two integers (a & b) to swap\n");


scanf("%d%d", &a, &b);

a = a + b;
b = a - b;
a = a - b;

printf("a = %d\nb = %d\n",a,b);


return 0;
}
28. Join two tables and show the results.
Ans: "Orders" table:
OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20

Customers" table:
CustomerID CustomerName ContactName Country
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico
3 Antonio Moreno Taquería Antonio Moreno Mexico

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate


FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

Result

OrderID CustomerName OrderDate


10308 Ana Trujillo Emparedados y helados 9/18/1996
10365 Antonio Moreno Taquería 11/27/1996
10383 Around the Horn 12/16/1996
10355 Around the Horn 11/15/1996
10278 Berglunds snabbköp 8/12/1996

29. How did you give connectivity to your project?

Ans: Java Connectivity

import java.sql.*;

class MysqlCon{

public static void main(String args[]){

try{

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection(

"jdbc:mysql://localhost:3306/sonoo","root","root");

//here sonoo is database name, root is username and password

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next())

System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));

con.close();

}catch(Exception e){ System.out.println(e);}

}
Drive Name: AMAZON

Book Index: 209-(D)

TECHNICAL INTERVIEW

1. Given an array of positive numbers, find the maximum sum of a subsequence with the constraint that no
two numbers in the sequence should be adjacent in the array.

Solution:

Algorithm: Loop for all elements in arr[] and maintain two sums incl and excl where incl = Max sum including
the previous element and excl = Max sum excluding the previous element.
Max sum excluding the current element will be max(incl, excl) and max sum including the current element will be
excl + current element (Note that only excl is considered because elements cannot be adjacent).
At the end of the loop return max of incl and excl.
Example:
arr[] = {5, 5, 10, 40, 50, 35}

incl = 5
excl = 0

For i = 1 (current element is 5)


incl = (excl + arr[i]) = 5
excl = max(5, 0) = 5

For i = 2 (current element is 10)


incl = (excl + arr[i]) = 15
excl = max(5, 5) = 5

For i = 3 (current element is 40)


incl = (excl + arr[i]) = 45
excl = max(5, 15) = 15

For i = 4 (current element is 50)


incl = (excl + arr[i]) = 65
excl = max(45, 15) = 45

For i = 5 (current element is 35)


incl = (excl + arr[i]) = 80
excl = max(65, 45) = 65

And 35 is the last element. So, answer is max(incl, excl) = 8

#include<stdio.h>

/*Function to return max sum such that no two elements


are adjacent */
int FindMaxSum(int arr[], int n)
{
int incl = arr[0];
int excl = 0;
int excl_new;
int i;

for (i = 1; i < n; i++)


{
/* current max excluding i */
excl_new = (incl > excl)? incl: excl;

/* current max including i */


incl = excl + arr[i];
excl = excl_new;
}

/* return max of incl and excl */


return ((incl > excl)? incl : excl);
}

/* Driver program to test above function */


int main()
{
int arr[] = {5, 5, 10, 100, 10, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d n", FindMaxSum(arr, n));
return 0;
}

2. Design a data structure to represent the movement of a knight on a chess board.


Solution:

Given any source point and destination point on a chess board, we need to find whether Knight can move to
the destination or not.

The above figure details the movements for a knight ( 8 possibilities ). Note that a knight cannot go out of the
board.
If yes, then what would be the minimum number of steps for the knight to move to the said point.
If knight can not move from the source point to the destination point, then return -1

Input:

N, M, x1, y1, x2, y2


where N and M are size of chess board
x1, y1 coordinates of source point
x2, y2 coordinates of destination point
Output:

return Minimum moves or -1


Example

Input : 8 8 1 1 8 8
Output : 6

Assume this problem as searching in graph where each block of chess board is vertex.
Define edges in such a graph and the ways when can you travel from vertex i to vertex
j. Once we have the graph, then it reduces to finding the shortest path in an
unweighted graph.

A knight can move to 8 positions from (x,y).

(x, y) ->
(x + 2, y + 1)
(x + 2, y - 1)
(x - 2, y + 1)
(x - 2, y - 1)
(x + 1, y + 2)
(x + 1, y - 2)
(x - 1, y + 2)
(x - 1, y - 2)

Corresponding to the knight's move, we can define edges.


(x,y) will have an edge to the 8 neighbors defined above.

To find the shortest path, we just run a plain BFS.

#include<bits/stdc++.h>
#define pb push_back
#define ff first
#define ss second
#define mpa make_pair
using namespace std;
typedef long long LL;

int dx[8] = {2, 2, -2, -2, 1, 1, -1, -1};


int dy[8] = {-1, 1, 1, -1, 2, -2, 2, -2};

bool valid(int x, int y, int N, int M) {


if(x <= 0 || y <= 0 || x > N || y > M)
return false;
return true;
}

int bfs(pair<int, int> p1, pair<int, int> p2, pair<int, int> p3) {

int N = p3.ff;
int M = p3.ss;
queue<pair<pair<int, int>, int> > Que;
map<pair<int, int>, bool> Vis;

Que.push(mpa(p1, 0));

while(!Que.empty()) {

pair<pair<int, int>, int> temp = Que.front();


Que.pop();

if(temp.ff.ff == p2.ff && temp.ff.ss == p2.ss)


return temp.ss;
int x = temp.ff.ff;
int y = temp.ff.ss;
int dis = temp.ss + 1;

if(Vis.count(mpa(x, y)))
continue;
Vis[mpa(x, y)] = true;

for(int i = 0; i < 8; ++i) {

int x1 = x + dx[i];
int y1 = y + dy[i];
if(valid(x1, y1, N, M))
Que.push(mpa(mpa(x1, y1), dis));
}

return -1;
}

int solve(int N, int M, int x1, int y1, int x2, int y2) {

pair<int, int> p1;


p1.ff = x1;
p1.ss = y1;

pair<int, int> p2;


p2.ff = x2;
p2.ss = y2;

pair<int, int> p3;


p3.ff = N;
p3.ss = M;

int ans = bfs(p1, p2, p3);


return ans;
}

int main() {

cout << solve(8, 8, 1, 1, 8, 8) << endl;


return 0;
}

3. Write an algorithm to traverse a knight covering all the squares on a chessboard starting at a particular
point.
Solution:

Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that “works”. Problems
which are typically solved using backtracking technique have following property in common. These problems can
only be solved by trying every possible configuration and each configuration is tried only once. A Naive solution for
these problems is to try all configurations and output a configuration that follows given problem constraints.
Backtracking works in incremental way and is an optimization over the Naive solution where all possible
configurations are generated and tried.

For example, consider the following Knight’s Tour problem.

The knight is placed on the first block of an empty board and, moving according to the rules of chess, must visit each
square exactly once.

Path followed by Knight to cover all the cells

Following is chessboard with 8 x 8 cells. Numbers in cells indicate move number of Knight.

knight-tour-problem

Let us first discuss the Naive algorithm for this problem and then the Backtracking algorithm.

Naive Algorithm for Knight’s tour

The Naive Algorithm is to generate all tours one by one and check if the generated tour satisfies the constraints.

while there are untried tours


{
generate the next tour
if this tour covers all squares
{
print this path;
}
}

Backtracking works in an incremental way to attack problems. Typically, we start from an empty solution vector and
one by one add items (Meaning of item varies from problem to problem. In context of Knight’s tour problem, an
item is a Knight’s move). When we add an item, we check if adding the current item violates the problem constraint,
if it does then we remove the item and try other alternatives. If none of the alternatives work out then we go to
previous stage and remove the item added in the previous stage. If we reach the initial stage back then we say that no
solution exists. If adding an item doesn’t violate constraints then we recursively add items one by one. If the solution
vector becomes complete then we print the solution.
Backtracking Algorithm for Knight’s tour

Following is the Backtracking algorithm for Knight’s tour problem.

If all squares are visited

print the solution

Else

a) Add one of the next moves to solution vector and recursively check if this move leads to a solution. (A Knight
can make maximum eight moves. We choose one of the 8 moves in this step).

b) If the move chosen in the above step doesn't lead to a solution then remove this move from the solution vector
and try other alternative moves.

c) If none of the alternatives work then return false (Returning false will remove the previously added item in
recursion and if false is returned by the initial call of recursion then "no solution exists" )

4. In a given maze, find out how many paths are there to get the cheese (program).
Solution:

This problem is an extension of below problem.

In this post a different solution is discussed that can be used to solve the above Rat in a Maze
problem also.
The idea is to modify the given grid[][] so that grid[i][j] contains count of paths to reach (i, j)
from (0, 0) if (i, j) is not a blockage, else grid[i][j] remains -1.
We can recursively compute grid[i][j] using below
formula and finally return grid[R-1][C-1]

// If current cell is a blockage


if (maze[i][j] == -1)
maze[i][j] = -1; // Do not change

// If we can reach maze[i][j] from maze[i-1][j]


// then increment count.
else if (maze[i-1][j] > 0)
maze[i][j] = (maze[i][j] + maze[i-1][j]);

// If we can reach maze[i][j] from maze[i][j-1]


// then increment count.
else if (maze[i][j-1] > 0)
maze[i][j] = (maze[i][j] + maze[i][j-1]);
Below is the implementation of above idea.
// C++ program to count number of paths in a maze
// with obstacles.
#include<bits/stdc++.h>
using namespace std;
#define R 4
#define C 4

// Returns count of possible paths in a maze[R][C]


// from (0,0) to (R-1,C-1)
int countPaths(int maze[][C])
{
// If the initial cell is blocked, there is no
// way of moving anywhere
if (maze[0][0]==-1)
return 0;

// Initializing the leftmost column


for (int i=0; i<R; i++)
{
if (maze[i][0] == 0)
maze[i][0] = 1;

// If we encounter a blocked cell in leftmost


// row, there is no way of visiting any cell
// directly below it.
else
break;
}

// Similarly initialize the topmost row


for (int i=1; i<C; i++)
{
if (maze[0][i] == 0)
maze[0][i] = 1;

// If we encounter a blocked cell in bottommost


// row, there is no way of visiting any cell
// directly below it.
else
break;
}

// The only difference is that if a cell is -1,


// simply ignore it else recursively compute
// count value maze[i][j]
for (int i=1; i<R; i++)
{
for (int j=1; j<C; j++)
{
// If blockage is found, ignore this cell
if (maze[i][j] == -1)
continue;
// If we can reach maze[i][j] from maze[i-1][j]
// then increment count.
if (maze[i-1][j] > 0)
maze[i][j] = (maze[i][j] + maze[i-1][j]);

// If we can reach maze[i][j] from maze[i][j-1]


// then increment count.
if (maze[i][j-1] > 0)
maze[i][j] = (maze[i][j] + maze[i][j-1]);
}
}

// If the final cell is blocked, output 0, otherwise


// the answer
return (maze[R-1][C-1] > 0)? maze[R-1][C-1] : 0;
}

// Driver code
int main()
{
int maze[R][C] = {{0, 0, 0, 0},
{0, -1, 0, 0},
{-1, 0, 0, 0},
{0, 0, 0, 0}};
cout << countPaths(maze);
return 0;
}
Output:
4
Time Complexity : O(R x C)

5. Create a class of watch having two member functions and two data members.

/*C++ program to read time in HH:MM:SS format and convert into total
seconds.*/

#include <iostream>
#include <iomanip>

using namespace std;

class Watch
{
private:
int seconds;
int hh,mm,ss;
public:
void getTime(void);
void convertIntoSeconds(void);
void displayTime(void);
};

void Time::getTime(void)
{
cout << "Enter time:" << endl;
cout << "Hours? "; cin >> hh;
cout << "Minutes? "; cin >> mm;
cout << "Seconds? "; cin >> ss;
}

void Time::convertIntoSeconds(void)
{
seconds = hh*3600 + mm*60 + ss;
}

void Time::displayTime(void)
{
cout << "The time is = " << setw(2) << setfill('0') << hh << ":"
<< setw(2) << setfill('0') << mm << ":"
<< setw(2) << setfill('0') << ss << endl;
cout << "Time in total seconds: " << seconds;
}

int main()
{
Watch W; //creating objects

W.getTime();
W.convertIntoSeconds();
W.displayTime();

return 0;
}

Output

Enter time:
Hours? 1
Minutes? 1
Seconds? 6
The time is = 01:01:06
Time in total seconds: 3666

6. There is a tree. Check whether it is a mirror tree or not


Solution:

Given two Binary Trees, write a function that returns true if two trees are mirror of each other,
else false. For example, the function should return true for following input trees.
For two trees ‘a’ and ‘b’ to be mirror images, the following three conditions must be true:
1. Their root node’s key must be same
2. Left subtree of root of ‘a’ and right subtree root of ‘b’ are mirror.
3. Right subtree of ‘a’ and left subtree of ‘b’ are mirror.
Below is implementation of above idea.
// C++ program to check if two trees are mirror
// of each other
#include<bits/stdc++.h>
using namespace std;

/* A binary tree node has data, pointer to


left child and a pointer to right child */
struct Node
{
int data;
Node* left, *right;
};

/* Given two trees, return true if they are


mirror of each other */
int areMirror(Node* a, Node* b)
{
/* Base case : Both empty */
if (a==NULL && b==NULL)
return true;

// If only one is empty


if (a==NULL || b == NULL)
return false;

/* Both non-empty, compare them recursively


Note that in recursive calls, we pass left
of one tree and right of other tree */
return a->data == b->data &&
areMirror(a->left, b->right) &&
areMirror(a->right, b->left);
}

/* Helper function that allocates a new node */


Node* newNode(int data)
{
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return(node);
}

/* Driver program to test areMirror() */


int main()
{
Node *a = newNode(1);
Node *b = newNode(1);
a->left = newNode(2);
a->right = newNode(3);
a->left->left = newNode(4);
a->left->right = newNode(5);

b->left = newNode(3);
b->right = newNode(2);
b->right->left = newNode(5);
b->right->right = newNode(4);

areMirror(a, b)? cout << "Yes" : cout << "No";

return 0;
}
Yes
Time Complexity : O(n)

7. Find the minimum element from the stack in O (1).

Solution: An approach that uses O(1) time and O(n) extra space is discussed here.
In this article, a new approach is discussed that supports minimum with O(1) extra space. We define a
variable minEle that stores the current minimum element in the stack. Now the interesting part is, how to handle the
case when minimum element is removed. To handle this, we push “2x – minEle” into the stack instead of x so that
previous minimum element can be retrieved using current minEle and its value stored in stack. Below are detailed
steps and explanation of working.
Push(x) : Inserts x at the top of stack.
 If stack is empty, insert x into the stack and make minEle equal to x.
 If stack is not empty, compare x with minEle. Two cases arise:
 If x is greater than or equal to minEle, simply insert x.
 If x is less than minEle, insert (2*x – minEle) into the stack and make minEle equal to x. For
example, let previous minEle was 3. Now we want to insert 2. We update minEle as 2 and insert 2*2 – 3
= 1 into the stack.
Pop() : Removes an element from top of stack.
 Remove element from top. Let the removed element be y. Two cases arise:
 If y is greater than or equal to minEle, the minimum element in the stack is still minEle.
 If y is less than minEle, the minimum element now becomes (2*minEle – y), so update (minEle =
2*minEle – y). This is where we retrieve previous minimum from current minimum and its value in
stack. For example, let the element to be removed be 1 and minEle be 2. We remove 1 and update
minEle as 2*2 – 1 = 3.
Important Points:
 Stack doesn’t hold actual value of an element if it is minimum so far.
 Actual minimum element is always stored in minEle
Illustration
Push(x)

 Number to be Inserted: 3, Stack is empty, so insert 3 into stack and minEle = 3.


 Number to be Inserted: 5, Stack is not empty, 5> minEle, insert 5 into stack and minEle = 3.
 Number to be Inserted: 2, Stack is not empty, 2< minEle, insert (2*2-3 = 1) into stack and minEle = 2.
 Number to be Inserted: 1, Stack is not empty, 1< minEle, insert (2*1-2 = 0) into stack and minEle = 1.
 Number to be Inserted: 1, Stack is not empty, 1 = minEle, insert 1 into stack and minEle = 1.
 Number to be Inserted: -1, Stack is not empty, -1 < minEle, insert (2*-1 – 1 = -3) into stack and minEle = -1.
Pop()

 Initially the minimum element minEle in the stack is -1.


 Number removed: -3, Since -3 is less than the minimum element the original number being removed is
minEle which is -1, and the new minEle = 2*-1 – (-3) = 1
 Number removed: 1, 1 == minEle, so number removed is 1 and minEle is still equal to 1.
 Number removed: 0, 0< minEle, original number is minEle which is 1 and new minEle = 2*1 – 0 = 2.
 Number removed: 1, 1< minEle, original number is minEle which is 2 and new minEle = 2*2 – 1 = 3.
 Number removed: 5, 5> minEle, original number is 5 and minEle is still 3

8. How will you insert the elements in Binary trees and tell me about the functioning of Binary search tree
with the help of program.
Solution:
The idea is to do iterative level order traversal of the given tree using queue. If we find a node
whose left child is empty, we make new key as left child of the node. Else if we find a node
whose right child is empty, we make new key as right child. We keep traversing the tree until we
find a node whose either left or right is empty.

// C++ program to insert element in binary tree
#include <iostream>
#include <queue>
using namespace std;

/* A binary tree node has key, pointer to left child


and a pointer to right child */
struct Node {
int key;
struct Node* left, *right;
};

/* function to create a new node of tree and r


eturns pointer */
struct Node* newNode(int key)
{
struct Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
};

/* Inorder traversal of a binary tree*/


void inorder(struct Node* temp)
{
if (!temp)
return;

inorder(temp->left);
cout << temp->key << " ";
inorder(temp->right);
}

/*function to insert element in binary tree */


void insert(struct Node* temp, int key)
{
queue<struct Node*> q;
q.push(temp);

// Do level order traversal until we find


// an empty place.
while (!q.empty()) {
struct Node* temp = q.front();
q.pop();

if (!temp->left) {
temp->left = newNode(key);
break;
} else
q.push(temp->left);
if (!temp->right) {
temp->right = newNode(key);
break;
} else
q.push(temp->right);
}
}

// Driver code
int main()
{
struct Node* root = newNode(10);
root->left = newNode(11);
root->left->left = newNode(7);
root->right = newNode(9);
root->right->left = newNode(15);
root->right->right = newNode(8);

cout << "Inorder traversal before insertion:";


inorder(root);

int key = 12;


insert(root, key);

cout << endl;


cout << "Inorder traversal after insertion:";
inorder(root);

return 0;
}
Copy CodeRun on IDE

Output:

Inorder traversal before insertion: 7 11 10 15 9 8


Inorder traversal after insertion: 7 11 12 10 15 9 8

9. What is the difference between Binary Tree and Binary Search tree?

Ans: A binary tree is made of nodes, where each node contains a "left" pointer, a "right" pointer,
and a data element. The "root" pointer points to the topmost node in the tree. The left and right
pointers recursively point to smaller "subtrees" on either side. A null pointer represents a binary tree
with no elements -- the empty tree. The formal recursive definition is: a binary tree is either empty
(represented by a null pointer), or is made of a single node, where the left and right pointers
(recursive definition ahead) each point to a binary tree.
A binary search tree (BST) or "ordered binary tree" is a type of binary tree where the nodes are
arranged in order: for each node, all elements in its left subtree are less to the node (<), and all the
elements in its right subtree are greater than the node (>).
5
/ \
3 6
/ \ \
1 4 9
The tree shown above is a binary search tree -- the "root" node is a 5, and its left subtree nodes (1, 3,
4) are < 5, and its right subtree nodes (6, 9) are > 5. Recursively, each of the subtrees must also
obey the binary search tree constraint: in the (1, 3, 4) subtree, the 3 is the root, the 1 < 3 and 4 > 3.

10. Given an integer and a tree, represented by an array, find out who is ancestor of the given integer value in
the tree.
Solution:

Given a Binary Tree and a key, write a function that prints all the ancestors of the key in the given
binary tree.
For example, if the given tree is following Binary Tree and key is 7, then your function should
print 4, 2 and 1.

1
/ \
2 3
/ \
4 5
/
7

#include<iostream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

/* A binary tree node has data, pointer to left child


and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};

/* If target is present in tree, then prints the ancestors


and returns true, otherwise returns false. */
bool printAncestors(struct node *root, int target)
{
/* base cases */
if (root == NULL)
return false;
if (root->data == target)
return true;

/* If target is present in either left or right subtree of this node,


then print this node */
if ( printAncestors(root->left, target) ||
printAncestors(root->right, target) )
{
cout << root->data << " ";
return true;
}

/* Else return false */


return false;
}

/* Helper function that allocates a new node with the


given data and NULL left and right pointers. */
struct node* newnode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

/* Driver program to test above functions*/


int main()
{

/* Construct the following binary tree


1
/ \
2 3
/ \
4 5
/
7
*/
struct node *root = newnode(1);
root->left = newnode(2);
root->right = newnode(3);
root->left->left = newnode(4);
root->left->right = newnode(5);
root->left->left->left = newnode(7);

printAncestors(root, 7);

getchar();
return 0;
}
Output:
421
Time Complexity: O(n) where n is the number of nodes in the given Binary Tree.

11. A matrix is given, such that in every row and column numbers are in increasing order, Find an element in
complexity of O (n).

Solution: Below is an efficient solution that works in O(n) time.


Let x = element we're trying to search for in the matrix,
e = current element we're processing in the array.
1) Start with top right element.
2) Loop: compare this element e with x
...i) if e = x, then return position of e, since we found x in the given matrix.
...ii) if e > x then move left to check elements smaller than e (if out of bound of matrix, then break and return false)
...iii) if e < x then move below to check elements greater than e (if out of bound of matrix, then break and return
false)
3) repeat the i), ii) and iii) until you find the element or return false
// C++ program to search an element in row-wise
// and column-wise sorted matrix
#include <bits/stdc++.h>

using namespace std;

/* Searches the element x in mat[][]. If the


element is found, then prints its position
and returns true, otherwise prints "not found"
and returns false */
int search(int mat[4][4], int n, int x)
{
int i = 0, j = n-1; //set indexes for top right element
while ( i < n && j >= 0 )
{
if ( mat[i][j] == x )
{
cout << "n Found at "
<< i << ", " << j;
return 1;
}
if (mat[i][j] > x )
j--;
else // if mat[i][j] < x
i++;
}

cout << "n Element not found";


return 0; // if ( i==n || j== -1 )
}
// Driver code
int main()
{
int mat[4][4] = { {10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};
search(mat, 4, 29);

return 0;
}

// This code is contributed


// by Akanksha Rai(Abby_akku)
Copy CodeRun on IDE
Output :
n Found at 2, 1
Time Complexity: O(n)

12. In a 2-D Character matrix, mine sweeper game, (.) was representing empty Cells,(x) was representing
mines. Find the number of groups of mines?

Solution: This is an interactive problem. Interactive problems differ from classic problems in that your solution
will send and receive data from a special judge program instead of from static files. Pay special attention to the
notice on output buffering described in the "Input + Output" section below.
An N × N field contains many mines. Each mine occupies some cell of the field. Each cell could contain at most
one mine. There are M mines in all at the field. You need to neutralize all of the mines so it will be safe to pass
through. The mines are neutralized with dynamite. A single piece of dynamite can be used to neutralize a single
cell. You have only K pieces of dynamite. But don't worry, it is guaranteed that K ≥ M.
You may perform two operations:
 Neutralize - neutralize the mine in the specified cell, if one exists. Otherwise has no effect. This
operation may be performed at most K times.
 Survey - check a cell for a mine, and if it doesn't have a mine count the number of cells adjacent to it
containing mines. Previously neutralized mines are not counted. Each cell is adjacent to up to 8 other cells
(2 horizontally, 2 vertically, and 4 diagonally). This operation may be performed at most N2 times. But you
could survey the same cell twice if necessary and also it is allowed to survey the cell after neutralize
operation was applied to it.
Surveying is very dangerous, so you need to try to minimize the number of survey operations you perform.
Submissions that use fewer survey operations will score more points.

Input + Output
Input begins with the line containing 3 space separated integers N, M, and K, the size of the field, the number
of mines, and the number of pieces of dynamite, respectively. The locations of mines are predetermined but
currently unknown to you.
To perform a neutralize operation, print a line containing "N x y" (without quotes), where x and y are the
coordinates of the cell you wish to neutralize (0 ≤ x, y < N).
To perform a survey operation, print "S x y" (without quotes), where x and y are the coordinates of the cell you
wish to check (0 ≤ x, y < N). Then read a line containing a single character. This character will be 'M' if the cell
contains a mine, otherwise it will be an integer between 0 and 8, indicating the number of cells adjacent to the
specified cell that contain mines.
When you are finished, print "Done" (without quotes).
Note that you will receive Wrong Answer verdict if one of the following happens:
 You will perform more than N2 survey operations.
 You will perform more than K neutralize operations.
 You will output operation in wrong format.
In particular, x and y should be between 0 and N − 1, inclusive.
 You will output "Done" but not all mines are neutralized.
Attention: the program should clear the output buffer after printing each line. It can be done using
fflush(stdout) command or by setting the proper type of buffering at the beginning of the execution -
setlinebuf(stdout). Failure to flush the output buffer will result in Time Limit Exceeded verdict.
For example, at C/C++ you could use the following routines:
char Survey(int x, int y) {
printf("S %d %d\n", x, y);
fflush(stdout);
char res;
scanf(" %c", &res);
return res;
}

void Neutralize(int x, int y) {


printf("N %d %d\n", x, y);
fflush(stdout); /* but it is not necessary here */
}

Scoring
Suppose you successfully neutralized all mines using S survey operations.
Then your score is 10 * (S + 1) / N2. Lower scores will earn more points.

Sample Input + Output


In: 4 2 3
Out: S 0 0
In: 0
Out: S 2 3
In: 2
Out: S 1 2
In: M
Out: N 1 2
Out: S 2 3
In: 1
Out: S 3 2
In: 1
Out: N 2 2
Out: N 3 3
Out: Done
Explanation
The mines are located at (1, 2) and (3, 3). The operations proceed as follows:
 Survey (0, 0). This cell does not contain a mine, nor do any of its 3 neighbors ((0, 1), (1, 0) and (1, 1)),
so the result is "0".
 Survey (2, 3). This cell does not contain a mine, but 2 of its 5 neighbors contain mines, so the result is
"2".
 Survey (1, 2). This cell contains a mine. The survey result is "M".
 Neutralize (1, 2). Destroy the mine in the cell (1, 2).
 Survey (2, 3). This cell was surveyed before, however the mine in (1, 2) has now been neutralized, so
only one mine remains and the result is "1".
 Survey (3, 2). This cell is adjacent to the remaining mine.
 Neutralize (2, 2). This cell does not contain a mine, but we have a spare piece of dynamite so it's okay to
neutralize this cell unnecessarily.
 Neutralize (3, 3). Destroy the last mine in the cell (3, 3).
 Done. All of the mines have now been neutralized.
Note that the above sequence of operations is also consistent with the mines having been located at (1, 2) and
(2, 2). This sample performs 5 survey operations, and therefore would score 10 * (5 + 1) / 42 = 3.75.

13. In Binary Search Tree, Print Right View of the tree O(n).

Solution: Given a Binary Tree, print Right view of it. Right view of a Binary Tree is set of nodes visible
when tree is visited from Right side.
Right view of following tree is 1 3 7 8

1
/ \
2 3
/ \ / \
4 5 6 7
\
8
The Right view contains all nodes that are last nodes in their levels. A simple solution is to do level order
traversal and print the last node in every level.
The problem can also be solved using simple recursive traversal. We can keep track of level of a node by
passing a parameter to all recursive calls. The idea is to keep track of maximum level also. And traverse the
tree in a manner that right subtree is visited before left subtree. Whenever we see a node whose level is
more than maximum level so far, we print the node because this is the last node in its level (Note that we
traverse the right subtree before left subtree). Following is C implementation of this approach.

// C program to print right view of Binary Tree


#include<stdio.h>
#include<stdlib.h>

struct Node
{
int data;
struct Node *left, *right;
};

// A utility function to create a new Binary Tree Node


struct Node *newNode(int item)
{
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}

// Recursive function to print right view of a binary tree.


void rightViewUtil(struct Node *root, int level, int *max_level)
{
// Base Case
if (root==NULL) return;

// If this is the last Node of its level


if (*max_level < level)
{
printf("%d\t", root->data);
*max_level = level;
}

// Recur for right subtree first, then left subtree


rightViewUtil(root->right, level+1, max_level);
rightViewUtil(root->left, level+1, max_level);
}

// A wrapper over rightViewUtil()


void rightView(struct Node *root)
{
int max_level = 0;
rightViewUtil(root, 1, &max_level);
}

// Driver Program to test above functions


int main()
{
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);

rightView(root);

return 0;
}

Output:
1 3 7 8

14. Suppose an Array is given as 1 3 5 7 8.Print a pyramid such that above elements becomes the base and
every element above it is sum of elements below it.
Ans:
15. How websites are blocked by Government?

Ans: Governments definitely can block your websites.Just look at examples such as Russia, China
or UAE. China, for example, has adopted a practice of blocking IPs of websites that don’t agree
with the ideology of China’s politics. Another example is Dubai where websites including adult
content, gambling or betting, anything anti-Islam, dating or drugs are blocked.

Website blocks are worked around with VPNs. But of course most governments, like China and
UAE block VPNs too. So the only way to work around this issues is to find a VPN service which
can provide you with servers that are not yet blocked by your country.

16. Find the distance between two nodes in Binary Search Tree.
17.

Ans: Given a Binary Search Tree and two keys in it. Find the distance between two nodes with given two
keys. It may be assumed that both keys exist in BST.

Input : Root of above tree


a = 3, b = 9
Output : 4
Distance between 3 and 9 in
above BST is 4.

Input : Root of above tree


a = 9, b = 25
Output : 3
Distance between 9 and 25 in
above BST is 3.

In case of BST, we can find distance faster. We start from root and for every node, we do
following.
1. If both keys are greater than current node, we move to right child of current node.
2. If both keys are smaller than current node, we move to left child of current node.
3. If one keys is smaller and other key is greater, current node is Lowest Common Ancestor
(LCA) of two nodes. We find distances of current node from two keys and return sum of the
distances.
// CPP program to find distance between
// two nodes in BST
#include <bits/stdc++.h>
using namespace std;

struct Node {
struct Node* left, *right;
int key;
};

struct Node* newNode(int key)


{
struct Node* ptr = new Node;
ptr->key = key;
ptr->left = ptr->right = NULL;
return ptr;
}

// Standard BST insert function


struct Node* insert(struct Node* root, int key)
{
if (!root)
root = newNode(key);
else if (root->key > key)
root->left = insert(root->left, key);
else if (root->key < key)
root->right = insert(root->right, key);
return root;
}

// This function returns distance of x from


// root. This function assumes that x exists
// in BST and BST is not NULL.
int distanceFromRoot(struct Node* root, int x)
{
if (root->key == x)
return 0;
else if (root->key > x)
return 1 + distanceFromRoot(root->left, x);
return 1 + distanceFromRoot(root->right, x);
}
// Returns minimum distance beween a and b.
// This function assumes that a and b exist
// in BST.
int distanceBetween2(struct Node* root, int a, int b)
{
if (!root)
return 0;

// Both keys lie in left


if (root->key > a && root->key > b)
return distanceBetween2(root->left, a, b);

// Both keys lie in right


if (root->key < a && root->key < b) // same path
return distanceBetween2(root->right, a, b);

// Lie in opposite directions (Root is


// LCA of two nodes)
if (root->key >= a && root->key <= b)
return distanceFromRoot(root, a) +
distanceFromRoot(root, b);
}

// This function make sure that a is smaller


// than b before making a call to findDistWrapper()
int findDistWrapper(Node *root, int a, int b)
{
if (a > b)
swap(a, b);
return distanceBetween2(root, a, b);
}

// Driver code
int main()
{
struct Node* root = NULL;
root = insert(root, 20);
insert(root, 10);
insert(root, 5);
insert(root, 15);
insert(root, 30);
insert(root, 25);
insert(root, 35);
int a = 5, b = 55;
cout << findDistWrapper(root, 5, 35);
return 0;
}

Output:
2
Time Complexity : O(h) where h is height of Binary Search Tree.

18. In C ++ write the code for system Crash?


Solution:

19. The players are ranked from 1 to 2 ^n .Condition is player 1 can beat all players ranked below him, similarly
player 2 can beat all ranked above him, So who will win the tournament and how many matches are to be played
in order to player two winning the tournament if it is knock out tournament?
Ans: Aptitude Question
20. What is the Thread in Operating System?

Ans: A process, in the simplest terms, is an executing program. One or more threads run in the
context of the process. A thread is the basic unit to which the operating system allocates processor
time. A thread can execute any part of the process code, including parts currently being executed by
another thread.
Drive Name: ZS ASSOCIATES
Book Index: 213 (C)

TECHNICAL INTERVIEW

1. What are checked & unchecked exceptions?


Answer:
In Java, there are two types of exceptions:

1) Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked
exception, then the method must either handle the exception or it must specify the exception using throws keyword.

For example, consider the following Java program that opens file at location “C:\test\a.txt” and prints the first three
lines of it. The program doesn’t compile, because the function main() uses FileReader() and FileReader() throws a
checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also
throw checked exception IOException

import java.io.*;

class Main {
public static void main(String[] args) {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);

// Print first 3 lines of file "C:\test\a.txt"


for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());

fileInput.close();
}
}
Output:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code -


unreported exception java.io.FileNotFoundException; must be caught or declared to be
thrown at Main.main(Main.java:5)
To fix the above program, we either need to specify list of exceptions using throws, or we need to use try-catch
block. We have used throws in the below program. Since FileNotFoundException is a subclass of IOException, we
can just specify IOException in the throws list and make the above program compiler-error-free.

import java.io.*;

class Main {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);

// Print first 3 lines of file "C:\test\a.txt"


for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());

fileInput.close();
}
}
Output: First three lines of file “C:\test\a.txt”
2) Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions are unchecked, so it is
not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and
specify or catch the exceptions.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under
throwable is checked.

Consider the following Java program. It compiles fine, but it throws ArithmeticException when run. The compiler
allows it to compile, because ArithmeticException is an unchecked exception.
class Main {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero


at Main.main(Main.java:5)
Java Result: 1

2. Have you ever panicked in a tough situation? How did you handle it?
Answer:
Not a Technical Question.

3. What is a deadlock in OS?


Answer:
A process in operating systems uses different resources and uses resources in following way.
1) Requests a resource
2) Use the resource
2) Releases the resource

Deadlock is a situation where a set of processes are blocked because each process is holding a resource and waiting
for another resource acquired by some other process.
Consider an example when two trains are coming toward each other on same track and there is only one track, none
of the trains can move once they are in front of each other. Similar situation occurs in operating systems when there
are two or more processes hold some resources and wait for resources held by other(s). For example, in the below
diagram, Process 1 is holding Resource 1 and waiting for resource 2 which is acquired by process 2, and process 2 is
waiting for resource 1.

4. If There is a bridge to be built in an island, but it’s faulty. How will you convince the people of the island
not to build it?
Answer:
Not a Technical Question.

5. What is your greatest weakness?


Answer:
Not a Technical Question.

6. What are the different models in RDBMS?


Answer:

A Database model defines the logical design and structure of a database and defines how data will be stored,
accessed and updated in a database management system. While the Relational Model is the most widely used
database model, there are other models too:

 Hierarchical Model
 Network Model
 Entity-relationship Model
 Relational Model
Hierarchical Model
This database model organises data into a tree-like-structure, with a single root, to which all the other data is linked.
The hierarchy starts from the Root data, and expands like a tree, adding child nodes to the parent nodes.
In this model, a child node will only have a single parent node.
This model efficiently describes many real-world relationships like index of a book, recipes etc.
In hierarchical model, data is organised into tree-like structure with one one-to-many relationship between two
different types of data, for example, one department can have many courses, many professors and of-course many
students.

Network Model
This is an extension of the Hierarchical model. In this model data is organised more like a graph, and are allowed to
have more than one parent node.
In this database model data is more related as more relationships are established in this database model. Also, as the
data is more related, hence accessing the data is also easier and fast. This database model was used to map many-to-
many data relationships.
This was the most widely used database model, before Relational Model was introduced.

Entity-relationship Model
In this database model, relationships are created by dividing object of interest into entity and its characteristics into
attributes.
Different entities are related using relationships.
E-R Models are defined to represent the relationships into pictorial form to make it easier for different stakeholders
to understand.
This model is good to design a database, which can then be turned into tables in relational model(explained below).
Let's take an example, If we have to design a School Database, then Student will be an entity with attributes name,
age, address etc. As Address is generally complex, it can be another entity with attributes street name, pincode, city
etc, and there will be a relationship between them.
Relationships can also be of different types. To learn about E-R Diagrams in details, click on the link.

Relational Model
In this model, data is organised in two-dimensional tables and the relationship is maintained by storing a common
field.
This model was introduced by E.F Codd in 1970, and since then it has been the most widely used database model,
infact, we can say the only database model used around the world.
The basic structure of data in the relational model is tables. All the information related to a particular type is stored in
rows of that table.
Hence, tables are also known as relations in relational model.
In the coming tutorials we will learn how to design tables, normalize them to reduce data redundancy and how to use
Structured Query language to access data from tables.
Drive Name: SOFT PRODIGY
Book Index: 211-(D)

Technical interview
1. What are access specifications?
Ans: Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility
of classes, methods, and other members. Access modifiers are a specific part of programming language syntax
used to facilitate the encapsulation of components.1

So an Access Specifier aka Access Modifier takes certain class, method, or variable and decides what other
classes are allowed to use them. The most common Access Specifiers are Public, Protected, and Private. What
these mean can vary depending on what language you are in, but I'm going to use C++ as an example since that's
what the article uses.

Accessor Method | Who Can Call It


-----------------------------------------------------------------------
Private | Only the class who created it
Protected | The class who created it and derived classes that "inherit" from this class
Public | Everyone can call it

2. What is abstract cloud?


Ans: Deploying a complex application on a Cloud-based infrastructure can be a challenging task. In this
contribution we present an approach for Cloud-based deployment of applications and its present or future
implementation in the framework of several projects, such as !CHAOS: a cloud of controls, a project funded by
MIUR (Italian Ministry of Research and Education) to create a Cloud-based deployment of a control system and
data acquisition framework, INDIGO-DataCloud, an EC H2020 project targeting among other things high-level
deployment of applications on hybrid Clouds, and Open City Platform, an Italian project aiming to provide open
Cloud solutions for Italian Public Administrations. We considered to use an orchestration service to hide the
complex deployment of the application components, and to build an abstraction layer on top of the orchestration
one. Through Heat orchestration service, we prototyped a dynamic, on-demand, scalable platform of software
components, based on OpenStack infrastructures. On top of the orchestration service we developed a prototype
of a web interface exploiting the Heat APIs. The user can start an instance of the application without having
knowledge about the underlying Cloud infrastructure and services. Moreover, the platform instance can be
customized by choosing parameters related to the application such as the size of a File System or the number of
instances of a NoSQL DB cluster. As soon as the desired platform is running, the web interface offers the
possibility to scale some infrastructure components. In this contribution we describe the solution design and
implementation, based on the application requirements, the details of the development of both the Heat templates
and of the web interface, together with possible exploitation strategies of this work in Cloud data centers.

3. Difference between final, finally and Finalize keyword?


Ans: There are many differences between final, finally and finalize. A list of differences between final, finally and finalize are given below:
No. final finally finalize

1) Final is used to apply restrictions on class, Finally is used to place important Finalize is used to perform clean up
method and variable. Final class can't be code, it will be executed whether processing just before object is garbage
inherited, final method can't be overridden exception is handled or not. collected.
and final variable value can't be changed.

2) Final is a keyword. Finally is a block. Finalize is a method.

4. Explain Post and pre-increment in a program.


Ans: Pre-increment operator: A pre-increment operator is used to increment the value of a variable before using
it in a expression. In the Pre-Increment, value is first incremented and then used inside the expression.

Syntax:

a = ++x;
Here, if the value of ‘x’ is 10 then value of ‘a’ will be 11 because the value of ‘x’ gets modified before using it in
the expression.
// CPP program to demonstrate pre increment
// operator.
#include <iostream>
using namespace std;

int main()
{
int x = 10, a;

a = ++x;
cout << "Pre Increment Operation";

// Value of a will change


cout << "\na = " << a;

// Value of x change before execution of a=++x;


cout << "\nx = " << x;

return 0;
}

Output :
Pre Increment Operation
a = 11
x = 11

Post-increment operator: A post-increment operator is used to increment the value of variable after executing
expression completely in which post increment is used. In the Post-Increment, value is first used in a expression
and then incremented.
Syntax:
a = x++;
Here, suppose the value of ‘x’ is 10 then value of variable ‘b’ will be 10 because old value of ‘x’ is
used.
// CPP program to demonstrate pre increment
// operator.
#include <iostream>
using namespace std;

int main()
{
int x = 10, a;

a = x++;

cout << "Post Increment Operation";

// Value of a will not change


cout << "\na = " << a;

// Value of x change after execution of a=x++;


cout << "\nx = " << x;

return 0;
}
Output :
Post Increment Operation
a = 10
x = 11

5. What is OOPS interface?


Ans: Interface, also known as protocol, is an alternative to inheritance for two unrelated classes to communicate
with each other. An interface defines methods and (often, but not always) values. Every class that implement the
interface must provide a concrete method for each method of the interface.

For example, you want to simulate ejection, or dismissal. Since only players and coaches can be ejected from the
field you cannot make it a method of the parent class that represent people. So you create an interface Ejectable
with a method Ejection() and make Player and Coach implement it.

Example of an Interface

interface Ejectable
{
Ejection()
}

class Player : implement Ejectable


{
Ejection()
{
// storm out of the field screaming
}
}

class Coach : implement Ejectable


{
Ejection()
{
// take your cellphone to talk with your assistant
}
}

interface Ejectable
{
Ejection()
}

class Player : implement Ejectable


{
Ejection()
{
// storm out of the field screaming
}
}

class Coach : implement Ejectable


{
Ejection()
{
// take your cellphone to talk with your assistant
}
}

There is not a standard way of describing the relationship that an interface establish, but you can thought it as
behave-as. In our example a Player behave-as Ejectable.

6. Tell me something about your project. What was your role in the project?
Ans: Depends on Student Answer
7. How you handled any conflicts, which occurred while working in the project?
Ans: Depends on Student Answer
Drive Name: MAVEN WAVE INDIA PVT. LTD.
Book Index: 215 (D)
TECHNICAL INTERVIEW

1. What is polymorphism?
Answer:
The word polymorphism is used in various contexts and describes situations in which something
occurs in several different forms. In computer science, it describes the concept that objects of different
types can be accessed through the same interface. Each type can provide its own, independent
implementation of this interface. It is one of the core concepts of object-oriented programming (OOP).
Java supports 2 types of polymorphism:

1.static or compile-time 2.Dynamic or Runtime

2. What is inheritance?
Answer:
In object-oriented programming, inheritance is the mechanism of basing an object or class upon
another object or class, retaining similar implementation. In most class-based object-oriented languages, an
object created through inheritance acquires all the properties and behaviors of the parent object.

3. What is the difference between Procedural programming and OOPS?


Definition

OOP stands for Object-oriented programming and is a programming approach that focuses on data rather
than the algorithm, whereas POP, short for Procedure-oriented programming, focuses on procedural
abstractions.

Programs

In OOP, the program is divided into small chunks called objects which are instances of classes, whereas in
POP, the main program is divided into small parts based on the functions.

Accessing Mode

Three accessing modes are used in OOP to access attributes or functions – ‘Private’, ‘Public’, and
‘Protected’. In POP, on the other hand, no such accessing mode is required to access attributes or functions
of a particular program.

1. Focus

The main focus is on the data associated with the program in case of OOP while POP relies on functions or
algorithms of the program.

1. Execution
In OOP, various functions can work simultaneously while POP follows a systematic step-by-step approach
to execute methods and functions.

1. Data Control

In OOP, the data and functions of an object act like a single entity so accessibility is limited to the member
functions of the same class. In POP, on the other hand, data can move freely because each function
contains different data.

1. Security

OOP is more secure than POP, thanks to the data hiding feature which limits the access of data to the
member function of the same class, while there is no such way of data hiding in POP, thus making it less
secure.

1. Ease of Modification

New data objects can be created easily from existing objects making object-oriented programs easy to
modify, while there’s no simple process to add data in POP, at least not without revising the whole
program.

1. Process

OOP follows a bottom-up approach for designing a program, while POP takes a top-down approach to
design a program.e.gCommonly used OOP languages are C++, Java, VB.NET, etc. Pascal and Fortran are
used by POP.

4. Is Java a pure object oriented language? If not why?


Answer:
Java is not fully object oriented because it supports primitive data type like it,byte,long etc.,which are not
objects.

5. Tell me about your project.


Answer:
Answer differs according to student

6. What is Java?

Java is a programming language that produces software for multiple platforms. When a programmer writes
a Java application, the compiled code (known as bytecode) runs on most operating systems (OS), including
Windows, Linux and Mac OS. Java derives much of its syntax from the C and C++ programming
languages.
Java was developed in the mid-1990s by James A. Gosling, a former computer scientist with Sun
Microsystems.

7. What is SQL?
 SQL stands for Structured Query Language
 SQL lets you access and manipulate databases
 SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in 1987

8. Tell me some basic queries of SQL.

a)The SQL SELECT Statement

The SELECT statement is used to select data from a database.

The data returned is stored in a result table, called the result-set.

SELECT Syntax
Select col1,col2……… from tablename;

b)The SQL INSERT INTO Statement

The INSERT INTO statement is used to insert new records in a table.

INSERT INTO Syntax

It is possible to write the INSERT INTO statement in two ways.

The first way specifies both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);

If you are adding values for all the columns of the table, you do not need to specify the column names in
the SQL query. However, make sure the order of the values is in the same order as the columns in the table.
The INSERT INTO syntax would be as follows:

INSERT INTO table_name


VALUES (value1, value2, value3, ...);
c)The SQL UPDATE Statement

The UPDATE statement is used to modify the existing records in a table.

UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Drive Name: Just Dial
Book Index: 281(D)

Technical

1. Given an array of numbers, combine them in a way that yields the


largest value.

int myCompare(string X, string Y)


{
// first append Y at the end of X
string XY = X.append(Y);

// then append X at the end of Y


string YX = Y.append(X);

// Now see which of the two formed numbers is greater


return XY.compare(YX) > 0 ? 1: 0;
}

// The main function that prints the arrangement with the largest value.
// The function accepts a vector of strings
void printLargest(vector<string> arr)
{
// Sort the numbers using library sort funtion. The function uses
// our comparison function myCompare() to compare two strings.
// See http://www.cplusplus.com/reference/algorithm/sort/ for details
sort(arr.begin(), arr.end(), myCompare);

for (int i=0; i < arr.size() ; i++ )


cout << arr[i];
}

// driver program to test above functions


int main()
{
vector<string> arr;

//output should be 6054854654


arr.push_back("54");
arr.push_back("546");
arr.push_back("548");
arr.push_back("60");
printLargest(arr);

// output should be 777776


/*arr.push_back("7");
arr.push_back("776");
arr.push_back("7");
arr.push_back("7");*/

//output should be 998764543431


/*arr.push_back("1");
arr.push_back("34");
arr.push_back("3");
arr.push_back("98");
arr.push_back("9");
arr.push_back("76");
arr.push_back("45");
arr.push_back("4");
*/

return 0;
}

2. Write a program to find the sum of contiguous sub array within one-
dimensional array of numbers, which has the largest sum.

int maxSubArraySum(int a[], int size)


{
int max_so_far = INT_MIN, max_ending_here = 0;

for (int i = 0; i < size; i++)


{
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;

if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}

/*Driver program to test maxSubArraySum*/


int main()
{
int a[] = {-2, -3, 4, -1, -2, 1, 5, -3};
int n = sizeof(a)/sizeof(a[0]);
int max_sum = maxSubArraySum(a, n);
cout << "Maximum contiguous sum is " << max_sum;
return 0;
}

3. Given an integer n, print the pattern


Input: contains the value of n
Output: pattern

int main()
{
int i, j, rows;

printf("Enter number of rows: ");


scanf("%d",&rows);

for(i=1; i<=rows; ++i)


{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}
Drive Name: Evry India PVT. Lt.
Book Index: 214(D)
Technical Interview
1. Tell me something about the project.
Depends
2. On which platform was it done.
Depends
3. Do you have any future study plans?
Depends
4. Do you have any certification related to entrances exams?
Answer : It can be Gate,Cat,Mat etc.
5. Differentiate between C and C++.
Answer:Difference between C and C++

C C++

C was developed by
Dennis Ritchie between C++ was developed by Bjarne Stroustrup in 1979 with C++'s predecessor "C
1969 and 1973 at AT&T with Classes".
Bell Labs.

When compared to C++, C C++ is a superset of C. C++ can run most of C code while C cannot run C++
is a subset of C++. code.

C supports procedural
C++ supports both procedural and object oriented programming paradigms;
programming paradigm
therefore C++ is also called a hybrid language.
for code development.

C does not support object


oriented programming;
therefore it has no
Being an object oriented programming language C++ supports
support for
polymorphism, encapsulation, and inheritance.
polymorphism,
encapsulation, and
inheritance.

In C (because it is a In C++ (when it is used as object oriented programming language), data and
procedural programming functions are encapsulated together in form of an object. For creating
language), data and objects class provides a blueprint of structure of the object.
functions are separate and
free entities.

In C, data are free entities


and can be manipulated
by outside code. This is In C++, Encapsulation hides the data to ensure that data structures and
because C does not operators are used as intended.
support information
hiding.

C, being a procedural
While, C++, being an object oriented programming, it is an object driven
programming, it is a
language.
function driven language.

C does not support


function and operator C++ supports both function and operator overloading.
overloading.

C does not allow functions


to be defined inside In C++, functions can be used inside a structure.
structures.

C++ uses NAMESPACE which avoid name collisions.

A namespace is a declarative region that provides a scope to the identifiers


(the names of types, functions, variables, etc) inside it. Namespaces are
C does not have used to organize code into logical groups and to prevent name collisions
namespace feature. that can occur especially when your code base includes multiple libraries. All
identifiers at namespace scope are visible to one another without
qualification. Identifiers outside the namespace can access the members by
using the fully qualified name for each identifier.

C uses functions for input/


output. For example C++ uses objects for input output. For example cin and cout.
scanf and printf.

C does not support


C++ supports reference variables.
reference variables.

C has no support for


virtual and friend C++ supports virtual and friend functions.
functions.

C provides malloc() C++ provides new operator for memory allocation and delete operator
and calloc() functions for memory de-allocation.
for dynamic memory
allocation, and free()
for memory de-allocation.

C does not provide direct


support for error handling C++ provides support for exception handling. Exceptions are used for "hard"
(also called exception errors that make the code incorrect.
handling)

6. What do you understand by Stack and Queue?


Answer: Stacks: Stack is collection of elements, that follows the LIFO order. LIFO stands for Last
In First Out, which means element which is inserted most recently will be removed first. Imagine a
stack of tray on the table. When you put a tray there you put it at top, and when you remove it, you
also remove it from top.
A stack has a restriction that insertion and deletion of element can only be done from only one end
of stack and we call that position as top. The element at top position is called top element. Insertion
of element is called PUSH and deletion is called POP.
Queue:
Queue is a data structure that follows the FIFO principle. FIFO means First In First Out i.e the
element added first in the queue will be the one to be removed first. Elements are always added to
the back and removed from the front. Think of it as a line of people waiting for a bus at the bus
stand. The person who will come first will be the first one to enter the bus.

Queue supports some fundamental functions:


Dequeue: Removes the element from the front of the queue if the queue is not empty otherwise it
will print “UnderFlow”
Enqueue: Adds an element to the back of the queue if the queue is not full otherwise it will print
“OverFlow”.

7. What is Binary Search?


Answer: Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an
interval covering the whole array. If the value of the search key is less than the item in the middle of the interval,
narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is
found or the interval is empty.
8. What is Bubble Sort?
Answer:
Bubble Sort

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in
wrong order.

Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole
pass without any swap to know it is sorted.

Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

9. What is Database? Elaborate.


Answer: Database is a systematic collection of data. Databases support storage and manipulation of data. Databases
make data management easy. Few examples, An online telephone directory would definitely use database to
store data pertaining to people, phone numbers, other contact details, etc. Your electricity service provider is
obviously using a database to manage billing , client related issues, to handle fault data, etc.
10. What are references and pointers?
Answer: Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be
dereferenced with * operator to access the memory location it points to.
References : A reference variable is an alias, that is, another name for an already existing variable. A reference, like
a pointer is also implemented by storing the address of an object. A reference can be thought of as a constant
pointer (not to be confused with a pointer to a constant value!) with automatic indirection, i.e the compiler will
apply the * operator for you.
A pointer can be re-assigned. This property is useful for implementation of data structures like linked list, tree, etc.
See the following examples:

int x = 5;
int y = 6;
int *p;
p = &x;
p = &y;

On the other hand, a reference cannot be re-assigned, and must be assigned at initialization.
int x = 5;
int y = 6;
int &r = x;

11. Define access specifiers.


Answer: Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility
of classes, methods, and other members. Access modifiers are a specific part of programming language syntax
used to facilitate the encapsulation of components. ... A class cannot be declared as private.

12. How inheritance can be implemented in C?


Answer:The C language being very lenient with type-safe programming, it is then safe to pass the new structure as a
casted pointer to a base function using the parent. The advantage is that adding a member in the parent will not
require changing all descendants.

struct parent {

int parent_i;
char parent_c;
};

struct descendant {
struct parent parent_data;
int descendant_d;
};
#define descendant_i parent_data.parent_i
#define descendant_c parent_data.parent_c
13. Given a table in HTML, write a code to divide a cell of the table in two parts.
Answer: <TABLE BORDER>

<TR>
<TD>Item 1</TD>
<TD>Item 1</TD>
<TD COLSPAN=2>Item 2</TD>
</TR>
<TR>
<TD>Item 3</TD>
<TD>Item 3</TD>
<TD>Item 4</TD>
<TD>Item 5</TD>
</TR>
</TABLE>

14. How to implement and display the data using join query when data is given to you about different
employees and managers?
Answer: SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULLOUTERJOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

15. What is SQL?


Answer:
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in 1987 some basic queries of SQL.
16. Tell me about Isnull function and update function in SQL.
Answer: The SQL Server ISNULL() function lets you return an alternative value when an expression
is NULL:
SELECT ProductName, UnitPrice * (UnitsInStock + ISNULL(UnitsOnOrder, 0))
FROM Products
The UPDATE statement is used to modify the existing records in a table.
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
17. What is the full form of DDL and DML?
Answer: Full form of DDL is Data Definition Language. It is used to create and database objects in a database.Eg:
CREATE, ALTER, DROP.
DML: Full form of DML is Data Manipulation Language. It is used to retrieve, store, modify, delete, insert and
update data in database.Eg: INSERT, UPDATE, DELETE,SELECT.
THECNICLA INTERVIEW QUESTIONS

15. How database can be connected in C language?


Ans: #include<stdio.h>
#include<SQLAPI.h> // main SQLAPI++ header

int main(int argc, char* argv[])


{
// create connection object to connect to database
SAConnection con;
try
{
// connect to database
// in this example, it is Oracle,
// but can also be Sybase, Informix, DB2
// SQLServer, InterBase, SQLBase and ODBC
con.Connect ("test", // database name
"tester", // user name
"tester", // password
SA_Oracle_Client); //Oracle Client
printf("We are connected!\n");

// Disconnect is optional
// autodisconnect will occur in destructor if needed
con.Disconnect();
printf("We are disconnected!\n");
}

catch(SAException & x)
{
// SAConnection::Rollback()
// can also throw an exception
// (if a network error for example),
// we will be ready
try
{
// on error rollback changes
con.Rollback ();
}
catch(SAException &)
{
}
// print error message
printf("%s\n", (const char*)x.ErrText());
}
return 0;
}
16. Explain your project in detail.
Ans:

17. int n=4, n=n>>2, if given is the code, What will be the output
Ans: output will be 1

18. What is Database normalization?


Ans: Database normalization is the process of restructuring a relational database in accordance with a series of so-
called normal forms in order to reduce data redundancy and improve data integrity. It was first proposed by
Edgar F. Codd as an integral part of his relational model.

19. What are the types of pointers in Java?


Ans: We use reference in Java.
Reference: A reference is a variable that refers to something else and can be used as an alias for that something else.
Pointer: A pointer is a variable that stores a memory address, for the purpose of acting as an alias to what is stored at
that address.
So, a pointer is a reference, but a reference is not necessarily a pointer. Pointers are a particular implementation of
the concept of a reference, and the term tends to be used only for languages that give you direct access to the
memory address.

20. What is jdbc function in Java?


Ans: The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational
Database. JDBC helps you to write Java applications that manage these three programming activities: Connect to
a data source, like a database. Send queries and update statements to the database.

21. Print a value without using printf in C language?


Ans:
#include<stdio.h>
int main(){
switch (printf("Chandigarh" ))
{ }
}

22. Divide a number without using /.


Ans: #include <bits/stdc++.h>
using namespace std;

// Function to divide a by b and


// return floor value it
int divide(int dividend, int divisor) {

// Calculate sign of divisor i.e.,


// sign will be negative only iff
// either one of them is negative
// otherwise it will be positive
int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;

// Update both divisor and


// dividend positive
dividend = abs(dividend);
divisor = abs(divisor);

// Initialize the quotient


int quotient = 0;
while (dividend >= divisor) {
dividend -= divisor;
++quotient;
}

return sign * quotient;


}

// Driver code
int main() {
int a = 10, b = 3;
cout << divide(a, b) <<"\n";

a = 43, b = -8;
cout << divide(a, b);

return 0;
}

23. Write a program where the comparison between c++ and python can be drawn.
Ans:C++
#include <bits/stdc++.h>
using namespace std;

// Function to divide a by b and


// return floor value it
int divide(int dividend, int divisor) {

// Calculate sign of divisor i.e.,


// sign will be negative only iff
// either one of them is negative
// otherwise it will be positive
int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1;

// Update both divisor and


// dividend positive
dividend = abs(dividend);
divisor = abs(divisor);

// Initialize the quotient


int quotient = 0;
while (dividend >= divisor) {
dividend -= divisor;
++quotient;
}

return sign * quotient;


}

// Driver code
int main() {
int a = 10, b = 3;
cout << divide(a, b) <<"\n";

a = 43, b = -8;
cout << divide(a, b);

return 0;
}

Python:
def divide(dividend, divisor):

# Calculate sign of divisor i.e.,


# sign will be negative only iff
# either one of them is negative
# otherwise it will be positive
sign = -1 if ((dividend < 0) ^ (divisor < 0)) else 1

# Update both divisor and


# dividend positive
dividend = abs(dividend)
divisor = abs(divisor)

# Initialize the quotient


quotient = 0
while (dividend >= divisor):
dividend -= divisor
quotient += 1

return sign * quotient

# Driver code
a = 10
b=3
print(divide(a, b))
a = 43
b = -8
print(divide(a, b))

24. What are DDL and DML commands?


Ans: DDL:-CREATE, ALTER, DROP, TRUNCATE AND COMMENT and RENAME, etc. DML:-SELECT,
INSERT, UPDATE, DELETE, MERGE, CALL, etc. Commands which Define the Structures or object are all
DDL . Also DDL commands are auto- commit , they are transaction in themselves.
25. What are transactions in DBMS?
Ans: A transaction is a single logical unit of work which accesses and possibly modifies the contents of a database.
Transactions access data using read and write operations. In order to maintain consistency in a database, before
and after transaction, certain properties are followed.

26. How can we print anything in java other than using SOPL?
Ans:import java.io.*;

public class PrintOutTest {


public static void main(String args[]) throws IOException {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new
FileOutputStream(FileDescriptor.out), "ASCII"), 512);
out.write("test string");
out.write('\n');
out.flush();
}
}
27. What is big data? Explain its applications
Ans: Big data usually includes data sets with sizes beyond the ability of commonly used software tools to
capture, curate, manage, and process data within a tolerable elapsed time. Big data philosophy encompasses
unstructured, semi-structured and structured data, however the main focus is on unstructured data.
Some of the industries propelled by big data analytics are –

Public Sector Services.


Healthcare contributions.
Learning Services.
Insurance Services.
Industrialized and Natural Resources.
Transportation Services.
Banking Sectors and Fraud Detection

28. Explain TCP/IP protocol.


Ans: Transmission Control Protocol/Internet Protocol (TCP/IP) is the language a computer uses to access the
internet. It consists of a suite of protocols designed to establish a network of networks to provide a host with
access to the internet.
Drive Name: BROADCOM
Book Index: 221(D)

Technical interview

Find subsequence in a given array.


Solution:
// C++ program to print distinct subset sums of
// a given array.
#include<bits/stdc++.h>
using namespace std;

// sum denotes the current sum of the subset


// currindex denotes the index we have reached in
// the given array
void distSumRec(int arr[], int n, int sum,
int currindex, unordered_set<int> &s)
{
if (currindex > n)
return;

if (currindex == n)
{
s.insert(sum);
return;
}

distSumRec(arr, n, sum + arr[currindex],


currindex+1, s);
distSumRec(arr, n, sum, currindex+1, s);
}

// This function mainly calls recursive function


// distSumRec() to generate distinct sum subsets.
// And finally prints the generated subsets.
void printDistSum(int arr[], int n)
{
unordered_set<int> s;
distSumRec(arr, n, 0, 0, s);

// Print the result


for (auto i=s.begin(); i!=s.end(); i++)
cout << *i << " ";
}

// Driver code
int main()
{
int arr[] = {2, 3, 4, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
printDistSum(arr, n);
return 0;
}

Write a program for Fibonacci series.


Solution:
/* Fibonacci series program in C language */
#include <stdio.h>

int main()
{
int n, first = 0, second = 1, next, c;

printf("Enter the number of terms\n");


scanf("%d", &n);

printf("First %d terms of Fibonacci series are:\n", n);

for (c = 0; c < n; c++)


{
if (c <= 1)
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n", next);
}

return 0;
}

What are arrays and strings?


Ans: Strings are similar to arrays with just a few differences. Usually, the array size is fixed, while strings can have a
variable number of elements. Arrays can contain any data type (char short int even other arrays) while strings are
usually ASCII characters terminated with a NULL (0) character.

Write a code to reverse a linked list.


Solution:
// Iterative C++ program to reverse
// a linked list
#include<iostream>
using namespace std;

/* Link list node */


struct Node
{
int data;
struct Node* next;
Node (int data)
{
this->data = data;
next = NULL;
}
};

struct LinkedList
{
Node *head;
LinkedList()
{
head = NULL;
}

/* Function to reverse the linked list */


void reverse()
{
// Initialize current, previous and
// next pointers
Node *current = head;
Node *prev = NULL, *next = NULL;

while (current != NULL)


{
// Store next
next = current->next;

// Reverse current node's pointer


current->next = prev;

// Move pointers one position ahead.


prev = current;
current = next;
}
head = prev;
}

/* Function to print linked list */


void print()
{
struct Node *temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}

void push(int data)


{
Node *temp = new Node(data);
temp->next = head;
head = temp;
}
};

/* Driver program to test above function*/


int main()
{
/* Start with the empty list */
LinkedList ll;
ll.push(20);
ll.push(4);
ll.push(15);
ll.push(85);

cout << "Given linked list\n";


ll.print();

ll.reverse();

cout << "\nReversed Linked list \n";


ll.print();
return 0;
}

What is double pointer?


Ans: a pointer points to a location in memory and thus used to store address of variables. So, when we define a
pointer to pointer. The first pointer is used to store the address of second pointer. That is why they are also known as
double pointers.

What is recursion?
Ans: Recursion is a method of solving problems that involves breaking a problem down into smaller and smaller
subproblems until you get to a small enough problem that it can be solved trivially. Usually recursion involves a
function calling itself. While it may not seem like much on the surface, recursion allows us to write elegant solutions
to problems that may otherwise be very difficult to program.
Write a program to find repeated element in array.
Solution:
// C++ program to find the only repeating element in an
// array of size n and elements from range 1 to n-1.
#include <bits/stdc++.h>
using namespace std;

// Returns index of second appearance of a repeating element


// The function assumes that array elements are in range from
// 1 to n-1.
int findRepeatingElement(int arr[], int low, int high)
{
// low = 0 , high = n-1;
if (low > high)
return -1;

int mid = (low + high) / 2;

// Check if the mid element is the repeating one


if (arr[mid] != mid + 1)
{
if (mid > 0 && arr[mid]==arr[mid-1])
return mid;

// If mid element is not at its position that means


// the repeated element is in left
return findRepeatingElement(arr, low, mid-1);
}

// If mid is at proper position then repeated one is in


// right.
return findRepeatingElement(arr, mid+1, high);
}

// Driver code
int main()
{
int arr[] = {1, 2, 3, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int index = findRepeatingElement(arr, 0, n-1);
if (index != -1)
cout << arr[index];
return 0;
}
Write program for a tic-tok game.
Solution:
// A C++ Program to play tic-tac-toe

#include<bits/stdc++.h>
using namespace std;

#define COMPUTER 1
#define HUMAN 2

#define SIDE 3 // Length of the board

// Computer will move with 'O'


// and human with 'X'
#define COMPUTERMOVE 'O'
#define HUMANMOVE 'X'

// A function to show the current board status


void showBoard(char board[][SIDE])
{
printf("\n\n");

printf("\t\t\t %c | %c | %c \n", board[0][0],


board[0][1], board[0][2]);
printf("\t\t\t--------------\n");
printf("\t\t\t %c | %c | %c \n", board[1][0],
board[1][1], board[1][2]);
printf("\t\t\t--------------\n");
printf("\t\t\t %c | %c | %c \n\n", board[2][0],
board[2][1], board[2][2]);

return;
}

// A function to show the instructions


void showInstructions()
{
printf("\t\t\t Tic-Tac-Toe\n\n");
printf("Choose a cell numbered from 1 to 9 as below"
" and play\n\n");

printf("\t\t\t 1 | 2 | 3 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 4 | 5 | 6 \n");
printf("\t\t\t--------------\n");
printf("\t\t\t 7 | 8 | 9 \n\n");

printf("-\t-\t-\t-\t-\t-\t-\t-\t-\t-\n\n");

return;
}
// A function to initialise the game
void initialise(char board[][SIDE], int moves[])
{
// Initiate the random number generator so that
// the same configuration doesn't arises
srand(time(NULL));

// Initially the board is empty


for (int i=0; i<SIDE; i++)
{
for (int j=0; j<SIDE; j++)
board[i][j] = ' ';
}

// Fill the moves with numbers


for (int i=0; i<SIDE*SIDE; i++)
moves[i] = i;

// randomise the moves


random_shuffle(moves, moves + SIDE*SIDE);

return;
}

// A function to declare the winner of the game


void declareWinner(int whoseTurn)
{
if (whoseTurn == COMPUTER)
printf("COMPUTER has won\n");
else
printf("HUMAN has won\n");
return;
}

// A function that returns true if any of the row


// is crossed with the same player's move
bool rowCrossed(char board[][SIDE])
{
for (int i=0; i<SIDE; i++)
{
if (board[i][0] == board[i][1] &&
board[i][1] == board[i][2] &&
board[i][0] != ' ')
return (true);
}
return(false);
}

// A function that returns true if any of the column


// is crossed with the same player's move
bool columnCrossed(char board[][SIDE])
{
for (int i=0; i<SIDE; i++)
{
if (board[0][i] == board[1][i] &&
board[1][i] == board[2][i] &&
board[0][i] != ' ')
return (true);
}
return(false);
}

// A function that returns true if any of the diagonal


// is crossed with the same player's move
bool diagonalCrossed(char board[][SIDE])
{
if (board[0][0] == board[1][1] &&
board[1][1] == board[2][2] &&
board[0][0] != ' ')
return(true);

if (board[0][2] == board[1][1] &&


board[1][1] == board[2][0] &&
board[0][2] != ' ')
return(true);

return(false);
}

// A function that returns true if the game is over


// else it returns a false
bool gameOver(char board[][SIDE])
{
return(rowCrossed(board) || columnCrossed(board)
|| diagonalCrossed(board) );
}

// A function to play Tic-Tac-Toe


void playTicTacToe(int whoseTurn)
{
// A 3*3 Tic-Tac-Toe board for playing
char board[SIDE][SIDE];

int moves[SIDE*SIDE];

// Initialise the game


initialise(board, moves);

// Show the instructions before playing


showInstructions();

int moveIndex = 0, x, y;
// Keep playing till the game is over or it is a draw
while (gameOver(board) == false &&
moveIndex != SIDE*SIDE)
{
if (whoseTurn == COMPUTER)
{
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = COMPUTERMOVE;
printf("COMPUTER has put a %c in cell %d\n",
COMPUTERMOVE, moves[moveIndex]+1);
showBoard(board);
moveIndex ++;
whoseTurn = HUMAN;
}

else if (whoseTurn == HUMAN)


{
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = HUMANMOVE;
printf ("HUMAN has put a %c in cell %d\n",
HUMANMOVE, moves[moveIndex]+1);
showBoard(board);
moveIndex ++;
whoseTurn = COMPUTER;
}
}

// If the game has drawn


if (gameOver(board) == false &&
moveIndex == SIDE * SIDE)
printf("It's a draw\n");
else
{
// Toggling the user to declare the actual
// winner
if (whoseTurn == COMPUTER)
whoseTurn = HUMAN;
else if (whoseTurn == HUMAN)
whoseTurn = COMPUTER;

// Declare the winner


declareWinner(whoseTurn);
}
return;
}

// Driver program
int main()
{
// Let us play the game with COMPUTER starting first
playTicTacToe(COMPUTER);

return (0);
}

What is DML compiler?


Ans: A data manipulation language (DML) is a family of syntax elements similar to a computer programming
language used for selecting, inserting, deleting and updating data in a database. Performing read-only queries of data
is sometimes also considered a component of DML.
A popular data manipulation language is that of Structured Query Language (SQL), which is used to retrieve and
manipulate data in a relational database.[1] Other forms of DML are those used by IMS/DLI, CODASYL databases,
such as IDMS and others.
Drive Name: EVALUESERVE
Book Index: 223(D)
TECHNICAL INTERVIEW

1. What is Multiplexing?
Ans: Multiplexing is a technique by which different analog and digital streams of transmission can be simultaneously
processed over a shared link. Multiplexing divides the high capacity medium into low capacity logical medium
which is then shared by different streams.

 Frequency Division Multiplexing


 Time Division Multiplexing
 Wavelength Division Multiplexing
 Code Division Multiplexing

2. What is GSM,

Ans: GSM stands for Global System for Mobile Communication. It is a digital cellular technology used for
transmitting mobile voice and data services. GSM makes use of narrowband Time Division Multiple Access
(TDMA) technique for transmitting signals. GSM digitizes and compresses data, then sends it down through a
channel with two other streams of user data, each in its own timeslot.
2. What are Handover techniques?
Ans: Handover in mobile communication refers to the process of transferring a call from one network cell to another
without breaking the call.
There are two types of handover which are as follows :
Hard Handoff : hard handoff is the process in which the cell connection is disconnected from the previous cell before
it is made with the new one.
Soft Handoff : It is the process in which a new connection is established first before disconnecting the old one. It is
thus more efficient and smart.

3. What are the types of antennas?


Ans: There are several different types of antennas in three broad categories: omni-directional, directional, and semi-
directional.

 Omni-directional antennas propagate in all directions.


 Semi-directional antennas propagate in a constricted fashion, defined by a specific angle.
 Directional antennas have a narrow “beam” that allows highly directional propagation; familiar types are the
parabolic and Yagi. Each has unique characteristics and applications.

4. What is TDMA?
Ans: Time-division multiple access (TDMA) is a channel access method for shared-medium networks. It allows
several users to share the same frequency channel by dividing the signal into different time slots. The users transmit
in rapid succession, one after the other, each using its own time slot.

5. What is FDMA?
Ans: In FDMA, The frequency band is divided into channels of equal bandwidth so that each conversation is carried
on a different frequency
6. What is half duplex and full duplex communication?
Ans: Half Duplex: In half duplex mode, data can be transmitted in both directions on a signal carrier except not at
the same time. At a certain point, it is actually a simplex channel whose transmission direction can be switched.
Walkie-talkie is a typical half duplex device.
Full Duplex: A full duplex communication channel is able to transmit data in both directions on a signal carrier at the
same time. Take telephone as an example, people at both ends of a call can speak and be heard by each other at the
same time because there are two communication paths between them. Thus, using the full duplex mode can greatly
increase the efficiency of communication.

7. What are Wireless Networks?


Ans: Wireless networks are computer networks that are not connected by cables of any kind. The use of a wireless
network enables enterprises to avoid the costly process of introducing cables into buildings or as a connection
between different equipment locations. The basis of wireless systems are radio waves, an implementation that takes
place at the physical level of network structure.

8. What is a deadlock?
Ans: In a database, a deadlock is an unwanted situation in which two or more transactions are waiting indefinitely for
one another to give up locks. Deadlock is said to be one of the most feared complications in DBMS as it brings the
whole system to a Halt.

9. Differentiate between RDBMS and DBMS.


Ans:

DBMS RDBMS
DBMS applications store data as file. RDBMS applications store data in a tabular form.
In DBMS, data is generally stored in either a In RDBMS, the tables have an identifier called
hierarchical form or a navigational form. primary key and the data values are stored in the
form of tables.
Normalization is not present in DBMS. Normalization is present in RDBMS.
DBMS does not apply any security with regards to RDBMS defines the integrity constraint for the
data manipulation. purpose of ACID (Atomocity, Consistency,
Isolation and Durability) property

10. Explain the types of scheduling in OS.


Ans: scheduling is very important in multiprogramming and multitasking operating system, where multiple processes
execute simultaneously.
1.First come first serve (FCFS)
In this scheduling algorithm the first process entered in queue is processed first.

2.Shortest job first (SJF)


In this scheduling algorithm the process which requires shortest CPU time to execute is processed first.

3.Priority scheduling
In this scheduling algorithm the priority is assigned to all the processes and the process with highest priority
executed first. Priority assignment of processes is done on the basis of internal factor such as CPU and memory
requirements or external factor such as user’s choice. The priority scheduling algorithm supports preemptive and non
- preemptive scheduling policy.

4.Round Robin (RR) scheduling


In this algorithm the process is allocated the CPU for the specific time period called time slice, which is normally of
10 to 100 milliseconds. If the process completes its execution within this time slice, then it is removed from the
queue otherwise it has to wait for another time slice.

11. Explain TCP/IP layers.


Ans: 1. Network Access Layer
This layer corresponds to the combination of Data Link Layer and Physical Layer of the OSI model. It looks out for
hardware addressing and the protocols present in this layer allows for the physical transmission of data.
2. Internet Layer
This layer parallels the functions of OSI’s Network layer. It defines the protocols which are responsible for logical
transmission of data over the entire network.
3. Host-to-Host Layer
This layer is analogous to the transport layer of the OSI model. It is responsible for end-to-end communication and
error-free delivery of data.
4. Process Layer
This layer performs the functions of top three layers of the OSI model: Application, Presentation and Session Layer.
It is responsible for node-to-node communication and controls user-interface specifications. Some of the protocols
present in this layer are: HTTP, HTTPS, FTP, TFTP, Telnet, SSH, SMTP, SNMP, NTP, DNS, DHCP, NFS

12. Talk about patents if you have filed any.


13. What are super classes?
Ans: In object-oriented programming, inheritance enables new objects to take on the properties of existing objects. A
class that is used as the basis for inheritance is called a superclass or base class. A class that inherits from a
superclass is called a subclass or derived class.

14. Differentiate between structures and classes.


Ans: 1. Members of a class are private by default and members of struct are public by default.
2. When deriving a struct from a class/struct, default access-specifier for a base class/struct is public. And when
deriving a class, default access specifier is private.
3. Classes are an expanded concept of structure like data structures, they can contain data members, but they can
also contain functions as members.

15. What is IP address and ports?


Ans: IP address is address of the system in the Network.
Port is address of the service within the System.
So IP address + Port defines address of the particular service on the particular system.
16. What is packet-switching?
Ans: Packet switching is a method of transferring the data to a network in form of packets. In order to transfer the
file fast and efficient manner over the network and minimize the transmission latency, the data is broken into small
pieces of variable length, called Packet. At the destination, all these small-parts (packets) has to be reassembled,
belonging to the same file. A packet composes of payload and various control information. No pre-setup or
reservation of resources is needed.

17. What is networking?


Ans: A network consists of two or more computers that are linked in order to share resources (such as printers and
CDs), exchange files, or allow electronic communications. The computers on a network may be linked through
cables, telephone lines, radio waves, satellites.

18. Talk about different operating systems.


Ans: 1. Microsoft Windows
Microsoft Windows has existed in one form or another since 1985, and it remains the most popular operating system
for home and office computers. Its latest versions, including Windows 10, are also used on some tablets, and the OS
is used on some web and number-crunching server computers as well. Computers from a wide variety of
manufacturers can use Windows.
2. Linux:
The Linux open source operating system, or Linux OS, is a freely distributable, cross-platform operating system
based on Unix that can be installed on PCs, laptops, netbooks, mobile and tablet devices, video game consoles,
servers, supercomputers and more. The Linux OS is frequently packaged as a Linux distribution for both desktop and
server use, and includes the Linux kernel (the core of the operating system) as well as supporting tools and libraries.
Popular Linux OS distributions include Debian, Ubuntu, Fedora, Red Hat and openSUSE.
3. Apple iOS
Apple's iOS is one of the most popular smartphone operating systems, second only to Android. It runs on Apple
hardware, including iPhones, iPad tablets and iPod Touch media players
4. Apple macOS
Apple's macOS, successor to the popular OS X operating system, runs on Apple laptops and desktops. Based in part
on the historic family of Unix operating systems dating back to research in the 1960s at AT&T's Bell Labs, macOS
shares some features with other Unix-related operating systems including Linux. While the graphical interfaces are
different, many of the underlying programming interfaces and command line features are the same.

19. What is polymorphism?


Ans: Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in
OOP occurs when a parent class reference is used to refer to a child class object.
Drive Name: Sapient
Book Index: 226(D)

1. Tell me about your project.


Ans: Student Dependent
2. Design some test cases for your project.
Ans: Based on student’s project
3. What are the quality checks you do in your project?
Ans: Based on student’s project
4. What verification and validation checks you have done in your project?
Ans: Based on student’s project
5. How you have applied Unit testing , system and integration testing on your project
Ans: Based on student’s project

6. What is Bootstrap?
Bootstrap is a free and open-source front-end framework for designing websites and web applications. It
contains HTML- and CSS-based design templates for typography, forms, buttons, navigation and other
interface components, as well as optional JavaScript extensions.

7. From a Table, How will you print two distinct elements?

void printDistinct(int arr[], int n)


{
// Pick all elements one by one
for (int i=0; i<n; i++)
{
// Check if the picked element is already printed
int j;
for (j=0; j<i; j++)
if (arr[i] == arr[j])
break;

// If not printed earlier, then print it


if (i == j)
cout << arr[i] << " ";
}
}

8. What is Normalization (SQL)?

Normalization is the process of reorganizing data in a database so that it meets two basic requirements: (1) There is
no redundancy of data (all data is stored in only one place), and (2) data dependencies are logical (all related data
items are stored together). Normalization is important for many reasons, but chiefly because it allows databases to
take up as little disk space as possible, resulting in increased performance. Normalization is also known as data
normalization.
9. About .NET and Its Input Output Operations?
Output functions:

Write()
writeLine(): create new line automatically

Input Functions:
read()
readLine():Reads the whole linea

10. What are IIS and JSP Servalets in Java?

Java Server Page (JSP) is a technology for controlling the content or appearance of Web pages through the use
of servlets, small programs that are specified in the Web page and run on the Web server to modify the Web page
before it is sent to the user who requested it. Sun Microsystems, the developer of Java, also refers to the JSP
technology as the Servlet application program interface (API). JSP is comparable to Microsoft's Active Server Page
(ASP) technology. Whereas a Java Server Page calls a Java program that is executed by the Web server, an Active
Server Page contains a script that is interpreted by a script interpreter (such as VBScript or JScript) before the page is
sent to the user.

IIS, or more specifically its Active Server Page (ASP) environment, contains a core group of classes that
virtually mirror those of the Java Servlet specification. ... You have to adapt (or wrap) the IIS versions of the
objects to make them look and act like servlet versions.

A servlet is a Java programming language class that is used to extend the capabilities of servers that host
applications accessed by means of a request-response programming model. Although servletscan respond to
any type of request, they are commonly used to extend the applications hosted by web servers.

11. What is the syntax for Java Class?

public class Dog {


String breed;
int age;
String color;

void barking() {
}

void hungry() {
}
void sleeping() {
}
}

12. What is Access Specifies?

An access specifier is a defining code element that can determine which elements of a program are allowed to access
a specific variable or other piece of data. Different programming languages have their own protocols for access
specifiers, as well as defaults for some code elements including both individual variables and classes.they are of 3
types:

4. Public: access allowed

5. Private:access not allowed outside the class

6. Protected:can access in inheritance.

13. What Is Default Scope?

Private in c++ and in java also.

14. What is the query of inner Joins ,Outer Join, Constant, Unique Key, Primary key, Inheritance ,Programs
Related to Linked List , In capsulation , Abstraction (there real Life Examples )

INNER JOIN: The INNER JOIN keyword selects all rows from both the tables as long as the condition
satisfies. This keyword will create the result-set by combining all rows from both the tables where the
condition satisfies i.e value of the common field will be same.
Syntax

SELECT table1.column1,table1.column2,table2.column1,....

FROM table1

INNER JOIN table2

ON table1.matching_column = table2.matching_column;

This query will show the names and age of students enrolled in different courses.

SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student

INNER JOIN StudentCourse

ON Student.ROLL_NO = StudentCourse.ROLL_NO;

OUTER JOIN
when performing an inner join, rows from either table that are unmatched in the other table are not returned. In an
outer join, unmatched rows in one or both tables can be returned. There are a few types of outer joins:

 LEFT JOIN returns only unmatched rows from the left table.
 RIGHT JOIN returns only unmatched rows from the right table.
 FULL OUTER JOIN returns unmatched rows from both tables.

Example of Left Outer Join:

SELECT companies.permalink AS companies_permalink,


companies.name AS companies_name,
acquisitions.company_permalink AS acquisitions_permalink,
acquisitions.acquired_at AS acquired_date
FROM tutorial.crunchbase_companies companies
LEFT JOIN tutorial.crunchbase_acquisitions acquisitions
ON companies.permalink = acquisitions.company_permalink

UNIQUE KEY
All tables in your databse should have a PK (although this is not enforced by most dbms), and PK can span
multiple columns. Unique key constraints are used to ensure that data is not duplicated in two rows in the
database. One row in the database is allowed to have null for the value of the unique key constraint

PRIMARY KEY

A primary key is a special relational database table column (or combination of columns) designated to
uniquely identify all table records. A primary key'smain features are: It must contain a unique value for each
row of data. It cannot contain null values.

15. What is SQ Lite?

SQLite is an embedded SQL database engine. Unlike most other SQL databases, SQLite does not have a separate
server process. SQLite reads and writes directly to ordinary disk files. A complete SQL database with multiple
tables, indices, triggers, and views, is contained in a single disk file. The database file format is cross-platform - you
can freely copy a database between 32-bit and 64-bit systems or between big-endian and little-endian architectures.
These features make SQLite a popular choice as an Application File Format. SQLite database files are
a recommended storage format by the US Library of Congress. Think of SQLite not as a replacement for Oracle but
as a replacement for fopen()

SQLite is a compact library. With all features enabled, the library size can be less than 600KiB, depending on the
target platform and compiler optimization settings. (64-bit code is larger. And some compiler optimizations such as
aggressive function inlining and loop unrolling can cause the object code to be much larger.) There is a tradeoff
between memory usage and speed. SQLite generally runs faster the more memory you give it. Nevertheless,
performance is usually quite good even in low-memory environments. Depending on how it is used, SQLite can
be faster than direct filesystem I/O.

SQLite is very carefully tested prior to every release and has a reputation for being very reliable. Most of the SQLite
source code is devoted purely to testing and verification. An automated test suite runs millions and millions of test
cases involving hundreds of millions of individual SQL statements and achieves 100% branch test coverage. SQLite
responds gracefully to memory allocation failures and disk I/O errors. Transactions are ACID even if interrupted by
system crashes or power failures. All of this is verified by the automated tests using special test harnesses which
simulate system failures. Of course, even with all this testing, there are still bugs. But unlike some similar projects
(especially commercial competitors) SQLite is open and honest about all bugs and provides bugs lists and minute-
by-minute chronologies of code changes.

The SQLite code base is supported by an international team of developers who work on SQLite full-time. The
developers continue to expand the capabilities of SQLite and enhance its reliability and performance while
maintaining backwards compatibility with the published interface spec, SQL syntax, and database file format. The
source code is absolutely free to anybody who wants it, but professional support is also available.

16. Database Query: Takeout a name from the table given?

Answer: Select name from the student where rollno=1;

Student is “TableName”
Name is the “ColumnName representing names of the student’
Rollno is the “ColumnName”

17. What are the real life examples of Stack and Queue?

Stack: Pile of dinner plates


Queue: Movie ticket window

18. What are DDL and DML?

DML statements are SQL statements that manipulate data. DML stands for Data Manipulation Language. The SQL
statements that are in the DML class are INSERT, UPDATE and DELETE. Some people also lump the SELECT
statement in the DML classification.

Data Definition Languages (DDL) are used to define the database structure. Any CREATE, DROP and ALTER
commands are examples of DDL SQL statements

19. Difference between SQ Lite and My SQL?

Sqlite is embeddable relational database management system. SQL is query language. ... Unlike other
databases (like SQL Server and MySQL) SQLite does not support stored procedures. SQLite is file-based,
unlike other databases, like SQL Server and MySQL which are server-based.
20. Where SQL is used? Give Real Life examples?

Data is stored in databases which in turn stores the data in tables that contains rows and columns. There are
several database applications available to handle the storage and management of data examples include Oracle,
Microsoft SQL and MySQL. ... Adding new record into a database. Deleting records from a database.e.g
Hospital records of patients and doctors.

21. Difference between KOTLIN and Java?

 Null Safety - As already mentioned in above section that Kotlin avoids NullPointerException. Kotlin fails at
compile-time whenever a NullPointerException may be thrown.

 Data Classes - In Kotlin there are Data Classes which leads to autogeneration of boilerplate like equals,
hashCode, toString, getters/setters and much more.

Extension Functions - Kotlin allows us to extend the functionality of existing classes without inheriting from
them. Means to say that Kotlin provides the ability to extend a class with new functionality without having to
inherit from the class. This is done by extension functions. To declare an extension function, we need to
prefix its name with a receiver type, i.e. the type being extended.

22. Have you heard about GO Language?

For the language released in 2003 by McCabe and Clark, see Go! (programming language).
"Google Go" redirects here. For the computer program by Google to play the board game Go, see AlphaGo.
Go (often referred to as Golang[12]) is a programming language designed by Google[13] engineers Robert
Griesemer, Rob Pike, and Ken Thompson.[10] Go is a statically typed, compiled language in the tradition of C, with
the added benefits of memory safety, garbage collection, structural typing,[3] and CSP-style concurrency.
[14]
The compiler, tools, and source code are all free and open source.[15]

23. Write a program of Fibonannci Series?

int main()
{
int i, n, t1 = 0, t2 = 1, nextTerm;

printf("Enter the number of terms: ");


scanf("%d", &n);

printf("Fibonacci Series: ");

for (i = 1; i <= n; ++i)


{
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}

24. What are main concepts of OOPS?

Objects:

Objects are the basic run-time entities in an object-oriented programming. They may represents a person, a place, a
bank account, a table of data or any item that the program has to handle. They may also represents user-defined data
such as vector, time and lists. When the program is executed, the object interact by sending message to one another.

Classes:

Objects contain data, and code to manipulate that data. The entire set of data and code of an object can be made a
user-defined data type with the help of class. In fact, objects are variable of the type class. Once a class has been
defined, we can create a number of objects belonging to that class. A class is a collection of objects of similar type.

Ex. Fruit mango;

Data Abstraction:

Abstractions refer to the act of representing essential features without including background details or explanation.
They are commonly known as Abstraction Data Type(ADT).

Encapsulation:

The wrapping up of data and functions into single unit is known as encapsulation. Data encapsulation is a striking
feature of a class. The data is not accessible to the outside world, and only those functions which are wrapped in the
class can access it. These functions provide the interface between the object's data and the program.

Inheritance:

Inheritance is the process by which objects of one class acquire the properties of object of another class. The class
whose members are inherited is called the Base class and the class that inherits those members is called Derived
class. It supports class of hierarchical classification.

The concept of inheritance provides the ideas of reusability. This means we can add essential features to an exciting
class without modifying it.

Polymorphism:

Polymorphism is another OOP concept. Polymorphism means the ability to take more than one form. An operation
may exhibit different behaviors at different instances.

25. There is a Bridge in .NET And Database, What it is called?


This interface acts as a bridge between an RDBMS system and a .Net application. ADO.NET is such an
interface that is created to connect .NET applications toRDBMS systems. In the .NET framework, Microsoft
introduced a new version of Active X Data Objects (ADO) called ADO.NET. ... ADO reduces the number of
objects.
26. What is static Queue?
A static queue is one that is defined ahead of time and the queue definition persists in the environment. A
dynamic queue is created on demand. ... A temporary dynamic queue is created on demand and is deleted
when the program that created it disconnects.

27. What is Project Architecture? What kind of Database you have used? Write its Database.

Ans: Ans: Project Architecure means what are the tiers in our project with flow diagram.
supposoe our project contains five tiers like client tier ,presentation tier, Business tier,Integration tier,Data tier. then
we draw the all tiers flow. Project approch is different from project architecure.

Client tier:
IE Browser (default) from which the end user will access the application
The request from the browser will be submitted to the Application Server using HTTP protocol.
The Response from the presentation layer (struts framework) will be interpreted into html pages to view on the
browsers.

Presentation Tier:
Struts Framework with Tiles
On Request from the browser, the appropriate Action Class handles the user request. The Action class then connects
to the business tier via Service Business Delegate.
Tiles have been used to create a set of pages with a consistent user interface (e.g.: the same navigation bar, header,
footer, etc.).
Taglibs are used for displaying tabular data (e.g. search results) in a consistent fashion, with pagination.

Business Delegate layer


Enable the Struts Action classes to be unaware of underlying Session Beans
Encapsulates the invocation of Service Locator to locate them.

Business Tier
The Business Delegate identifies the business service class (the Session EJBs) and delegates client request to the
EJBs. Internally, the session beans are shallow, and delegate all business logic requests to business logic POJOs,
which in turn implement the actual functionality.
The Business Logic POJOs encapsulate the server side business logic. They do not use Hibernate directly, but
instead call upon Data Access Objects (DAO) to work with the model. Parameters and return values are modeled as
Data Transfer Objects (DTO), and hence no Hibernate model classes will ever leave the DAO layer. The business
logic is made available in the business service class, which increases maintainability and easy debugging, if
necessary.

DB Tier
The DAOs encapsulates the database access. For all practical purposes, we are using Hibernate (v 2.1) as the OR
mapping layer. This saves development time to write SQLs for executing insert and update statements, find by
primary key etc. For each value object that directly or compositely represent a table in the database, we have
Hibernate mapping files.
For some complex data retrieval, however we will be using raw SQLs (independent of database) from the DAOs and
populate the Value Object POJOs. In those specific cases, the DAOs will be having direct access to the Databases
using the available connection. The connection properties of the ?DB Manager?, holding the data sources, direct the
request to the appropriate database.
28. What is Cloud Computing? What are its platforms? What are its advantages? What are its
disadvantages? Why it was started? What are its Modules?

Ans: Cloud computing is the the use of various services, such as software development platforms, servers, storage
and software, over the internet, often referred to as the "cloud."
In general, there are three cloud computing characteristics that are common among all cloud-computing vendors:

4. The back-end of the application (especially hardware) is completely managed by a cloud vendor.
5. A user only pays for services used (memory, processing time and bandwidth, etc.).
6. Services are scalable

Many cloud computing advancements are closely related to virtualization. The ability to pay on demand and scale
quickly is largely a result of cloud computing vendors being able to pool resources that may be divided among
multiple clients.
It is common to categorize cloud computing services as infrastructure as a service (IaaS), platform as a service
(PaaS) or software as a service (SaaS).

Cloud Computing advantages


Cloud computing is an emerging technology that almost every company switched to from on-premise technologies.
Whether it is public, private or hybrid, Cloud computing has become an essential factor for the companies to achieve
competitive. Let us find out why Cloud is so much preferred over on-premise technologies-

 Cost efficiency – The biggest reason behind shifting to cloud computing is that it takes considerably lesser
cost than an on-premise technology. Now the companies need not store the data in disks anymore as the Cloud
offers enormous space available saving money and resources of the companies.

 High Speed – Cloud computing lets you deploy the service quickly in fewer clicks. This quick deployment
lets you get the resources required for your system within fewer minutes.

 Excellent accessibility – Storing the information in cloud allows you to access it anywhere, anytime
regardless of the machine making it highly accessible and flexible technology of present times.

 Back-up and restore data – Once the data is stored in Cloud, it is easier to get the back-up and recovery of
that, which is quite a time taking process on-premise.

Cloud Computing disadvantages


Every technology has positive and negatives aspects that are highly important to discuss before implementing it.
Aforementioned points highlight the benefits of using cloud technology and following discussion will outline the
potential cons of Cloud Computing-

 Security issues – At time storing data in cloud may pose serious challenge of information theft in front of
the company. Though advanced security measures are deployed on cloud, still storing a confidential data in cloud
can be a risky affair.
 Low bandwidth – At times the bandwidth is low as many users are accessing cloud at the same time which
causes its bandwidth to go down. With less speed the benefits of cloud computing cannot be realized.

 Flexibility issues – The cloud services run on remote servers which make it hard for the companies to have
control over software and hardware. The services at times do not run the way it should.

 Incompatibility – Since entire infrastructure gets virtualized, incompatibility issues may arise at times that
may pose serious challenges on the way of smooth running of services.

29. Why Is Cloud Computing Preferable?


Ans: Kindly follow the advantages of Cloud Computing.

30. If there is a String A, B, C, D, E .Without affecting its elements, how will you reverse it?
Ans: Simple Solution:
1) Create a temporary character array say temp[].
2) Copy alphabetic characters from given array to temp[].
3) Reverse temp[] using standard string reversal algorithm.
4) Now traverse input string and temp in a single loop. Wherever there is alphabetic character is input string,
replace it with current character of temp[].

Efficient Solution:
Time complexity of above solution is O(n), but it requires extra space and it does two traversals of input string.
We can reverse with one traversal and without extra space. Below is algorithm.

1) Let input string be 'str[]' and length of string be 'n'


2) l = 0, r = n-1
3) While l is smaller than r, do following
a) If str[l] is not an alphabetic character, do l++
b) Else If str[r] is not an alphabetic character, do r--
c) Else swap str[l] and str[r]

31. What is the difference between Stored Procedure and Function?


Ans:

Stored Procedure Functions


1.Can have both input / output parameters 1.Can have only input parameters
2. Stored procedure can’t call from the functions 2.Functions can call from the stored procedures
3.It’s optional to return the value, as somestimes it returns 0 or
3.It’s should return the value
n values
4. It allows insert/update/delete/select 4.It allows only select statement
5.Procedures cant be utilized in a select statement 5.Function is embedded in a select statement
6.Procedure cannot be used in SQL statements with WHERE/ 6.SQL statements can be used with
HAVING/SELECT WHERE/HAVING/SELECT
7.Here, we can’t handle the exception, using try-
7. Exception can be handled by try-catch block
catch block

32. What do you know about Data Structure?


Ans: Data structure refers to methods of organizing units of data within larger data sets. Achieving and
maintaining specific data structures help improve data access and value. Data structures also help programmers
implement various programming tasks.

33. What is the working of Max Function?

Ans: The max() function of PHP is used to find the numerically maximum value in an array or the numerically
maximum value of several specified values. The max() function can take an array or several numbers as an argument
and return the numerically maximum value among the passed parameters. The return type is not fixed, it can be an
integer value or a float value based on input.
Syntax:
max(array_values)

or

max(value1, value2, ...)

Parameters: This function accepts two different types of arguments which are explained below:
3. array_values : It specifies an array containing the values.
4. value1, value2, … : It specifies two or more than two values to be compared.
Return Value: The max() function returns the numerically maximum value.
Drive Name: Brilio Technologies
Book Index: 233 (D)

Technical Interview

1. Define DBMS.

Ans: A database management system (DBMS) is system software for creating and managing databases. The DBMS
provides users and programmers with a systematic way to create, retrieve, update and manage data.

A DBMS makes it possible for end users to create, read, update and delete data in a database. The DBMS essentially
serves as an interface between the database and end users or application programs, ensuring that data is consistently
organized and remains easily accessible.

2. What is SQL?
Ans: SQL stands for Structured Query Language. SQL lets you access and manipulate databases. SQL became a
standard of the American National Standards Institute (ANSI) in 1986, and of the International Organization for
Standardization (ISO) in 1987. SQL can execute queries against a database. SQL can retrieve data from a
database. SQL can insert records in a database. SQL can update records in a database. SQL can delete records
from a database. SQL can create new databases. SQL can create new tables in a database, SQL can create stored
procedures in a database. SQL can create views in a database. SQL can set permissions on tables, procedures,
and views

3. Define Data Structure.


Ans: A data structure is a specialized format for organizing and storing data. General data structure types
include the array, the file, the record, the table, the tree, and so on. Any data structure is designed to organize
data to suit a specific purpose so that it can be accessed and worked with in appropriate ways. In computer
programming, a data structure may be selected or designed to store data for the purpose of working on it with
various algorithms.
4. What is OS?
Ans: An operating system or OS is software installed on a computer's the hard drive that enables computer
hardware to communicate with and run computer programs. Without an operating system, a computer and
software would be useless. The picture to the right is an example of Microsoft Windows XP, a popular operating
system.
5. What is Inheritance diagram?
Ans: In object-oriented programming, inheritance is the mechanism of basing an object or class upon another
object (prototype-based inheritance) or class (class-based inheritance), retaining similar implementation. Also
defined as deriving new classes (sub classes) from existing ones (super class or base class) and forming them
into a hierarchy of classes. In most class-based object-oriented languages, an object created through inheritance
(a "child object") acquires all the properties and behaviors of the parent object (except: constructors, destructor,
overloaded operators and friend functions of the base class). Inheritance allows programmers to create classes
that are built upon existing classes, [1] to specify a new implementation while maintaining the same behaviors
(realizing an interface), to reuse code and to independently extend original software via public classes and
interfaces. The relationships of objects or classes through inheritance give rise to a directed graph.
Drive Name: Orange Business Service
Book Index: 234 (D)
Technical Interview

1. What is Hash Map?


Ans: HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of Map
interface of Java. It stores the data in (Key, Value) pairs. To access a value one must know its key. HashMap is
known as HashMap because it uses a technique called Hashing. Hashing is a technique of converting a large
String to small String that represents same String. A shorter value helps in indexing and faster searches. HashSet
also uses HashMap internally. It internally uses a link list to store key-value pairs already explained
in HashSet in detail and further articles.

2. What do you understand by Tree in data structure?

Ans: There are many basic data structures that can be used to solve application problems. Array is a good static data
structure that can be accessed randomly and is fairly easy to implement. Linked Lists on the other hand is dynamic
and is ideal for application that requires frequent operations such as add, delete, and update. One drawback of linked
list is that data access is sequential. Then there are other specialized data structures like, stacks and queues that
allows us to solve complicated problems (eg: Maze traversal) using these restricted data structures. One other data
structure is the hash table that allows users to program applications that require frequent search and updates. They
can be done in O(1) in a hash table.

One of the disadvantages of using an array or linked list to store data is the time necessary to search for an item.
Since both the arrays and Linked Lists are linear structures the time required to search a “linear” list is proportional
to the size of the data set. For example, if the size of the data set is n, then the number of comparisons needed to find
(or not find) an item may be as bad as some multiple of n. So imagine doing the search on a linked list (or array) with
n = 106 nodes. Even on a machine that can do million comparisons per second, searching for m items will take
roughly m seconds. This not acceptable in today’s world where speed at which we complete operations is extremely
important. Time is money. Therefore it seems that better (more efficient) data structures are needed to store and
search data.

3. What is the difference between Overloading and overriding?

Ans: There are many differences between method overloading and method overriding in java. A list of differences between
method overloading and method overriding are given below:

No Method Overloading Method Overriding


.

1) Method overloading is used to increase the Method overriding is used to


readability of the program. provide the specific
implementation of the method
that is already provided by its
super class.
2) Method overloading is performed within class. Method overriding occurs in two
classesthat have IS-A (inheritance)
relationship.

3) In case of method overloading, parameter In case of method overriding,


must be different. parameter must be same.

4) Method overloading is the example of compile Method overriding is the example


time polymorphism. of run time polymorphism.

5) In java, method overloading can't be Return type must be same or


performed by changing return type of the covariant in method overriding.
method only. Return type can be same or
different in method overloading. But you must
have to change the parameter.

4. What is the difference between DDL and DML?


Ans:

5. Linked List and Array


Ans: The major difference between Array and Linked list regards to their structure. Arrays are index based data
structure where each element associated with an index. On the other hand, Linked list relies on references where each
node consists of the data and the references to the previous and next element.

Basically, an array is a set of similar data objects stored in sequential memory locations under a common heading or
a variable name.

While a linked list is a data structure which contains a sequence of the elements where each element is linked to its
next element. There are two fields in an element of linked list. One is Data field, and other is link field, Data field
contains the actual value to be stored and processed. Furthermore, the link field holds the address of the next data
item in the linked list. The address used to access a particular node is known as a pointer.

Another significant difference between an array and linked list is that Array has a fixed size and required to be
declared prior, but Linked List is not restricted to size and expand and contract during execution.

6. What is LAN and WAN?


Ans:

LAN versus WAN comparison chart

LAN WAN
Stands For Local Area Network Wide Area Network

Covers Local areas only (e.g., homes, offices, Large geographic areas (e.g.,
schools) cities, states, nations)

Definition LAN (Local Area Network) is a WAN (Wide Area Network)


computer network covering a small is a computer network that
geographic area, like a home, office, covers a broad area (e.g., any
school, or group of buildings. network whose
communications links cross
metropolitan, regional, or
national boundaries over a
long distance).

Speed High speed (1000 mbps) Less speed (150 mbps)

Data transfer LANs have a high data transfer rate. WANs have a lower data
rates transfer rate compared to
LANs.

Example The network in an office building can be The Internet is a good


a LAN example of a WAN

Technology Tend to use certain connectivity WANs tend to use


technologies, primarily Ethernetand technologies like MPLS,
Token Ring ATM, Frame Relay and X.25
for connectivity over longer
distances
LAN versus WAN comparison chart

LAN WAN

Connection One LAN can be connected to other Computers connected to a


LANs over any distance via telephone wide-area network are often
lines and radio waves. connected through public
networks, such as the
telephone system. They can
also be connected through
leased lines or satellites.

Components Layer 2 devices like switches and Layers 3 devices Routers,


bridges. Layer 1 devices like hubs and Multi-layer Switches and
repeaters. Technology specific devices
like ATM or Frame-relay
Switches etc.

Fault LANs tend to have fewer problems WANs tend to be less fault
Tolerance associated with them, as there are smaller tolerant as they consist of
number of systems to deal with. large number of systems.

Data Experiences fewer data transmission Experiences more data


Transmissio errors transmission errors as
n Error compared to LAN

Ownership Typically owned, controlled, and WANs (like the Internet) are
managed by a single person or not owned by any one
organization. organization but rather exist
under collective or distributed
ownership and management
over long distances.

Set-up costs If there is a need to set-up a couple of For WANs since networks in
extra devices on the network, it is not remote areas have to be
very expensive to do that. connected the set-up costs are
higher. However WANs
using public networks can be
setup very cheaply using just
software (VPN etc).

Geographica Have a small geographical range and do Have a large geographical


l Spread not need any leased telecommunication range generally spreading
lines across boundaries and need
leased telecommunication
lines

Maintenance Because it covers a relatively small Maintaining WAN is difficult


costs geographical area, LAN is easier to because of its wider
LAN versus WAN comparison chart

LAN WAN

maintain at relatively low costs. geographical coverage and


higher maintenance costs.

Bandwidth High bandwidth is available for Low bandwidth is available


transmission. for transmission.

Congestion Less congestion More congestion

7. What is Networking?

Ans: A network is defined as a group of two or more computer systemslinked together. There are many types
of computer networks, including the following:
 local-area networks (LANs): The computers are geographically close together (that is, in the same
building).
 wide-area networks (WANs): The computers are farther apart and are connected by telephone lines or radio
waves.
 campus-area networks (CANs): The computers are within a limited geographic area, such as a campus or
military base.
 metropolitan-area networks MANs): A data network designed for a town or city.
 home-area networks (HANs): A network contained within a user's home that connects a person's digital
devices.
Network Characteristics
In addition to these types, the following characteristics are also used to categorize different types of networks:
 topology : The geometric arrangement of a computer system. Common topologies include a bus, star, and
ring. See the Network topology diagrams in the Quick Reference section of Webopedia.
 protocol : The protocol defines a common set of rules and signals that computers on the network use to
communicate. One of the most popular protocols for LANs is called Ethernet. Another popular LAN
protocol for PCs is the IBM token-ring network .
 architecture : Networks can be broadly classified as using either a peer-to-peer or client/server
architecture.
Computers on a network are sometimes called nodes. Computers and devices that allocate resources for a network
are called servers.

8. Difference between Private and Public IP?


Ans: A public IP address is the address that is assigned to a computing device to allow direct access over the
Internet. A web server, email server and any server device directly accessible from the Internet are candidate for a
public IP address. A public IP address is globally unique, and can only be assigned to a unique device.
A private IP address is the address space allocated by InterNIC to allow organizations to create their own private
network. There are three IP blocks (1 class A, 1 class B and 1 class C) reserved for a private use. The computers,
tablets and smartphones sitting behind your home, and the personal computers within an organizations are usually
assigned private IP addresses. A network printer residing in your home is assigned a private address so that only your
family can print to your local printer.
When a computer is assigned a private IP address, the local devices see this computer via it's private IP address.
However, the devices residing outside of your local network cannot directly communicate via the private IP address,
but uses your router's public IP address to communicate. To allow direct access to a local device which is assigned a
private IP address, a Network Address Translator (NAT) should be used.

9. What is the Structure of private IP?


Ans: IPv4, also known as the fourth version of Internet Protocol, is the core protocol that routes most of the internet
traffic. This is a connectionless protocol, which means that the state of the connection is not preserved and the data is
transmitted to the receiver without ensuring that the recipient is available or not.
IPv4 uses 32-bit addressing which allows a total of 4,294,967,296 (232) addresses. Some addresses are reserved for
public and private networks. An IP address consists of four octets which are separated by a period (.) which is also
known as dotted-decimal notation. For example, the IP address 172.16.254.1 represents four octets.

IPv4 Address Structure

IP Packet Structure
An IP packet consists of header information as well as encapsulated data. An IP header consists of 14 fields and
contains necessary information required to deliver the packet at another end.

IP Packet Structure
Version: Provides the version number of Internet Protocol used (such as IPv4).
IHL: Refers to Internet Header Length which is the length of entire IP header.
DSCP: Differentiated Services Code Point, also called Type of Service and caters to data from emerging
technologies.
ECN: Explicit Congestion Notification provides information about the network congestion seen in the route.
Total Length: Length of entire IP packet which includes IP header and encapsulated data.
Identification: This field is used to uniquely identify a group of fragments in the single IP packet.
Flags: This is a three-bit field that is used to identify and control fragments. In this 3-bit flag, the bit 0 is always set
to '0'.
Fragment Offset: This offset provides the location of the fragment in the original IP Packet.
Time to Live (TTL): Every packet is sent with some TTL value set to avoid looping in the network. TTL tells the
network about the hops it has crossed on the router. With each hop, the TTL value is decremented by one and when
the value reaches zero, the packet is discarded.
Protocol: This field provides the protocol that is used in the data part of the packet.
Header Checksum: This field is used for error-checking of the entire header. The value of the header checksum is
matched at the router and the packet is discarded if values don't match.
Source Address: This field is the 32-bit address of the sender of the packet.

10. What is OOPS Concept?


Ans: Object Oriented Programming
Object Oriented programming is a programming style that is associated with the concept of Class, Objects and
various other concepts revolving around these two, like Inheritance, Polymorphism, Abstraction, Encapsulation etc.

In the video below, we have explained the basic concepts of Object Oriented Programming with help of a very easy
to understand example. If you want to skip the video, everything is covered below as well.
Let us try to understand a little about all these, through a simple example. Human Beings are living forms, broadly
categorized into two types, Male and Female. Right? Its true. Every Human being(Male or Female) has two legs, two
hands, two eyes, one nose, one heart etc. There are body parts that are common for Male and Female, but then there
are some specific body parts, present in a Male which are not present in a Female, and some body parts present in
Female but not in Males.
All Human Beings walk, eat, see, talk, hear etc. Now again, both Male and Female, performs some common
functions, but there are some specifics to both, which is not valid for the other. For example : A Female can give
birth, while a Male cannot, so this is only for the Female.
Human Anatomy is interesting, isn't it? But let's see how all this is related to C++ and OOPS. Here we will try to
explain all the OOPS concepts through this example and later we will have the technical definitons for all this.

Class
Here we can take Human Being as a class. A class is a blueprint for any functional entity which defines its properties
and its functions. Like Human Being, having body parts, and performing various actions.

Inheritance
Considering HumanBeing a class, which has properties like hands, legs, eyes etc, and functions like walk, talk, eat,
see etc. Male and Female are also classes, but most of the properties and functions are included in HumanBeing,
hence they can inherit everything from class HumanBeing using the concept of Inheritance.

Objects
My name is Abhishek, and I am an instance/object of class Male. When we say, Human Being, Male or Female, we
just mean a kind, you, your friend, me we are the forms of these classes. We have a physical existence while a class
is just a logical definition. We are the objects.

Abstraction
Abstraction means, showcasing only the required things to the outside world while hiding the details. Continuing our
example, Human Being's can talk, walk, hear, eat, but the details are hidden from the outside world. We can take our
skin as the Abstraction factor in our case, hiding the inside mechanism.
Encapsulation
This concept is a little tricky to explain with our example. Our Legs are binded to help us walk. Our hands, help us
hold things. This binding of the properties to functions is called Encapsulation.
Polymorphism
Polymorphism is a concept, which allows us to redefine the way something works, by either changing how it is done
or by changing the parts using which it is done. Both the ways have different terms for them.
If we walk using our hands, and not legs, here we will change the parts used to perform something. Hence this is
called Overloading.
And if there is a defined way of walking, but I wish to walk differently, but using my legs, like everyone else. Then I
can walk like I want, this will be called as Overriding.

11. What is Stack?


Ans: A stack (sometimes called a “push-down stack”) is an ordered collection of items where the addition of new
items and the removal of existing items always takes place at the same end. This end is commonly referred to as the
“top.” The end opposite the top is known as the “base.”
The base of the stack is significant since items stored in the stack that are closer to the base represent those that have
been in the stack the longest. The most recently added item is the one that is in position to be removed first. This
ordering principle is sometimes called LIFO, last-in first-out. It provides an ordering based on length of time in the
collection. Newer items are near the top, while older items are near the base.
Many examples of stacks occur in everyday situations. Almost any cafeteria has a stack of trays or plates where you
take the one at the top, uncovering a new tray or plate for the next customer in line. Imagine a stack of books on a
desk (Figure 1). The only book whose cover is visible is the one on top. To access others in the stack, we need to
remove the ones that are sitting on top of them. Figure 2 shows another stack. This one contains a number of
primitive Python data objects.

One of the most useful ideas related to stacks comes from the simple observation of items as they are added and then
removed. Assume you start out with a clean desktop. Now place books one at a time on top of each other. You are
constructing a stack. Consider what happens when you begin removing books. The order that they are removed is
exactly the reverse of the order that they were placed. Stacks are fundamentally important, as they can be used to
reverse the order of items. The order of insertion is the reverse of the order of removal. Figure 3 shows the Python
data object stack as it was created and then again as items are removed. Note the order of the objects.

Considering this reversal property, you can perhaps think of examples of stacks that occur as you use your computer.
For example, every web browser has a Back button. As you navigate from web page to web page, those pages are
placed on a stack (actually it is the URLs that are going on the stack). The current page that you are viewing is on the
top and the first page you looked at is at the base. If you click on the Back button, you begin to move in reverse order
through the pages.
12. Describe Data Structure?
Ans: Data Structure is a way of collecting and organising data in such a way that we can perform operations on these
data in an effective way. Data Structures is about rendering data elements in terms of some relationship, for better
organization and storage. For example, we have some data which has, player's name "Virat" and age 26. Here "Virat"
is of String data type and 26 is of integer data type.

We can organize this data as a record like Player record, which will have both player's name and age in it. Now we
can collect and store player's records in a file or database as a data structure. For example: "Dhoni" 30, "Gambhir"
31, "Sehwag" 33

If you are aware of Object Oriented programming concepts, then a class also does the same thing, it collects different
type of data under one single entity. The only difference being, data structures provides for techniques to access and
manipulate data efficiently.

In simple language, Data Structures are structures programmed to store ordered data, so that various operations can
be performed on it easily. It represents the knowledge of data to be organized in memory. It should be designed and
implemented in such a way that it reduces the complexity and increases the efficiency.

Basic types of Data Structures


As we have discussed above, anything that can store data can be called as a data structure, hence Integer, Float,
Boolean, Char etc, all are data structures. They are known as Primitive Data Structures.

Then we also have some complex Data Structures, which are used to store large and connected data. Some example
of Abstract Data Structure are :

 Linked List
 Tree
 Graph
 Stack, Queue etc.

13. Explain Enumeration.


Ans: An enumeration consists of integral constants. To define an enumeration, keyword enum is used.

enum flag { const1, const2, ..., constN };


Here, name of the enumeration is flag.

And, const1, const2,...., constN are values of type flag.

By default, const1 is 0, const2 is 1 and so on. You can change default values of enum elements during declaration (if
necessary).

// Changing default values of enum


enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3,
};
Enumerated Type Declaration
When you create an enumerated type, only blueprint for the variable is created. Here's how you can create variables
of enum type.

enum boolean { false, true };


enum boolean check;

14. What is Bit Set in Java with examples?


Ans: BitSet is a class defined in the java.util package. It creates an array of bits represented by boolean values.

Constructors:

BitSet class Constructors


/ \
BitSet() BitSet(int no_Of_Bits)
BitSet() : A no-argument constructor to create an empty BitSet object.
BitSet(int no_Of_Bits) : A one-constructor with an integer argument to create an instance of the BitSet class with an
initial size of the integer argument representing the number of bits.

15. What is the difference between Views Table and Hash Table?
Ans: HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to
store unique keys.
But there are many differences between HashMap and Hashtable classes that are given below.
HashMapHashtable
1) HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper
synchronization code.Hashtable is synchronized. It is thread-safe and can be shared with many threads.
2) HashMap allows one null key and multiple null values.Hashtable doesn't allow any null key or value.
3) HashMap is a new class introduced in JDK 1.2.Hashtable is a legacy class.
4) HashMap is fast.Hashtable is slow.
5) We can make the HashMap as synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap);Hashtable is internally synchronized and can't be unsynchronized.
6) HashMap is traversed by Iterator.Hashtable is traversed by Enumerator and Iterator.
7) Iterator in HashMap is fail-fast.Enumerator in Hashtable is not fail-fast.
8) HashMap inherits AbstractMap class.Hashtable inherits Dictionaryclass.
Drive Name: EASTERN SOFTWARE
Book Index: 235 (D)
Technical Interview

1. Explain Tree Data Structure.


Ans: Tree represents the nodes connected by edges. We will discuss binary tree or binary search tree
specifically.
Binary Tree is a special datastructure used for data storage purposes. A binary tree has a special condition
that each node can have a maximum of two children. A binary tree has the benefits of both an ordered
array and a linked list as search is as quick as in a sorted array and insertion or deletion operation are as
fast as in linked list.

2. Reduce the complexity of the code.


Ans: Complexity of an algorithm is a measure of the amount of time and/or space required by an algorithm for
an input of a given size (n).
What effects run time of an algorithm?
(a) computer used, the harware platform
(b) representation of abstract data types (ADT's)
(c) efficiency of compiler
(d) competence of implementer (programming skills)
(e) complexity of underlying algorithm
(f) size of the input
We will show that of those above (e) and (f) are generally the most significant
Time for an algorithm to run t(n)
A function of input. However, we will attempt to characterise this by the size of the input. We will try and
estimate the WORST CASE, and sometimes the BEST CASE, and very rarely the AVERAGE CASE.
In analysing an algorithm, rather than a piece of code, we will try and predict the number of times "the principle
activity" of that algorithm is performed. For example, if we are analysing a sorting algorithm we might count the
number of comparisons performed, and if it is an algorithm to find some optimal solution, the number of times it
evaluates a solution. If it is a graph colouring algorithm we might count the number of times we check that a
coloured node is compatible with its neighbours.
Worst Case
It is the maximum run time, over all inputs of size n, ignoring effects (a) through (d) above. That is, we only
consider the "number of times the principle activity of that algorithm is performed".
Best Case
In this case we look at specific instances of input of size n. For example, we might get best behaviour from a
sorting algorithm if the input to it is already sorted.
Average Case
Arguably, average case is the most useful measure. It might be the case that worst case behaviour is pathological
and extremely rare, and that we are more concerned about how the algorithm runs in the general case.
Unfortunately this is typically a very difficult thing to measure. Firstly, we must in some way be able to define
by what we mean as the "average input of size n". We would need to know a great deal about the distribution of
cases throughout all data sets of size n. Alternatively we might make a possibly dangerous assumption that all
data sets of size n are equally likely. Generally, in order to get a feel for the average case we must resort to an
empirical study of the algorithm, and in some way classify the input (and it is only recently with the advent of
high performance, low cost computation, that we can seriously consider this option).
3. Problems on Array.
Ans: Remove duplicates from unsorted array
Given an unsorted array of integers, Print the array after removing the duplicate elements from it. We need to
print distinct array elements according to their first occurrence.

Examples:

Input : arr[] = { 1, 2, 5, 1, 7, 2, 4, 2}
Output : 1 2 5 7 4
Explanation : {1, 2} appear more than one time.
Approach :

Take a hash map, in which will store all the elements which has appeared before.
Traverse the array.
Check if the element is present in the hash map.
If yes, continue traversing the array.
Else Print the element.

4. Shell Sort.
Ans: ShellSort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position
ahead. When an element has to be moved far ahead, many movements are involved. The idea of shellSort is to
allow exchange of far items. In shellSort, we make the array h-sorted for a large value of h. We keep reducing
the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h’th element is sorted.
5. Merge Sort.
Ans: Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls
itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two
halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges
the two sorted sub-arrays into one.

6. Largest triplet product in a stream.


Ans: Given a stream of integers represented as arr[]. For each index i from 0 to n-1, print the multiplication of
largest, second largest, third largest element of the subarray arr[0…i]. If i < 2 print -1.

Examples:

Input : arr[] = {1, 2, 3, 4, 5}


Output :-1
-1
6
24
60
Explanation : for i = 2 only three elements
are there {1, 2, 3} so answer is 6. For i = 3
largest three elements are {2, 3, 4} their
product is 2*3*4 = 24 ....so on

 Insert arr[i] in the priority queue


 As the top element in priority queue is largest so pop it and store it as x. Now the top element in the priority
queue will be the second largest element in subarray arr[0…i] pop it and store as y. Now the top element is
third largest element in subarray arr[0…i] so pop it and store it as z.
 Print x*y*z
 Reinsert x, y, z.

7. Count distinct elements in an array.


Ans: Given an unsorted array, count all distinct elements in it.

Examples:

Input : arr[] = {10, 20, 20, 10, 30, 10}


Output : 3
There are three distinct elements 10, 20 and 30.

Input : arr[] = {10, 20, 20, 10, 20}


Output : 2

A simple solution is to run two loops. For every element, check if it has appeared before. If yes, increment count
of distinct elements.

// C++ program to count distinct elements


// in a given array
#include <iostream>
using namespace std;

int countDistinct(int arr[], int n)


{
int res = 1;

// Pick all elements one by one


for (int i = 1; i < n; i++) {
int j = 0;
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;

// If not printed earlier, then print it


if (i == j)
res++;
}
return res;
}

// Driver program to test above function


int main()
{
int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << countDistinct(arr, n);
return 0;
}
Output:
5
Time Complexity of above solution is O(n2). We can Use Sorting to solve the problem in O(nLogn) time. The
idea is simple, first sort the array so that all occurrences of every element become consecutive. Once the
occurrences become consecutive, we can traverse the sorted array and count distinct elements in O(n) time.
Following is the implementation of the idea.

8. Inorder Successor of a node in Binary Tree.


Ans: In Binary Tree, Inorder successor of a node is the next node in Inorder traversal of the Binary Tree. Inorder
Successor is NULL for the last node in Inoorder traversal.
In Binary Search Tree, Inorder Successor of an input node can also be defined as the node with the smallest key
greater than the key of input node. So, it is sometimes important to find next node in sorted order.
In the above diagram, inorder successor of 8 is 10, inorder successor of 10 is 12 and inorder successor of 14 is 20.

Method 1 (Uses Parent Pointer)


In this method, we assume that every node has parent pointer.
The Algorithm is divided into two cases on the basis of right subtree of the input node being empty or not.
Input: node, root // node is the node whose Inorder successor is needed.
output: succ // succ is Inorder successor of node.
1) If right subtree of node is not NULL, then succ lies in right subtree. Do following.
Go to right subtree and return the node with minimum key value in right subtree.
2) If right sbtree of node is NULL, then succ is one of the ancestors. Do following.
Travel up using the parent pointer until you see a node which is left child of it’s parent. The parent of such a node is
the succ.

9. Mirror Image of a Tree.


Ans: Given a binary tree, the task is to create a new binary tree which is a mirror image of the given binary tree.

Examples:
Input:
5
/\
3 6
/\
2 4
Output:
Inorder of original tree: 2 3 4 5 6
Inorder of mirror tree: 6 5 4 3 2
Mirror tree will be:
5
/\
6 3
/\
4 2

Input:
2
/\
1 8
/ \
12 9
Output:
Inorder of original tree: 12 1 2 8 9
Inorder of mirror tree: 9 8 2 1 12

Approach: Write a recursive function that will take two nodes as the argument, one of the original tree and the
other of the newly created tree. Now, for every passed node of the original tree, create a corresponding node in
the mirror tree and then recursively call the same method for the child nodes but passing the left child of the
original tree node with the right child of the mirror tree node and the right child of the original tree node with the
left child of the mirror tree node.

10. Right view of a tree.


Ans: Given a Binary Tree, print Right view of it. Right view of a Binary Tree is set of nodes visible when tree is
visited from Right side.

Examples:

Input :
10
/ \
2 3
/ \ / \
7 8 12 15
/
14
Output : 10 3 15 14
The output nodes are the rightmost
nodes of their respective levels.
We have already discussed recursive solution for right view. In this post, level order traversal based solution is
discussed.
If we observe carefully, we will see that our main task is to print the right most node of every level. So, we will
do a level order traversal on the tree and print the rightmost node at every level.

11. Check whether a tree is Balance or Not.


Ans: A binary search tree (BST) is a node based binary tree data structure which has the following properties.
• The left subtree of a node contains only nodes with keys less than the node’s key.
• The right subtree of a node contains only nodes with keys greater than the node’s key.
• Both the left and right subtrees must also be binary search trees.

From the above properties it naturally follows that:


• Each node (item in the tree) has a distinct key.

Following is a simple program. For each node, check if left node of it is smaller than the node and right node of it is
greater than the node.

filter_none
edit
play_arrow

brightness_4
int isBST(struct node* node)
{
if (node == NULL)
return 1;

/* false if left is > than node */


if (node->left != NULL && node->left->data > node->data)
return 0;

/* false if right is < than node */


if (node->right != NULL && node->right->data < node->data)
return 0;

/* false if, recursively, the left or right is not a BST */


if (!isBST(node->left) || !isBST(node->right))
return 0;

/* passing all that, it's a BST */


return 1;
}
Drive Name: DE FACTO INFOTECH
Book Index: 236 (D)

Technical Written Test

1. Display prime number between 1 to 100.


ANS:
/* C Program to Print Prime Numbers between 1 to 100 using For Loop */

#include <stdio.h>

int main()
{
int i, Number, count;

printf(" Prime Number from 1 to 100 are: \n");


for(Number = 1; Number <= 100; Number++)
{
count = 0;
for (i = 2; i <= Number/2; i++)
{
if(Number%i == 0)
{
count++;
break;
}
}
if(count == 0 && Number != 1 )
{
printf(" %d ", Number);
}
}
return 0;
}

2. Display Reverse of a given Number.


ANS:
#include <bits/stdc++.h>

using namespace std;


/* Iterative function to reverse digits of num*/
int reversDigits(int num)
{
int rev_num = 0;
while(num > 0)
{
rev_num = rev_num*10 + num%10;
num = num/10;
}
return rev_num;
}

/*Driver program to test reversDigits*/


int main()
{
int num = 4562;
cout << "Reverse of no. is "
<< reversDigits(num);
getchar();
return 0;
}

3. Display a Fibonacci Series up to 1000.


ANS:
#include <stdio.h>
int main()
{
int i, n, t1 = 0, t2 = 1, nextTerm;

printf("Enter the number of terms: ");


scanf("%d", &n);

printf("Fibonacci Series: ");

for (i = 1; i <= n; ++i)


{
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}

4. Display a Factorial of any given number.


ANS:
#include <stdio.h>
int main()
{
int n, i;
unsigned long long factorial = 1;

printf("Enter an integer: ");


scanf("%d",&n);

// show error if the user enters a negative integer


if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");

else
{
for(i=1; i<=n; ++i)
{
factorial *= i; // factorial = factorial*i;
}
printf("Factorial of %d = %llu", n, factorial);
}

return 0;
}

5. Display a pyramid of
*
*
***
*****
*******
*********
ANS:

public class Pattern {

public static void main(String[] args) {


int rows = 5, k = 0;

for(int i = 1; i <= rows; ++i, k = 0) {


for(int space = 1; space <= rows - i; ++space) {
System.out.print(" ");
}

while(k != 2 * i - 1) {
System.out.print("* ");
++k;
}

System.out.println();
}
}
}

Das könnte Ihnen auch gefallen