GetMoney

Thursday, May 27, 2010

BASIC JAVA INTERVIEW QUESTION WITH ANSWER

1)What is OOPs?

Ans: Object oriented programming organizes a program around its data,i.e.,objects and a set of well defined interfaces to that data.An object-oriented program can be characterized as data controlling access to code.



2)what is the difference between Procedural and OOPs?

Ans: a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOPs program, unit of program is object, which is nothing but combination of data and code.


b) In procedural program,data is exposed to the whole program whereas in OOPs program,it is accessible with in the object and which in turn assures the security of the code.


3)What are Encapsulation, Inheritance and Polymorphism?

Ans: Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse.

Inheritance is the process by which one object acquires the properties of another object.

Polymorphism is the feature that allows one interface to be used for general class actions.


4)What is the difference between Assignment and Initialization?


Ans: Assignment can be done as many times as desired whereas initialization can be done only once.


5)What are Class, Constructor and Primitive data types?

Ans: Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform. Constructor is a special kind of method that determines how an object is initialized when created.

Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean, char


6)What is an Object and how do you allocate memory to it?

Ans: Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using new operator, memory is allocated to it.


7)What is the difference between constructor and method?

Ans: Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.



8)What are methods and how are they defined?

Ans: Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes.Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method’s signature is a combination of the first three parts mentioned above.


9)What is the use of bin and lib in JDK?

Ans: Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.


10)What is casting?

Ans: Casting is used to convert the value of one type to another.


11)How many ways can an argument be passed to a subroutine and explain them?


Ans: An argument can be passed in two ways. They are passing by value and passing by reference.Passing by value: This method copies the value of an argument into the formal parameter of the subroutine.Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.


12)What is the difference between an argument and a parameter?

Ans: While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.


13)What are different types of access modifiers?

Ans: public: Any thing declared as public can be accessed from anywhere.

private: Any thing declared as private can’t be seen outside of its class.

protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages.

default modifier : Can be accessed only to classes in the same package.



14)What is final, finalize() and finally?

Ans: final : final keyword can be used for class, method and variables.A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods.A final method can’ t be overriddenA final variable can’t change from its initialized value.finalize( ) : finalize( ) method is used just before an object is destroyed and can be called just prior to garbage collecollection finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.


15)What is UNICODE?

Ans: Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.


16)What is Garbage Collection and how to call it explicitly?

Ans: When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection.System.gc() method may be used to call it explicitly.


17)What is finalize() method ?


Ans: finalize () method is used just before an object is destroyed and can be called just prior to garbage collection.


18)What are Transient and Volatile Modifiers?

Ans: Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized.Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.


19)What is method overloading and method overriding?

Ans: Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading.

Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.


20)What is difference between overloading and overriding?


Ans: a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method.

b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass.

c) In overloading, separate methods share the same name whereas in overriding,subclass method replaces the superclass.

d) Overloading must have different method signatures whereas overriding must have same signature.


21) What is meant by Inheritance and what are its advantages?

Ans: Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.


22)What is the difference between this() and super()?

Ans: this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.



23)What is the difference between superclass and subclass?

Ans: A super class is a class that is inherited whereas sub class is a classthat does the inheriting.


24) What modifiers may be used with top-level class?

Ans: public, abstract and final can be used for top-level class.


25)What are inner class and anonymous class?

Ans: Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private.Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.

Tuesday, May 25, 2010

Networking server side Interview Questions with Answers

1. What is an Object server?

With an object server, the Client/Server application is written as a set of communicating objects. Client object communicate with server objects using an Object Request Broker (ORB). The client invokes a method on a remote object. The ORB locates an instance of that object server class, invokes the requested method and returns the results to the client object. Server objects must provide support for concurrency and sharing. The ORB brings it all together.

2. What is a Transaction server?

With a transaction server, the client invokes remote procedures that reside on the server with an SQL database engine. These remote procedures on the server execute a group of SQL statements. The network exchange consists of a single request/reply message. The SQL statements either all succeed or fail as a unit.

3. What is a Database Server?

With a database server, the client passes SQL requests as messages to the database server. The results of each SQL command are returned over the network. The server uses its own processing power to find the request data instead of passing all the records back to the client and then getting it find its own data. The result is a much more efficient use of distributed processing power. It is also known as SQL engine.

4. What are the most typical functional units of the Client/Server applications?

* User interface
* Business Logic and
* Shared data.

5. What are all the Extended services provided by the OS?

* Ubiquitous communications
* Network OS extension
* Binary large objects (BLOBs)
* Global directories and Network yellow pages
* Authentication and Authorization services
* System management
* Network time
* Database and transaction services
* Internet services
* Object- oriented services

6. What are Triggers and Rules?

Triggers are special user defined actions usually in the form of stored procedures, that are automatically invoked by the server based on data related events. It can perform complex actions and can use the full power of procedural languages.
A rule is a special type of trigger that is used to perform simple checks on data.

7. What is meant by Transparency?

Transparency really means hiding the network and its servers from the users and even the application programmers.

8. What are TP-Lite and TP-Heavy Monitors?

TP-Lite is simply the integration of TP Monitor functions in the database engines. TP-Heavy are TP Monitors which supports the Client/Server architecture and allow PC to initiate some very complex multiserver transaction from the desktop.

9. What are the two types of OLTP?

TP lite, based on stored procedures. TP heavy, based on the TP monitors.

10. What is a Web server?

This new model of Client/Server consists of thin, protable, "universal" clients that talk to superfat servers. In the simplet form, a web server returns documents when clients ask for them by name. The clients and server communicate using an RPC-like protocol called HTTP.
11. What are Super servers?

These are fully-loaded machines which includes multiprocessors, high-speed disk arrays for intervive I/O and fault tolerant features.

12. What is a TP Monitor?

There is no commonly accepted definition for a TP monitor. According to Jeri Edwards' a TP Monitor is "an OS for transaction processing".

13. TP Monitor does mainly two things extremely well. They are Process management and Transaction management.?

They were originally introduced to run classes of applications that could service hundreds and sometimes thousands of clients. TP Monitors provide an OS - on top of existing OS - that connects in real time these thousands of humans with a pool of shared server processes.

14. What is meant by Asymmetrical protocols?

There is a many-to-one relationship between clients and server. Clients always initiate the dialog by requesting a service. Servers are passively awaiting for requests from clients.

15. What are the types of Transparencies?

The types of transparencies the NOS middleware is expected to provide are:-

* Location transparency
* Namespace transparency
* Logon transparency
* Replication transparency
* Local/Remote access transparency
* Distributed time transparency
* Failure transparency and
* Administration transparency.

16. What is the difference between trigger and rule?

The triggers are called implicitly by database generated events, while stored procedures are called explicitly by client applications.

17. What are called Transactions?

The grouped SQL statements are called Transactions (or) A transaction is a collection of actions embused with ACID properties.

18. What are the building blocks of Client/Server?

* The client
* The server and
* Middleware.

19. Explain the building blocks of Client/Server?

The client side building block runs the client side of the application.
The server side building block runs the server side of the application.

20. The middleware buliding block runs on both the client and server sides of an application. It is broken into three categories:-

* Transport stack
* Network OS
* Service-specific middleware.

21. What are all the Base services provided by the OS?

* Task preemption
* Task priority
* Semaphores
* Interprocess communications (IPC)
* Local/Remote Interprocess communication
* Threads
* Intertask protection
* Multiuser
* High performance file system
* Efficient memory management and
* Dynamically linked Run-time extensions.

22. What are the roles of SQL?

* SQL is an interactive query language for ad hoc database queries.
* SQL is a database programming language.
* SQL is a data definition and data administration language.
* SQL is the language of networked database servers
* SQL helps protect the data in a multi-user networked environment.
* Because of these multifacted roles it plays, physicists might call SQL as "The grand unified theory of database".

23. What is Structured Query Langauge (SQL)?

SQL is a powerful set-oriented language which was developed by IBM research for the databases that adhere to the relational model. It consists of a short list of powerful, yet highly flexible, commands that can be used to manipulate information collected in tables. Through SQL, we can manipulate and control sets of records at a time.

24. What are the characteristics of Client/Server?

* Service
* Shared resources
* Asymmentrical protocols
* Transparency of location
* Mix-and-match
* Message based exchanges
* Encapsulation of services
* Scalability
* Integrity

Client/Server computing is the ultimate "Open platform". It gives the freedom to mix-and-match components of almost any level. Clients and servers are loosely coupled systems that interact through a message-passing mechanism.

25. What is Remote Procedure Call (RPC)?

RPC hides the intricacies of the network by using the ordinary procedure call mechanism familiar to every programmer. A client process calls a function on a remote server and suspends itself until it gets back the results. Parameters are passed like in any ordinary procedure. The RPC, like an ordinary procedure, is synchoronous. The process that issues the call waits until it gets the results.

Under the covers, the RPC run-time software collects values for the parameters, forms a message, and sends it to the remote server. The server receives the request, unpack the parameters, calls the procedures, and sends the reply back to the client. It is a telephone-like metaphor.

26. What are the main components of Transaction-based Systems?

* Resource Manager
* Transaction Manager and
* Application Program.

27. What are the three types of SQL database server architecture?

* Process-per-client Architecture. (Example: Oracle 6, Informix )
* Multithreaded Architecture. (Example: Sybase, SQL server)
* Hybrid Architecture (Example: Oracle 7)

28. What are the Classification of clients?

Non-GUI clients - Two types are:-

1. Non-GUI clients that do not need multi-tasking
(Example: Automatic Teller Machines (ATM), Cell phone)
2. Non-GUI clients that need multi-tasking
(Example: ROBOTs)
GUI clients
OOUI clients

29. What are called Non-GUI clients, GUI Clients and OOUI Clients?

Non-GUI Client: These are applications, generate server requests with a minimal amount of human interaction.
GUI Clients: These are applicatoins, where occassional requests to the server result from a human interacting with a GUI
(Example: Windows 3.x, NT 3.5)
OOUI clients : These are applications, which are highly-iconic, object-oriented user interface that provides seamless access to information in very visual formats.
(Example: MAC OS, Windows 95, NT 4.0)

30. What is Message Oriented Middleware (MOM)?

MOM allows general purpose messages to be exchanged in a Client/Server system using message queues. Applications communicate over networks by simply putting messages in the queues and getting messages from queues. It typically provides a very simple high level APIs to its services.
MOM's messaging and queuing allow clients and servers to communicate across a network without being linked by a private, dedicated, logical connection. The clients and server can run at different times. It is a post-office like metaphor.

31. What is meant by Middleware?

Middleware is a distributed software needed to support interaction between clients and servers. In short, it is the software that is in the middle of the Client/Server systems and it acts as a bridge between the clients and servers. It starts with the API set on the client side that is used to invoke a service and it covers the transmission of the request over the network and the resulting response.
It neither includes the software that provides the actual service - that is in the servers domain nor the user interface or the application login - that's in clients domain.

32. What are the functions of the typical server program?

It waits for client-initiated requests. Executes many requests at the same time. Takes care of VIP clients first. Initiates and runs background task activity. Keeps running. Grown bigger and faster.

33. What is meant by Symmentric Multiprocessing (SMP)?

It treats all processors as equal. Any processor can do the work of any other processor. Applications are divided into threads that can run concurrently on any available processor. Any processor in the pool can run the OS kernel and execute user-written threads.

34. What are Service-specific middleware?

It is needed to accomplish a particular Client/Server type of services which includes:-

* Database specific middleware
* OLTP specific middleware
* Groupware specific middleware
* Object specific middleware
* Internet specific middleware and
* System management specific middleware.

35. What are General Middleware?

It includes the communication stacks, distributed directories, authentication services, network time, RPC, Queuing services along with the network OS extensions such as the distributed file and print services.

36. What is meant by Asymmetric Multiprocessing (AMP)?

It imposses hierarchy and a division of labour among processors. Only one designated processor, the master, controls (in a tightly coupled arrangement) slave processors dedicated to specific functions.

37. What is OLTP?

In the transaction server, the client component usually includes GUI and the server components usually consists of SQL transactions against a database. These applications are called OLTP (Online Transaction Processing) OLTP Applications typically,
Receive a fixed set of inputs from remote clients. Perform multiple pre-compiled SQL comments against a local database. Commit the work and Return a fixed set of results.

38. What is meant by 3-Tier architecture?

In 3-tier Client/Server systems, the application logic (or process) lives in the middle tier and it is separated from the data and the user interface. In theory, the 3-tier Client/Server systems are more scalable, robust and flexible.
Example: TP monitor, Web.

39. What is meant by 2-Tier architecture?

In 2-tier Client/Server systems, the application logic is either burried inside the user interface on the client or within the database on the server.
Example: File servers and Database servers with stored procedures.

40. What is Load balancing?

If the number of incoming clients requests exceeds the number of processes in a server class, the TP Monitor may dynamically start new ones and this is called Load balancing.

41. What are called Fat clients and Fat servers?

If the bulk of the application runs on the Client side, then it is Fat clients. It is used for decision support and personal software.
If the bulk of the application runs on the Server side, then it is Fat servers. It tries to minimize network interchanges by creating more abstract levels of services.

42. What is meant by Horizontal scaling and Vertical scaling?

Horizontal scaling means adding or removing client workstations with only a slight performance impact. Vertical scaling means migrating to a larger and faster server machine or multiservers.

43. What is Groupware server?

Groupware addresses the management of semi-structured information such as text, image, mail, bulletin boards and the flow of work. These Client/Server systems have people in direct contact with other people.

44. What are the two broad classes of middleware?

* General middleware
* Service-specific middleware.

45. What are the types of Servers?

* File servers
* Database servers Transaction servers Groupware servers
* Object servers Web servers.

46. What is a File server?

File servers are useful for sharing files across a network. With a file server, the client passes requests for file records over nerwork to file server.

47. What are the five major technologies that can be used to create Client/Server applications?

* Database Servers
* TP Monitors
* Groupware
* Distributed Objects
* Intranets.

48. What is Client/Server?

Clients and Servers are separate logical entities that work together over a network to accomplish a task. Many systems with very different architectures that are connected together are also called Client/Server.

49. List out the benefits obtained by using the Client/Server oriented TP Monitors?

* Client/Server applications development framework.
* Firewalls of protection.
* High availability.
* Load balancing.
* MOM integration.
* Scalability of functions.
* Reduced system cost.

50. What are the services provided by the Operating System?

Extended services - These are add-on modular software components that are layered on top of base service.

Basic networking

What is LAN?

LAN is a computer network that spans a relatively small area. Most LANs are confined to a single building or group of buildings. However, one LAN can be connected to other LANs over any distance via telephone lines and radio waves. A system of LANs connected in this way is called a wide-area network (WAN). Most LANs connect workstations and personal computers. Each node (individual computer) in a LAN has its own CPU with which it executes programs, but it also is able to access data and devices anywhere on the LAN. This means that many users can share expensive devices, such as laser printers, as well as data. Users can also use the LAN to communicate with each other, by sending e-mail or engaging in chat sessions.
What's the difference Between an Intranet and the Internet?

There's one major distinction between an intranet and the Internet: The Internet is an open, public space, while an intranet is designed to be a private space. An intranet may be accessible from the Internet, but as a rule it's protected by a password and accessible only to employees or other authorized users.

From within a company, an intranet server may respond much more quickly than a typical Web site. This is because the public Internet is at the mercy of traffic spikes, server breakdowns and other problems that may slow the network. Within a company, however, users have much more bandwidth and network hardware may be more reliable. This makes it easier to serve high-bandwidth content, such as audio and video, over an intranet.
Define the term Protocol.

Protocol is a standard way of communicating across a network. A protocol is the "language" of the network. It is a method by which two dissimilar systems can communicate. TCP is a protocol which runs over a network.
Define File Transfer Protocol.

File Transfer Protocol (FTP), a standard Internet protocol, is the simplest way to exchange files between computers on the Internet. Like the Hypertext Transfer Protocol (HTTP), which transfers displayable Web pages and related files, and the Simple Mail Transfer Protocol (SMTP), which transfers e-mail, FTP is an application protocol that uses the Internet's TCP/IP protocols. FTP is commonly used to transfer Web page files from their creator to the computer that acts as their server for everyone on the Internet. It's also commonly used to download programs and other files to your computer from other servers.
Networking - What is FTP (File Transfer Protocol)? - Jan 28, 2009, 17:00 pm by Rajmeet Ghai
What is FTP (File Transfer Protocol)?

FTP is File Transfer Protocol. It used to exchange files on the internet. To enable the data transfer FTP uses TCP/IP, FTP is most commonly used to upload and download files from the internet. FTP can be invoked from the command prompt or some graphical user interface. FTP also allows to update (delete, rename, move, and copy) files at a server. It uses a reserved port no 21.
Explain the 7 Layers of OSI.

Layer 1: Physical layer
It represents all the electrical and physical specifications for devices.

Layer 2: Data link layer
It provides the functional and procedural means to transfer data between network entities and to detect and possibly correct errors that may occur in the Physical layer.

Layer 3: Network layer
The Network layer provides the functional and procedural means of transferring variable length data sequences from a source to a destination via one or more networks.

Layer 4: Transport layer
It provides transparent transfer of data between end users.

Layer 5: Session layer
It controls the sessions between computers. It connects, manages and terminates the connections between the local and remote application.

Layer 6: Presentation layer
It transforms data to provide a standard interface for the Application layer.

Layer 7: Application layer
It provides a means for the user to access information on the network through an application.

What is a network? What are the different kinds of network? Explain them

A network is a group of computers or nodes connected together. They are connected with each other by communication paths.

Types of Networks:

LAN – Local Area Network connects a group of nodes covering a small physical area. LAN’s are most commonly seen in offices, building etc. LAN’s enable higher transfer rate of data, smaller coverage of area and hence less wiring.

WAN – Wide Area Network connects a group of nodes covering a wide area. WAN typically connects and allow communication between regions or national boundaries. The most common example of WAN is internet.

VPN – Virtual Private Network connects or links nodes in some larger area by open connections or virtual circuits in some larger network (e.g., the Internet) instead of by physical wires. It is used for secure communication through the public internet. VPN alone may not support explicit security features, such as authentication or content encryption.

Intranet – It is a set of networks under the control of a single administrative person. It can be considered as an internal network of an organization. If it is large, web servers are used to provide information to the users.

Extranet – It is a network that restricts itself within a single organization. It can be categorized as WAN, MAN etc. however; it cannot have a single LAN. It must have a connection (at least one) with external network.
What are network topologies? Explain Ring, Bus and Star topology.

A network topology describes the layout of a network. It describes how different nodes and elements are connected to each other. Different types of topology:

a. Ring:-

* All nodes connected with another in a loop.
* Each device is connected to one or more another device on either side.

b. Bus

* All nodes connected to a central and a common cable called as a back bone.
* In bus topology, the server is at one end and the clients are connected at different positions across the network.
* Easy to manage and install.
* If the backbone fails, the entire communication fails.

c. Star

* All nodes connected to a central hub.
* The communication between the nodes is through the hub.
* Relative requires more cables as compared to BUS. However if any node fails, it wont affect the entire LAN.
Explain IP, TCP and UDP.

TCP – Transmission control Protocol is used to establish communication between nodes or networks and exchange data packets. It guarantees delivery of data packets in the order they were sent. Hence it is most commonly used in all applications that require guaranteed delivery of data. It can handle both timeouts (if packets were delayed) and retransmission (if packets were lost). The stream of data is transmitted in segments. The segment header is 32 bit. it is a connectionless communication protocol at the third level (network) of the OSI model.

IP – Internet protocol is used for transmission of data over the internet. IP uses IP addresses to identity each machine uniquely. Message is sent using small packets. The packet contains both the sender and receivers address. IP does not guarantee the delivery in the same order as sent. This is because the packets are sent via different routes. It is a connectionless communication protocol at the third level (network) of the OSI model.

UDP – User Data Protocol is a communication protocol. It is normally used as an alternative for TCP/IP. However there are a number of differences between them. UDP does not divide data into packets. Also, UDP does not send data packets in sequence. Hence, the application program must ensure the sequencing. UDP uses port numbers to distinguish user requests. It also has a checksum capability to verify the data.
What is multicasting?

Multicasting allows a single message to be sent to a group of recipients. Emailing, teleconferencing, are examples of multicasting. It uses the network infrastructure and standards to send messages.

Explain the functionality of PING.

Ping Is particularly used to check if the system is in network or not. It also gives packet lost information. In windows ping command is written as ping ip_address. The output returns the data packets information. The number of packets sent, received and lost is returned by PING
Explain the core naming mechanism, Domain Name System (DNS).

A Domain Name system is used to convert the names of the website on the internet to IP addresses. The domain names for each IP addresses are stored in a database that is distributed across different servers. A domain name space consists of a tree of domain names. The tree has zones. Zones consist of a collection of connected nodes. These nodes are served by a name server. A domain name is usually in the form of mydomain.com. Here, .com is the top level domain. Where as mydomain is the sub domain or subdivision. A host name is a domain name that has one or more IP addresses associated with it.
What is Application layer?

The application layer is located at the top of the TCP/IP protocol layers. This one contains the network applications which make it possible to communicate using the lower layers. The software in this layer therefore communicates using one of the two protocols of the layer below (the transport layer), i.e. TCP or UDP. In computer networking, an application layer firewall is a firewall operating at the application layer of a protocol stack.[1] Generally it is a host using various forms of proxy servers to proxy traffic instead of routing it. As it works on the application layer, it may inspect the contents of the traffic, blocking what the firewall administrator views as inappropriate content, such as certain websites, viruses, and attempts to exploit known logical flaws in client software, and so forth. An application layer firewall does not route traffic on the network layer. All traffic stops at the firewall which may initiate its own connections if the traffic satisfies the rules.
Define DNS

The DNS translates Internet domain and host names to IP addresses. DNS automatically converts the names we type in our Web browser address bar to the IP addresses of Web servers hosting those sites. DNS implements a distributed database to store this name and address information for all public hosts on the Internet.
Define Telnet

Telnet is the main Internet protocol for creating a connection to a remote server.
Define SMTP.

SMTP - Short for Simple Mail Transfer Protocol, a protocol for sending e-mail messages between servers.
What Is a MAC Address?

MAC (Media Access Control) addresses are globally unique addressed that are written into hardware at the time of manufacture. The MAC address is a unique value associated with a network adapter. MAC addresses are also known as hardware addresses or physical addresses. They uniquely identify an adapter on a LAN. MAC addresses are 12-digit hexadecimal numbers (48 bits in length).

MAC vs. IP Addressing

Whereas MAC addressing works at the data link layer, IP addressing functions at the network layer (layer 3). It's a slight oversimplification, but one can think of IP addressing as supporting the software implementation and MAC addresses as supporting the hardware implementation of the network stack. The MAC address generally remains fixed and follows the network device, but the IP address changes as the network device moves from one network to another.
Define Spanning-Tree Protocol (STP)

Spanning-Tree Protocol (STP) as defined in the IEEE 802.1D is a link management protocol that provides path redundancy while preventing undesirable loops in the network. For an Ethernet network to function properly, only one active path can exist between two stations. Loops occur in networks for a variety of reasons. The most common reason you find loops in networks is the result of a deliberate attempt to provide redundancy - in case one link or switch fails, another link or switch can take over.
What is VPN?

A VPN is a service that offers secure, reliable connectivity over a shared public network infrastructure such as the Internet. VPNs maintain the same security and management policies as a private network. They are the most cost effective method of establishing a virtual point-to-point connection between remote users and an enterprise customer's network.
How would you define IP address?

IP address or Internet Protocol address is the address of a device attached to an IP network (TCP/IP network). It is a must for every client, server and network device to have a unique IP address for each network connection (network interface). Every IP packet contains a source IP address and a destination IP address. As a device moves from one network to another, its IP address changes.
Computers using the TCP/IP for communication are uniquely identified by a 32 bit address called as an IP address. The routers use the IP address information to forward the packet to the destination computer.

IP addresses are categorized as:

Private address: these IP addresses are used exclusively within a private network and not for public to see.

Public Address: these are registered IP addresses used for public.

Each IP address has a network address and a host address. IP addresses are expressed in four sets of three numbers, separated with dots. Each set is called as an octet because when converted to binary; it denotes eight binary.

Difference between Static and Dynamic IP.
Static IP is also called as permanent address assigned to each device in a network, whereas Dynamic IP, a temporary address assigned to the device via DHCP software. IP address assigned to your service by your cable or DSL Internet provider is typically dynamic IP. In routers and operating systems, the default configuration for clients is dynamic IP

What is Network Address Translation?
Network Address Translation acts as an agent between the Internet and a local network. It is a dynamic method which is used to minimize Internet connectivity needs. Network address translation describes the rewriting of the Internet Protocol (IP) addresses of data packets so that multiple transmissions require only one IP address
What is subneting?

Subnet adds one level to the way IP address is represented. It logically organizes the network. For instance, it can logically group computers belongs to the finance department.
Define Address Resolution Protocol.

Address Resolution Protocol ARP, is responsible for mapping an IP address to its corresponding physical network address. It is mostly seen on Ethernet network.
Explain Maximum Transfer Unit, MTU.

MTU specifies the largest amount of data that can be transferred across a network

What is Routing Protocol?

Routing protocol is the way to send routing information between any routers in an autonomous system.
When a source sends a packet to a destination, this packet has a specific path or route it follows. Different routing protocols are used to find the shortest path to the destination. The protocols maintain routing tables. Routing tables consist of a set of rules used to determine where these packets will travel. When a packet is received, a network device examines the packet and matches it to the routing table entry providing the best match for its destination. The packet keeps hopping until it reaches its destination.
Define broadcast domain.

It is a logical area in a computer network where any computer connected to the network can directly transmit to any other computer in the domain without having to go through a routing device.

C Aptitude Questions and Answers

Predict the output or error(s) for the following:
1. void main()
{
int const * p=5;
printf("%d",++(*p));
}

Answer:
Compiler error: Cannot modify a constant value.
Explanation:
p is a pointer to a "constant integer". But we tried to change the value of the "constant integer".

2. main()
{
char s[ ]="man";
int i;
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}

Answer:
mmmm
aaaa
nnnn
Explanation:
s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. Generally array name is the base address for that array. Here s is the base address. i is the index number/displacement from the base address. So, indirecting it with * is same as s[i]. i[s] may be surprising. But in the case of C it is same as s[i].

3. main()
{
float me = 1.1;
double you = 1.1;
if(me==you)
printf("I love U");
else
printf("I hate U");
}

Answer:
I hate U

Explanation:
For floating point numbers (float, double, long double) the values cannot be predicted exactly. Depending on the number of bytes, the precession with of the value represented varies. Float takes 4 bytes and long double takes 10 bytes. So float stores 0.9 with less precision than long double.
Rule of Thumb:
Never compare or at-least be cautious when using floating point numbers with relational operators (== , >, <, <=, >=,!= ) .

4. main()
{
static int var = 5;
printf("%d ",var--);
if(var)
main();
}

Answer:
5 4 3 2 1

Explanation:
When static storage class is given, it is initialized once. The change in the value of a static variable is retained even between the function calls. Main is also treated like any other ordinary function, which can be called recursively.

5. main()
{
int c[ ]={2.8,3.4,4,6.7,5};
int j,*p=c,*q=c;
for(j=0;j<5;j++) {
printf(" %d ",*c);
++q; }
for(j=0;j<5;j++){
printf(" %d ",*p);
++p; }
}

Answer:
2 2 2 2 2 2 3 4 6 5

Explanation:
Initially pointer c is assigned to both p and q. In the first loop, since only q is incremented and not c , the value 2 will be printed 5 times. In second loop p itself is incremented. So the values 2 3 4 6 5 will be printed.

6. main()
{
extern int i;
i=20;
printf("%d",i);
}

Answer:
Linker Error : Undefined symbol '_i'
Explanation:
extern storage class in the following declaration,
extern int i;
specifies to the compiler that the memory for i is allocated in some other program and that address will be given to the current program at the time of linking. But linker finds that no other variable of name i is available in any other program with memory space allocated for it. Hence a linker error has occurred .
7. main()
{
int i=-1,j=-1,k=0,l=2,m;
m=i++&&j++&&k++||l++;
printf("%d %d %d %d %d",i,j,k,l,m);
}

Answer:
0 0 1 3 1

Explanation :
Logical operations always give a result of 1 or 0 . And also the logical AND (&&) operator has higher priority over the logical OR (||) operator. So the expression ‘i++ && j++ && k++’ is executed first. The result of this expression is 0 (-1 && -1 && 0 = 0). Now the expression is 0 || 2 which evaluates to 1 (because OR operator always gives 1 except for ‘0 || 0’ combination- for which it gives 0). So the value of m is 1. The values of other variables are also incremented by 1.

8. main()
{
char *p;
printf("%d %d ",sizeof(*p),sizeof(p));
}

Answer:
1 2

Explanation:
The sizeof() operator gives the number of bytes taken by its operand. P is a character pointer, which needs one byte for storing its value (a character). Hence sizeof(*p) gives a value of 1. Since it needs two bytes to store the address of the character pointer sizeof(p) gives 2.

9. main()
{
int i=3;
switch(i)
{
default:printf("zero");
case 1: printf("one");
break;
case 2:printf("two");
break;
case 3: printf("three");
break;
}
}

Answer :
three

Explanation :
The default case can be placed anywhere inside the loop. It is executed only when all other cases doesn't match.

10. main()
{
printf("%x",-1<<4);
}

Answer:
fff0

Explanation :
-1 is internally represented as all 1's. When left shifted four times the least significant 4 bits are filled with 0's.The %x format specifier specifies that the integer value be printed as a hexadecimal value.

11. main()
{
char string[]="Hello World";
display(string);
}
void display(char *string)
{
printf("%s",string);
}

Answer:
Compiler Error : Type mismatch in redeclaration of function display

Explanation :
In third line, when the function display is encountered, the compiler doesn't know anything about the function display. It assumes the arguments and return types to be integers, (which is the default type). When it sees the actual function display, the arguments and type contradicts with what it has assumed previously. Hence a compile time error occurs.

12. main()
{
int c=- -2;
printf("c=%d",c);
}

Answer:
c=2;

Explanation:
Here unary minus (or negation) operator is used twice. Same maths rules applies, ie. minus * minus= plus.
Note:
However you cannot give like --2. Because -- operator can only be applied to variables as a decrement operator (eg., i--). 2 is a constant and not a variable.

13. #define int char
main()
{
int i=65;
printf("sizeof(i)=%d",sizeof(i));
}

Answer:
sizeof(i)=1

Explanation:
Since the #define replaces the string int by the macro char

14. main()
{
int i=10;
i=!i>14;
Printf ("i=%d",i);
}

Answer:
i=0

Explanation:
In the expression !i>14 , NOT (!) operator has more precedence than ‘ >’ symbol. ! is a unary logical operator. !i (!10) is 0 (not of true is false). 0>14 is false (zero).
15. #include
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}

Answer:
77

Explanation:
p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10, which is then incremented to 11. The value of ++*p is 11. ++*str1, str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98.
Now performing (11 + 98 – 32), we get 77("M");
So we get the output 77 :: "M" (Ascii is 77).

16. #include
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d----%d",*p,*q);
}

Answer:
SomeGarbageValue---1

Explanation:
p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. Now q is pointing to starting address of a. If you print *q, it will print first element of 3D array.

17. #include
main()
{
struct xx
{
int x=3;
char name[]="hello";
};
struct xx *s;
printf("%d",s->x);
printf("%s",s->name);
}

Answer:
Compiler Error

Explanation:
You should not initialize variables in declaration

18. #include
main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
};
struct yy *q;
};
}

Answer:
Compiler Error

Explanation:
The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created after defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member.

19. main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}

Answer:
hai

Explanation:
\n - newline
\b - backspace
\r - linefeed

20. main()
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}

Answer:
45545

Explanation:
The arguments in a function call are pushed into the stack from left to right. The evaluation is by popping out from the stack. and the evaluation is from right to left, hence the result.

21. #define square(x) x*x
main()
{
int i;
i = 64/square(4);
printf("%d",i);
}

Answer:
64

Explanation:
the macro call square(4) will substituted by 4*4 so the expression becomes i = 64/4*4 . Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e. 16*4 = 64

22. main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
}

Answer:
ibj!gsjfoet

Explanation:
++*p++ will be parse in the given order
Ø *p that is value at the location currently pointed by p will be taken
Ø ++*p the retrieved value will be incremented
Ø when ; is encountered the location will be incremented that is p++ will be executed
Hence, in the while loop initial value pointed by p is ‘h’, which is changed to ‘i’ by executing ++*p and pointer moves to point, ‘a’ which is similarly changed to ‘b’ and so on. Similarly blank space is converted to ‘!’. Thus, we obtain value in p becomes “ibj!gsjfoet” and since p reaches ‘\0’ and p1 points to p thus p1doesnot print anything.

23. #include
#define a 10
main()
{
#define a 50
printf("%d",a);
}

Answer:
50

Explanation:
The preprocessor directives can be redefined anywhere in the program. So the most recently assigned value will be taken.

24. #define clrscr() 100
main()
{
clrscr();
printf("%d\n",clrscr());
}

Answer:
100

Explanation:
Preprocessor executes as a seperate pass before the execution of the compiler. So textual replacement of clrscr() to 100 occurs.The input program to compiler looks like this :
main()
{
100;
printf("%d\n",100);
}
Note:
100; is an executable statement but with no action. So it doesn't give any problem

25. main()
{
printf("%p",main);
}

Answer:
Some address will be printed.

Explanation:
Function names are just addresses (just like array names are addresses).
main() is also a function. So the address of function main will be printed. %p in printf specifies that the argument is an address. They are printed as hexadecimal numbers.

26. main()
{
clrscr();
}
clrscr();

Answer:
No output/error

Explanation:
The first clrscr() occurs inside a function. So it becomes a function call. In the second clrscr(); is a function declaration (because it is not inside any function).

27. enum colors {BLACK,BLUE,GREEN}
main()
{

printf("%d..%d..%d",BLACK,BLUE,GREEN);

return(1);
}

Answer:
0..1..2

Explanation:
enum assigns numbers starting from 0, if not explicitly defined.

28. void main()
{
char far *farther,*farthest;

printf("%d..%d",sizeof(farther),sizeof(farthest));

}

Answer:
4..2

Explanation:
the second pointer is of char type and not a far pointer

29. main()
{
int i=400,j=300;
printf("%d..%d");
}

Answer:
400..300

Explanation:
printf takes the values of the first two assignments of the program. Any number of printf's may be given. All of them take only the first two values. If more number of assignments given in the program, then printf will take garbage values.

30. main()
{
char *p;
p="Hello";
printf("%c\n",*&*p);
}

Answer:
H

Explanation:
* is a dereference operator & is a reference operator. They can be applied any number of times provided it is meaningful. Here p points to the first character in the string "Hello". *p dereferences it and so its value is H. Again & references it to an address and * dereferences it to the value H.

31. main()
{
int i=1;
while (i<=5)
{
printf("%d",i);
if (i>2)
goto here;
i++;
}
}
fun()
{
here:
printf("PP");
}

Answer:
Compiler error: Undefined label 'here' in function main

Explanation:
Labels have functions scope, in other words The scope of the labels is limited to functions . The label 'here' is available in function fun() Hence it is not visible in function main.

32. main()
{
static char names[5][20]={"pascal","ada","cobol","fortran","perl"};
int i;
char *t;
t=names[3];
names[3]=names[4];
names[4]=t;
for (i=0;i<=4;i++)
printf("%s",names[i]);
}

Answer:
Compiler error: Lvalue required in function main

Explanation:
Array names are pointer constants. So it cannot be modified.

33. void main()
{
int i=5;
printf("%d",i++ + ++i);
}

Answer:
Output Cannot be predicted exactly.

Explanation:
Side effects are involved in the evaluation of i

34. void main()
{
int i=5;
printf("%d",i+++++i);
}

Answer:
Compiler Error

Explanation:
The expression i+++++i is parsed as i ++ ++ + i which is an illegal combination of operators.

35. #include
main()
{
int i=1,j=2;
switch(i)
{
case 1: printf("GOOD");
break;
case j: printf("BAD");
break;
}
}

Answer:
Compiler Error: Constant expression required in function main.

Explanation:
The case statement can have only constant expressions (this implies that we cannot use variable names directly so an error).
Note:
Enumerated types can be used in case statements.
36. main()
{
int i;
printf("%d",scanf("%d",&i)); // value 10 is given as input here
}

Answer:
1

Explanation:
Scanf returns number of items successfully read and not 1/0. Here 10 is given as input which should have been scanned successfully. So number of items read is 1.

37. #define f(g,g2) g##g2
main()
{
int var12=100;
printf("%d",f(var,12));
}

Answer:
100

38. main()
{
int i=0;

for(;i++;printf("%d",i)) ;
printf("%d",i);
}

Answer:
1

Explanation:
before entering into the for loop the checking condition is "evaluated". Here it evaluates to 0 (false) and comes out of the loop, and i is incremented (note the semicolon after the for loop).

39. #include
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}

Answer:
M

Explanation:
p is pointing to character '\n'.str1 is pointing to character 'a' ++*p meAnswer:"p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10. then it is incremented to 11. the value of ++*p is 11. ++*str1 meAnswer:"str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98. both 11 and 98 is added and result is subtracted from 32.
i.e. (11+98-32)=77("M");

40. #include
main()
{
struct xx
{
int x=3;
char name[]="hello";
};
struct xx *s=malloc(sizeof(struct xx));
printf("%d",s->x);
printf("%s",s->name);
}

Answer:
Compiler Error

Explanation:
Initialization should not be done for structure members inside the structure declaration

41. #include
main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
};
struct yy *q;
};
}

Answer:
Compiler Error

Explanation:
in the end of nested structure yy a member have to be declared

42. main()
{
extern int i;
i=20;
printf("%d",sizeof(i));
}

Answer:
Linker error: undefined symbol '_i'.

Explanation:
extern declaration specifies that the variable i is defined somewhere else. The compiler passes the external variable to be resolved by the linker. So compiler doesn't find an error. During linking the linker searches for the definition of i. Since it is not found the linker flags an error.

43. main()
{
printf("%d", out);
}

int out=100;
Answer:
Compiler error: undefined symbol out in function main.

Explanation:
The rule is that a variable is available for use from the point of declaration. Even though a is a global variable, it is not available for main. Hence an error.
4. main()
{
extern out;
printf("%d", out);
}
int out=100;

Answer:
100

Explanation:
This is the correct way of writing the previous program.

45. main()
{
show();
}
void show()
{
printf("I'm the greatest");
}

Answer:
Compier error: Type mismatch in redeclaration of show.

Explanation:
When the compiler sees the function show it doesn't know anything about it. So the default return type (ie, int) is assumed. But when compiler sees the actual definition of show mismatch occurs since it is declared as void. Hence the error.
The solutions are as follows:
1. declare void show() in main() .
2. define show() before main().
3. declare extern void show() before the use of show().

46. main( )
{
int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}};
printf(“%u %u %u %d \n”,a,*a,**a,***a);
printf(“%u %u %u %d \n”,a+1,*a+1,**a+1,***a+1);
}

Answer:
100, 100, 100, 2
114, 104, 102, 3

47. main( )
{
int a[ ] = {10,20,30,40,50},j,*p;
for(j=0; j<5; j++)
{
printf(“%d” ,*a);
a++;
}
p = a;
for(j=0; j<5; j++)
{
printf(“%d ” ,*p);
p++;
}
}

Answer:
Compiler error: lvalue required.

Explanation:
Error is in line with statement a++. The operand must be an lvalue and may be of any of scalar type for the any operator, array name only when subscripted is an lvalue. Simply array name is a non-modifiable lvalue.

48. main( )
{
static int a[ ] = {0,1,2,3,4};
int *p[ ] = {a,a+1,a+2,a+3,a+4};
int **ptr = p;
ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
*ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
*++ptr;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
++*ptr;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
}

Answer:
111
222
333
344

49. main( )
{
void *vp;
char ch = ‘g’, *cp = “goofy”;
int j = 20;
vp = &ch;
printf(“%c”, *(char *)vp);
vp = &j;
printf(“%d”,*(int *)vp);
vp = cp;
printf(“%s”,(char *)vp + 3);
}

Answer:
g20fy

Explanation:
Since a void pointer is used it can be type casted to any other type pointer. vp = &ch stores address of char ch and the next statement prints the value stored in vp after type casting it to the proper data type pointer. the output is ‘g’. Similarly the output from second printf is ‘20’. The third printf statement type casts it to print the string from the 4th value hence the output is ‘fy’.

50. main ( )
{
static char *s[ ] = {“black”, “white”, “yellow”, “violet”};
char **ptr[ ] = {s+3, s+2, s+1, s}, ***p;
p = ptr;
**++p;
printf(“%s”,*--*++p + 3);
}

Answer:
ck

Explanation:
In this problem we have an array of char pointers pointing to start of 4 strings. Then we have ptr which is a pointer to a pointer of type char and a variable p which is a pointer to a pointer to a pointer of type char. p hold the initial value of ptr, i.e. p = s+3. The next statement increment value in p by 1 , thus now value of p = s+2. In the printf statement the expression is evaluated *++p causes gets value s+1 then the pre decrement is executed and we get s+1 – 1 = s . the indirection operator now gets the value from the array of s and adds 3 to the starting address. The string is printed starting from this position. Thus, the output is ‘ck’.

51. main()
{
int i, n;
char *x = “girl”;
n = strlen(x);
*x = x[n];
for(i=0; i
{
printf(“%s\n”,x);
x++;
}
}

Answer:
(blank space)
irl
rl
l

Explanation:
Here a string (a pointer to char) is initialized with a value “girl”. The strlen function returns the length of the string, thus n has a value 4. The next statement assigns value at the nth location (‘\0’) to the first location. Now the string becomes “\0irl” . Now the printf statement prints the string after each iteration it increments it starting position. Loop starts from 0 to 4. The first time x[0] = ‘\0’ hence it prints nothing and pointer value is incremented. The second time it prints from x[1] i.e “irl” and the third time it prints “rl” and the last time it prints “l” and the loop terminates.
52. int i,j;
for(i=0;i<=10;i++)
{
j+=5;
assert(i<5);
}

Answer:
Runtime error: Abnormal program termination.
assert failed (i<5), ,

Explanation:
asserts are used during debugging to make sure that certain conditions are satisfied. If assertion fails, the program will terminate reporting the same. After debugging use,
#undef NDEBUG
and this will disable all the assertions from the source code. Assertion
is a good debugging tool to make use of.

53. main()
{
int i=-1;
+i;
printf("i = %d, +i = %d \n",i,+i);
}

Answer:
i = -1, +i = -1

Explanation:
Unary + is the only dummy operator in C. Where-ever it comes you can just ignore it just because it has no effect in the expressions (hence the name dummy operator).

54. What are the files which are automatically opened when a C file is executed?
Answer:
stdin, stdout, stderr (standard input,standard output,standard error).

55. what will be the position of the file marker?
a: fseek(ptr,0,SEEK_SET);
b: fseek(ptr,0,SEEK_CUR);

Answer :
a: The SEEK_SET sets the file position marker to the starting of the file.
b: The SEEK_CUR sets the file position marker to the current position
of the file.

56. main()
{
char name[10],s[12];
scanf(" \"%[^\"]\"",s);
}
How scanf will execute?
Answer:
First it checks for the leading white space and discards it.Then it matches with a quotation mark and then it reads all character upto another quotation mark.

57. What is the problem with the following code segment?
while ((fgets(receiving array,50,file_ptr)) != EOF)
;
Answer & Explanation:
fgets returns a pointer. So the correct end of file check is checking for != NULL.

58. main()
{
main();
}

Answer:
Runtime error : Stack overflow.

Explanation:
main function calls itself again and again. Each time the function is called its return address is stored in the call stack. Since there is no condition to terminate the function call, the call stack overflows at runtime. So it terminates the program and results in an error.

59. main()
{
char *cptr,c;
void *vptr,v;
c=10; v=0;
cptr=&c; vptr=&v;
printf("%c%v",c,v);
}

Answer:
Compiler error (at line number 4): size of v is Unknown.

Explanation:
You can create a variable of type void * but not of type void, since void is an empty type. In the second line you are creating variable vptr of type void * and v of type void hence an error.

60. main()
{
char *str1="abcd";
char str2[]="abcd";
printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd"));
}

Answer:
2 5 5

Explanation:
In first sizeof, str1 is a character pointer so it gives you the size of the pointer variable. In second sizeof the name str2 indicates the name of the array whose size is 5 (including the '\0' termination character). The third sizeof is similar to the second one.

61. main()
{
char not;
not=!2;
printf("%d",not);
}

Answer:
0

Explanation:
! is a logical operator. In C the value 0 is considered to be the boolean value FALSE, and any non-zero value is considered to be the boolean value TRUE. Here 2 is a non-zero value so TRUE. !TRUE is FALSE (0) so it prints 0.

62. #define FALSE -1
#define TRUE 1
#define NULL 0
main() {
if(NULL)
puts("NULL");
else if(FALSE)
puts("TRUE");
else
puts("FALSE");
}

Answer:
TRUE

Explanation:
The input program to the compiler after processing by the preprocessor is,
main(){
if(0)
puts("NULL");
else if(-1)
puts("TRUE");
else
puts("FALSE");
}
Preprocessor doesn't replace the values given inside the double quotes. The check by if condition is boolean value false so it goes to else. In second if -1 is boolean value true hence "TRUE" is printed.
63. main()
{
int k=1;
printf("%d==1 is ""%s",k,k==1?"TRUE":"FALSE");
}

Answer:
1==1 is TRUE

Explanation:
When two strings are placed together (or separated by white-space) they are concatenated (this is called as "stringization" operation). So the string is as if it is given as "%d==1 is %s". The conditional operator( ?: ) evaluates to "TRUE".

64. main()
{
int y;
scanf("%d",&y); // input given is 2000
if( (y%4==0 && y%100 != 0) || y%100 == 0 )
printf("%d is a leap year");
else
printf("%d is not a leap year");
}

Answer:
2000 is a leap year

Explanation:
An ordinary program to check if leap year or not.

65. #define max 5
#define int arr1[max]
main()
{
typedef char arr2[max];
arr1 list={0,1,2,3,4};
arr2 name="name";
printf("%d %s",list[0],name);
}

Answer:
Compiler error (in the line arr1 list = {0,1,2,3,4})

Explanation:
arr2 is declared of type array of size 5 of characters. So it can be used to declare the variable name of the type arr2. But it is not the case of arr1. Hence an error.
Rule of Thumb:
#defines are used for textual replacement whereas typedefs are used for declaring new types.

66. int i=10;
main()
{
extern int i;
{
int i=20;
{
const volatile unsigned i=30;
printf("%d",i);
}
printf("%d",i);
}
printf("%d",i);
}

Answer:
30,20,10

Explanation:
'{' introduces new block and thus new scope. In the innermost block i is declared as,
const volatile unsigned
which is a valid declaration. i is assumed of type int. So printf prints 30. In the next block, i has value 20 and so printf prints 20. In the outermost block, i is declared as extern, so no storage space is allocated for it. After compilation is over the linker resolves it to global variable i (since it is the only variable visible there). So it prints i's value as 10.

67. main()
{
int *j;
{
int i=10;
j=&i;
}
printf("%d",*j);
}

Answer:
10

Explanation:
The variable i is a block level variable and the visibility is inside that block only. But the lifetime of i is lifetime of the function so it lives upto the exit of main function. Since the i is still allocated space, *j prints the value stored in i since j points i.

68. main()
{
int i=-1;
-i;
printf("i = %d, -i = %d \n",i,-i);
}

Answer:
i = -1, -i = 1

Explanation:
-i is executed and this execution doesn't affect the value of i. In printf first you just print the value of i. After that the value of the expression -i = -(-1) is printed.

69. #include
main()
{
const int i=4;
float j;
j = ++i;
printf("%d %f", i,++j);
}

Answer:
Compiler error

Explanation:
i is a constant. you cannot change the value of constant

70. #include
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d..%d",*p,*q);
}

Answer:
garbagevalue..1

Explanation:
p=&a[2][2][2] you declare only two 2D arrays. but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. now q is pointing to starting address of a.if you print *q meAnswer:it will print first element of 3D array.

71. #include
main()
{
register i=5;
char j[]= "hello";
printf("%s %d",j,i);
}

Answer:
hello 5

Explanation:
if you declare i as register compiler will treat it as ordinary integer and it will take integer value. i value may be stored either in register or in memory.

72. main()
{
int i=5,j=6,z;
printf("%d",i+++j);
}

Answer:
11

Explanation:
the expression i+++j is treated as (i++ + j)

Monday, May 24, 2010

C/C++ Aptitude Questions and Answers

Find the output of the following program
class Sample
{
public:
int *ptr;
Sample(int i)
{
ptr = new int(i);
}
~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << "The value is " << *ptr;
} };
void SomeFunc(Sample x) {
cout << "Say i am in someFunc " << s1=" 10;"
bval="0;
}"
dval="1;}"
i="0;"
cout="">< }
int main()
{
base BaseArr[5];
SomeFunc(BaseArr,5);
deri DeriArr[5];
SomeFunc(DeriArr,5);
}
Answer: 00000 01010
Explanation: The function SomeFunc expects two arguments.The first one is a pointer to an array of base class objects and the second one is the sizeof the array.The first call of someFunc calls it with an array of bae objects, so it works correctly and prints the bval of all the objects. When Somefunc is called the second time the argument passed is the pointeer to an array of derived class objects and not the array of base class objects. But that is what the function expects to be sent. So the derived class pointer is promoted to base class pointer and the address is sent to the function. SomeFunc() knows nothing about this and just treats the pointer as an array of base class objects. So when arr++ is met, the size of base class object is taken into consideration and is incremented by sizeof(int) bytes for bval (the deri class objects have bval and dval as members and so is of size >= sizeof(int)+sizeof(int) ).

Find the output of the following program
class base
{
public:void baseFun()
{
cout<<"from base"<
};
class deri:public base
{
public: void baseFun()
{
cout<< "from derived"<
};
void SomeFunc(base *baseObj)
{ baseObj->baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
deri deriObject;
SomeFunc(&deriObject);
}

Answer:
from base
from base

Explanation:
As we have seen in the previous case, SomeFunc expects a pointer to a base class. Since a pointer to a derived class object is passed, it treats the argument only as a base class pointer and the corresponding base function is called.

Find the output of the following program
class base
{
public:
virtual void baseFun()
{
cout<<"from base"<
};
class deri:public base
{
public: void baseFun()
{
cout<< "from derived"<
};
void SomeFunc(base *baseObj)
{
baseObj->baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
deri deriObject;
SomeFunc(&deriObject);
}

Answer:
from base
from derived

Explanation:
Remember that baseFunc is a virtual function. That means that it supports run-time polymorphism. So the function corresponding to the derived class object is called.



What is a node class?
A node class is a class that,
  • relies on the base class for services and implementation,
  • provides a wider interface to te users than its base class,
  • relies primarily on virtual functions in its public interface
  • depends on all its direct and indirect base class
  • can be understood only in the context of the base class
  • can be used as base for further derivation
  • can be used to create objects.
A node class is a class that has added new services or functionality beyond the services inherited from its base class.

What is an orthogonal base class?
If two base classes have no overlapping methods or data they are said to be independent of, or orthogonal to each other. Orthogonal in the sense means that two classes operate in different dimensions and do not interfere with each other in any way. The same derived class may inherit such classes with no difficulty.

What is a container class? What are the types of container classes?
A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.
What is a protocol class?
An abstract class is a protocol class if:
Ø it neither contains nor inherits from classes that contain member data, non-virtual functions, or private (or protected) members of any kind.
Ø it has a non-inline virtual destructor defined with an empty implementation,
Ø all member functions other than the destructor including inherited functions, are declared pure virtual functions and left undefined.

What is a mixin class?
A class that provides some but not all of the implementation for a virtual base class is often called mixin. Derivation done just for the purpose of redefining the virtual functions in the base classes is often called mixin inheritance. Mixin classes typically don't share common bases.

What is a concrete class?
A concrete class is used to define a useful object that can be instantiated as an automatic variable on the program stack. The implementation of a concrete class is defined. The concrete class is not intended to be a base class and no attempt to minimize dependency on other classes in the implementation or behavior of the class.

What is the handle class?
A handle is a class that maintains a pointer to an object that is programmatically accessible through the public interface of the handle class.
Explanation:
In case of abstract classes, unless one manipulates the objects of these classes through pointers and references, the benefits of the virtual functions are lost. User code may become dependent on details of implementation classes because an abstract type cannot be allocated statistically or on the stack without its size being known. Using pointers or references implies that the burden of memory management falls on the user. Another limitation of abstract class object is of fixed size. Classes however are used to represent concepts that require varying amounts of storage to implement them.
A popular technique for dealing with these issues is to separate what is used as a single object in two parts: a handle providing the user interface and a representation holding all or most of the object's state. The connection between the handle and the representation is typically a pointer in the handle. Often, handles have a bit more data than the simple representation pointer, but not much more. Hence the layout of the handle is typically stable, even when the representation changes and also that handles are small enough to move around relatively freely so that the user needn’t use the pointers and the references.

What is an action class?
The simplest and most obvious way to specify an action in C++ is to write a function. However, if the action has to be delayed, has to be transmitted 'elsewhere' before being performed, requires its own data, has to be combined with other actions, etc then it often becomes attractive to provide the action in the form of a class that can execute the desired action and provide other services as well. Manipulators used with iostreams is an obvious example.
Explanation:
A common form of action class is a simple class containing just one virtual function.
class Action
{
public:
virtual int do_it( int )=0;
virtual ~Action( );
}
Given this, we can write code say a member that can store actions for later execution without using pointers to functions, without knowing anything about the objects involved, and without even knowing the name of the operation it invokes. For example:
class write_file : public Action
{
File& f;
public:
int do_it(int)
{
return fwrite( ).suceed( );
}
};
class error_message: public Action
{
response_box db(message.cstr( ),"Continue","Cancel","Retry");
switch (db.getresponse( ))
{
case 0: return 0;
case 1: abort();
case 2: current_operation.redo( );return 1;
}
};

A user of the Action class will be completely isolated from any knowledge of derived classes such as write_file and error_message.

When can you tell that a memory leak will occur?
A memory leak occurs when a program loses the ability to free a block of dynamically allocated memory.

What is a parameterized type?
A template is a parameterized construct or type containing generic code that can use or manipulate any type. It is called parameterized because an actual type is a parameter of the code body. Polymorphism may be achieved through parameterized types. This type of polymorphism is called parameteric polymorphism. Parameteric polymorphism is the mechanism by which the same code is used on different types passed as parameters.

Differentiate between a deep copy and a shallow copy?
Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain ht same information but the target object will have its own buffers and resources. the destruction of either object will not affect the remaining object. The overloaded assignment operator would create a deep copy of objects.
Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable.
Explanation:
Using a copy constructor we simply copy the data values member by member. This method of copying is called shallow copy. If the object is a simple class, comprised of built in types and no pointers this would be acceptable. This function would use the values and the objects and its behavior would not be altered with a shallow copy, only the addresses of pointers that are members are copied and not the value the address is pointing to. The data values of the object would then be inadvertently altered by the function. When the function goes out of scope, the copy of the object with all its data is popped off the stack.
If the object has any pointers a deep copy needs to be executed. With the deep copy of an object, memory is allocated for the object in free store and the elements pointed to are copied. A deep copy is used for objects that are returned from a function.
What is an opaque pointer?
A pointer is said to be opaque if the definition of the type to which it points to is not included in the current translation unit. A translation unit is the result of merging an implementation file with all its headers and header files.

What is a smart pointer?
A smart pointer is an object that acts, looks and feels like a normal pointer but offers more functionality. In C++, smart pointers are implemented as template classes that encapsulate a pointer and override standard pointer operators. They have a number of advantages over regular pointers. They are guaranteed to be initialized as either null pointers or pointers to a heap object. Indirection through a null pointer is checked. No delete is ever necessary. Objects are automatically freed when the last pointer to them has gone away. One significant problem with these smart pointers is that unlike regular pointers, they don't respect inheritance. Smart pointers are unattractive for polymorphic code. Given below is an example for the implementation of smart pointers.
Example:
template
class smart_pointer
{
public:
smart_pointer(); // makes a null pointer
smart_pointer(const X& x) // makes pointer to copy of x

X& operator *( );
const X& operator*( ) const;
X* operator->() const;

smart_pointer(const smart_pointer &);
const smart_pointer & operator =(const smart_pointer&);
~smart_pointer();
private:
//...
};
This class implement a smart pointer to an object of type X. The object itself is located on the heap. Here is how to use it:
smart_pointer p= employee("Harris",1333);
Like other overloaded operators, p will behave like a regular pointer,
cout<<*p; p->raise_salary(0.5);

What is reflexive association?
The 'is-a' is called a reflexive association because the reflexive association permits classes to bear the is-a association not only with their super-classes but also with themselves. It differs from a 'specializes-from' as 'specializes-from' is usually used to describe the association between a super-class and a sub-class. For example:
Printer is-a printer.

What is slicing?
Slicing means that the data added by a subclass are discarded when an object of the subclass is passed or returned by value or from a function expecting a base class object.
Explanation:
Consider the following class declaration:
class base
{
...
base& operator =(const base&);
base (const base&);
}
void fun( )
{
base e=m;
e=m;
}
As base copy functions don't know anything about the derived only the base part of the derived is copied. This is commonly referred to as slicing. One reason to pass objects of classes in a hierarchy is to avoid slicing. Other reasons are to preserve polymorphic behavior and to gain efficiency.

What is name mangling?
Name mangling is the process through which your c++ compilers give each function in your program a unique name. In C++, all programs have at-least a few functions with the same name. Name mangling is a concession to the fact that linker always insists on all function names being unique.
Example:
In general, member names are made unique by concatenating the name of the member with that of the class e.g. given the declaration:
class Bar
{
public:
int ival;
...
};
ival becomes something like:
// a possible member name mangling
ival__3Bar
Consider this derivation:
class Foo : public Bar
{
public:
int ival;
...
}
The internal representation of a Foo object is the concatenation of its base and derived class members.
// Pseudo C++ code
// Internal representation of Foo
class Foo
{
public:
int ival__3Bar;
int ival__3Foo;
...
};
Unambiguous access of either ival members is achieved through name mangling. Member functions, because they can be overloaded, require an extensive mangling to provide each with a unique name. Here the compiler generates the same name for the two overloaded instances(Their argument lists make their instances unique).

What are proxy objects?
Objects that points to other objects are called proxy objects or surrogates. Its an object that provides the same interface as its server object but does not have any functionality. During a method invocation, it routes data to the true server object and sends back the return value to the object.
Differentiate between declaration and definition in C++.
A declaration introduces a name into the program; a definition provides a unique description of an entity (e.g. type, instance, and function). Declarations can be repeated in a given scope, it introduces a name in a given scope. There must be exactly one definition of every object, function or class used in a C++ program.
A declaration is a definition unless:
Ø it declares a function without specifying its body,
Ø it contains an extern specifier and no initializer or function body,
Ø it is the declaration of a static class data member without a class definition,
Ø it is a class name definition,
Ø it is a typedef declaration.
A definition is a declaration unless:
Ø it defines a static class data member,
Ø it defines a non-inline member function.

What is cloning?
An object can carry out copying in two ways i.e. it can set itself to be a copy of another object, or it can return a copy of itself. The latter process is called cloning.

Describe the main characteristics of static functions.
The main characteristics of static functions include,
Ø It is without the a this pointer,
Ø It can't directly access the non-static members of its class
Ø It can't be declared const, volatile or virtual.
Ø It doesn't need to be invoked through an object of its class, although for convenience, it may.

Will the inline function be compiled as the inline function always? Justify.
An inline function is a request and not a command. Hence it won't be compiled as an inline function always.
Explanation:
Inline-expansion could fail if the inline function contains loops, the address of an inline function is used, or an inline function is called in a complex expression. The rules for inlining are compiler dependent.

Define a way other than using the keyword inline to make a function inline.
The function must be defined inside the class.

How can a '::' operator be used as unary operator?
The scope operator can be used to refer to members of the global namespace. Because the global namespace doesn’t have a name, the notation :: member-name refers to a member of the global namespace. This can be useful for referring to members of global namespace whose names have been hidden by names declared in nested local scope. Unless we specify to the compiler in which namespace to search for a declaration, the compiler simple searches the current scope, and any scopes in which the current scope is nested, to find the declaration for the name.

What is placement new?
When you want to call a constructor directly, you use the placement new. Sometimes you have some raw memory that's already been allocated, and you need to construct an object in the memory you have. Operator new's special version placement new allows you to do it.
class Widget
{
public :
Widget(int widgetsize);
...
Widget* Construct_widget_int_buffer(void *buffer,int widgetsize)
{
return new(buffer) Widget(widgetsize);
}
};
This function returns a pointer to a Widget object that's constructed within the buffer passed to the function. Such a function might be useful for applications using shared memory or memory-mapped I/O, because objects in such applications must be placed at specific addresses or in memory allocated by special routines.

OOAD
What do you mean by analysis and design?
Analysis:
Basically, it is the process of determining what needs to be done before how it should be done. In order to accomplish this, the developer refers the existing systems and documents. So, simply it is an art of discovery.
Design:
It is the process of adopting/choosing the one among the many, which best accomplishes the users needs. So, simply, it is compromising mechanism.

What are the steps involved in designing?
Before getting into the design the designer should go through the SRS prepared by the System Analyst.
The main tasks of design are Architectural Design and Detailed Design.
In Architectural Design we find what are the main modules in the problem domain.
In Detailed Design we find what should be done within each module.

What are the main underlying concepts of object orientation?
Objects, messages, class, inheritance and polymorphism are the main concepts of object orientation.

What do u meant by "SBI" of an object?
SBI stands for State, Behavior and Identity. Since every object has the above three.
Ø State:
It is just a value to the attribute of an object at a particular time.
Ø Behaviour:
It describes the actions and their reactions of that object.
Ø Identity:
An object has an identity that characterizes its own existence. The identity makes it possible to distinguish any object in an unambiguous way, and independently from its state.
Differentiate persistent & non-persistent objects?
Persistent refers to an object's ability to transcend time or space. A persistent object stores/saves its state in a permanent storage system with out losing the information represented by the object.
A non-persistent object is said to be transient or ephemeral. By default objects are considered as non-persistent.

What do you meant by active and passive objects?
Active objects are one which instigate an interaction which owns a thread and they are responsible for handling control to other objects. In simple words it can be referred as client.
Passive objects are one, which passively waits for the message to be processed. It waits for another object that requires its services. In simple words it can be referred as server.

What is meant by software development method?
Software development method describes how to model and build software systems in a reliable and reproducible way. To put it simple, methods that are used to represent ones' thinking using graphical notations.

What are models and meta models?
Model:
It is a complete description of something (i.e. system).
Meta model:
It describes the model elements, syntax and semantics of the notation that allows their manipulation.

What do you meant by static and dynamic modeling?
Static modeling is used to specify structure of the objects that exist in the problem domain. These are expressed using class, object and USECASE diagrams.
But Dynamic modeling refers representing the object interactions during runtime. It is represented by sequence, activity, collaboration and statechart diagrams.

Why generalization is very strong?
Even though Generalization satisfies Structural, Interface, Behaviour properties. It is mathematically very strong, as it is Antisymmetric and Transitive.
Antisymmetric: employee is a person, but not all persons are employees. Mathematically all As’ are B, but all Bs’ not A.
Transitive: A=>B, B=>c then A=>c.
A. Salesman.
B. Employee.
C. Person.
Note: All the other relationships satisfy all the properties like Structural properties, Interface properties, Behavior properties.

Differentiate Aggregation and containment?
Aggregation is the relationship between the whole and a part. We can add/subtract some properties in the part (slave) side. It won't affect the whole part.
Best example is Car, which contains the wheels and some extra parts. Even though the parts are not there we can call it as car.
But, in the case of containment the whole part is affected when the part within that got affected. The human body is an apt example for this relationship. When the whole body dies the parts (heart etc) are died.

Can link and Association applied interchangeably?
No, You cannot apply the link and Association interchangeably. Since link is used represent the relationship between the two objects.
But Association is used represent the relationship between the two classes.
link :: student:Abhilash course:MCA
Association:: student course

what is meant by "method-wars"?
Before 1994 there were different methodologies like Rumbaugh, Booch, Jacobson, Meyer etc who followed their own notations to model the systems. The developers were in a dilemma to choose the method which best accomplishes their needs. This particular span was called as "method-wars"

Whether unified method and unified modeling language are same or different?
Unified method is convergence of the Rumbaugh and Booch.
Unified modeling lang. is the fusion of Rumbaugh, Booch and Jacobson as well as Betrand Meyer (whose contribution is "sequence diagram"). Its' the superset of all the methodologies.

Who were the three famous amigos and what was their contribution to the object community?
The Three amigos namely,
Ø James Rumbaugh (OMT): A veteran in analysis who came up with an idea about the objects and their Relationships (in particular Associations).
Ø Grady Booch: A veteran in design who came up with an idea about partitioning of systems into subsystems.

Ø Ivar Jacobson (Objectory): The father of USECASES, who described about the user and system interaction.

Why does the function arguments are called as "signatures"?
The arguments distinguish functions with the same name (functional polymorphism). The name alone does not necessarily identify a unique function. However, the name and its arguments (signatures) will uniquely identify a function.
In real life we see suppose, in class there are two guys with same name, but they can be easily identified by their signatures. The same concept is applied here.
ex:
class person
{
public:
char getsex();
void setsex(char);
void setsex(int);
};
In the above example we see that there is a function setsex() with same name but with different signature.