Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Tuesday, April 15, 2008

Q & A on Teoretical ANalysis of Router Systems

Q: Simple IP routers have only one FIFO (First-in-first-out first-come-first-served) queue for the packets. That has the drawback that some users may achieve much higher data rate than others, for example if their packets are long in average, if their TCP sessions have long duration, and thus they avoid TCP slow-start, and if the IP packets only traverse a few routers. That is not fair. To address this problem, modern routers support fair packet scheduling algorithms, such as the Weighted Fair Queuing algorithm. This means that each flow (=stream=session) of IP packets has its own FIFO queue, instead of one common FIFO queue. If we only consider best-effort traffic (without QoS guarantees), then the router controls that backlogged flows (with at least on packet in queue) get equal bit rate, independently of packet sizes, TCP session durations, number of passed routers, etc. If we consider several routers, all flows do not achieve equal bandwith, but the minimum bandwith that a user can achieve is maximized. This is called max-min fairness. (I hope my terminology is correct.)

A flow is identified as a unique combination of source and destination IP address and TCP port number. This mean that a user who simultaneously communicates with N different hosts, or N different TCP ports, will achieve N times higher data rate than a user who communicates with only one host and one TCP port. I.M.O., that is not fair. I think that if several packets goes to [from] the same IP host, and that host is situated in the same (sub)net as the IP router, then they should be considered as the same flow irrespectively of the source [destination] and the TCP port numbers. I haven't seen any discussion about it in scientific papers, or in CISCO knowledge database, so I guess that CISCO routers do not support this. Do you have some idea why?

In the academic world, a lot of other fair resource sharing algorithms are studied, such as deficit round robin, and algorithms for proportional fairness. Do you know if these algorithms are supported by routers existing on the market today?

A: You are correct that the academic world is overrun with theoretical studies of packet scheduling and traffic engineering. Researchers in the area of Performance Evaluation have had little impact in operating systems and databases; now they are applying the same techniques to networks. In fact, everyone I know who used to write papers on performance of something is now writing papers on performance of networks. Recently, I had a visitor in my office who told me he was shocked to discover that the academic work was almost completely ignored by industry -- engineers bulding switches and routers didn't find that the analysis worked in practice.

So, you are discussing a few details, when the important question is whether the whole scheme is worthwhile. Many of us in networking think that it is not -- scheduling will NEVER be a satisfactory solution to the resource problme. The notion of ``equal pain'' didn't work for operating systems, doesn't work for automobile traffic, and it won't work for networks. The only viable long-term solution is increasing resources (the ``big bandwidth'' solution).

Q & A on Application Level Gateways,

Q: Please could you help me understand this - how do application (level) gateways work?

A: An application gateway is a running program that connects two or more (heterogeneous) distributed systems. For example, one type of application gateway is used to connect heterogeneous e-mail systems. To understand the motivation, assume that you work for a company that runs proprietary e-mail software internally. If the company wants to send e-mail across the Internet, it must format the message according to the Internet standard and must use standard Internet protocols to transfer the messahe. An application gateway can be placed between the two -- the gateway accepts outgoing mail in the proprietary format, reformats it to use the Internet standard, and sends it. Similarly, the application gateway accepts all incoming e-mail, reformats it to use the proprietary system, and forwards each message to the appropriate recipient using the proprietary e-mail system.

Q: How are they related to ip packet filtering.

A: Application gateways are seldom used to perform packet filtering because the overhead is high (each packet must be transferred from inside the operating system to the application gateway and back into the operating system for transmission, and there is usually a context switch as well). Thus, most packet filtering is performed by a router or by protocol software inside an operating system.

Q & A on Ethernet Transceivers and "10BaseT",

Q: I had a few questions regarding ethernet ..

Unlike thicknet, thinnet and twisted pair do not have a explicit transceiver - dont they require one or it is in the NIC(for thinnet) or hub for twisted pair

A: You are correct, thinnet and twisted pair do not have an external transceiver. The necessary transmission hardware is part of the network interface card (NIC) for thinnet. In twisted pair Ethernet, the hub contains active electronics that can amplify and retransmit signals. Thus, the NIC in a given computer only needs to propagate the signal as far as the hub.

Q: Why is 10Base-T called so

A: The "10" stands for the transfer rate of 10 megabits per second. The "T" stands for twisted pair. Thicknet, which has a maximum cable segment length of 500 meters, is named 10Base-5, and thinnet, which has a maximum cable length of 200 meters is named 10Base-2. (Note: the names can be written without the dash).

Q: In Twisted pair - we refer to the logical topology as a BUS but the physical topology is Star - have I got it right.

A: Yes. The original Ethernet was, of course, both a physical and logical bus -- a single cable comprised the medium over which signals were transmitted. From the point of view of an attached computer, twisted pair Ethernet appears logically to be exactly the same as a single cable (i.e., twisted pair Ethernet uses CSMA/CD for media access just like the original Ethernet). Physically, however, twisted pair Ethernet consists of a hub to which each computer connects, making it a physical star. One often hears the terms "star-shaped bus" or "bus-in-a-box" used to describe the configuration.

Q: Why is that the hosts on the ethernet need to be seperated by a minimum distance (3m?). I understand the need for maximum distance.

A: This answer from Tim Korb:

It's in 7.6.2 of the spec. The placement is to reduce signal reflections and, in particular, to make sure that placement does not "add in phase to a significant degree". The spec is not to insure a minimum distance, but to insure regular placement. The placement distance, incidentally, is 2.5 meters.

Q & A on 100BaseT and 10BaseT Cabling,

Q: Can 100-Base-T ethernet cables be used with 10-Base-T cables? In which case, some pairs are just ignored?

A: There are two parts to the answer. First, as long as the cable meets the standard (i.e., category 5), the same type of cable can indeed be used for either. Second, twisted pair Ethernet uses RJ-45 connectors (8-pin modular connectors that are larger versions of 4-wire connectors used on a conventional telephone). As long as all eight wires are connected, the same connector can be plugged into either 10 or 100 Mbps equipment.

As a practical matter, most network interface cards are now called ``10/100 cards'' because the hardware automatically senses whether it has been connected to a 10Base-T hub or a 100Base-T hub. The same cable can be used between the computer and the hub in each case. In our lab, for example, when we ask students to measure 10 and 100 Mbps Ethernet, they switch computers from one to the other merely by changing the hub -- the same cable is used.

Q & A on One LAN or Many LANs on a Campus,

Q: I have a question about LANs. Are computers on a large university campus on one LAN or many LANs?

A: In general one LAN is incapable of supporting an entire large campus. As a general rule, each LAN is limited to an area approximaely the size of a single building. Indeed, mnay large unoversity buildings have more than one LAN. There are exceptions, of course, but you can use that as a guideline.

Q: Is it right that Ips with same mask are on a same LAN?

A: "Ips" is not a valid technical term. I assume you mean IP addresses (the 32-bit value assigned to a host on an internet). If so, the answer is "no". It's not the mask itself that determines whether two computers are on the same network, but whether the prefixes of the two addresses match. The mask simply tells where the prefix ends.. For example, the network in the Xinu lab here at Purdue and the main CS departmental network both use the same mask:

255.255.255.0

However, the prefixes differ in the third octet. Thus, two hosts on those two networks might have addresses:

128.10.2.1

and

128.10.3.1

When the mask is applied (logical and), the resulting prefixes are

128.10.2.0

and

128.10.3.0

which differ. However, the following two addresses are on the same network because when the mask is applied, both addresses have prefix 128.10.2.0

128.10.2.26

and

128.10.2.3

Q & A on ICMP and UDP "ping",

Q: Touching the subject "source for ping" I think that could be useful to cite an article of Eric T. Horne, published by SysAdmin in the July/August 1993 issue, where he shows the source code for a newping that uses the TIME/TCP port, instead of the traditional ICMP, to detect CPU activity for the destination machine. I hope this citation be useful.

A: Actually, one doesn't need to use the time port because both TCP and UDP have a standard port reserved for echo: port 7. A program called ``upds'' has been floating around for many years that uses the UDP echo port exactly like ping uses ICMP echo. In fact, when I lecture to professional audiences, I usually talk about udps and explain that unlike ping, it determines more than whether interrupts are working on the remote computer.

Q & A on Netweork Analyzer Software,

Q: I am planning to use your book, Computer Networks and Internets, for my class (Computer Networks) in the coming Fall semester. As you wrote in the preface that students seem to understand more on the material if they see packets on a real network. You also mention about an inexpensive network analyzer software. Would you please give me the name of the network analyzer software that good but not too expensive? The department cannot afford to by an expensive HP network anlyzer.

A: Here at Purdue, we have used a variety of network analyzer software running on a workstation (i.e., a PC) rather than a dedicated box. Currently, we're using 'snoop' (a program available with Solaris); we used to use 'etherfind'. To make it 'safe' for undergrads, we (1) install an extra NIC in each workstation that connects to an experimental network, and (2) use the sudo program to invoke snoop, which restricts what the students are allowed to do.

I should tell you that, it's not difficult to roll your own -- as a first project in my graduate-level internetworking course, I have each student build an analyzer (put the interface card in promiscuous mode and selectively dump packets).

Q: I totally agree with you that teaching computer network, the lab is a must. Your book is very good, you make something so complex to be simple.

A: Thanks.

Q: I will teach this course for one-semester, what Parts should I cover? Part 1 through 3 as you suggested in the preface?

A: I'm currently teaching a senior-level networking course from the text, with the following empahsis:

  • 1.5 weeks : Introduction, signals, media, bandwidth, throughput, snd multiplexing

  • 5.0 weeks: Packet transmission concepts and technologies; LANs, WANs, and local loop technologies

  • 5.0 weeks: Internetworking fundamentals and internals
  • 3.0 weeks: Internet applications

Q & A on Writing a Network Analyzer,

Q: I'm interested in exploring the idea of writing one's own analyzer. What do you use for this, the Berkeley packet library?

A: The grad students use my operating system, Xinu. We give them a device driver that can put the NIC in promiscuous mode to receive packets; they build the rest inside the kernel. Undergrads use snoop to capture frames, put them in a file, and then decode them offline (there are packet traces on the CD-ROM that comes with the book if you want to try decoding headers but don't have direct access to the driver).

Q: Also, I've just recently become more interested in networking, and I'm pretty much teaching myself this stuff. I was wondering what kind of approach you'd recommend for this type of education. I've read your TCP/IP Volumes I and III, as well as the RFCs for TCP,IP,ICMP. It's a bit of a curve, but once you read a few you want to read them all. I enjoy just reading the specs. What I guess I really need is a big project.

A: Yes, the only way to really appreciate the subtleties is to build. You can do packet analysis to find out about header details of existing protocols or watch traffic, but I suggest trying to implement a reliable protocol. If you don't have low-level facilities available, start with UDP -- build your own protocol and use UDP as a 'delivery' mechanism. Then, place an intermediate application between the two sides that delays, reorders, duplicates, or purposefully damages a few bits. See if you can design a protocol that detects/corrects the problem.

Q & A on Interpreting IP Addresses in Octal,

Q: Recently, I got a IP address for my computer in one of my university's resident halls. The address is read as xxx.xxx.xxx.070. So I did a ping to this address (just want to make sure it's not used by other people since I haven't connected my machine) and found out the machine already exists. When I did a telnet, I was really connected to a machine. By looking more carefully, I found I was connected to xxx.xxx.xxx.56 instead. What is the explanation?

A: Understanding the mystery requires you to know several facts:

1) 56 in decimal is 70 in octal (base 8).

2) The C programming language (and UNIX programs in general) follow the convention of interpreting constants with a leading zero as being an octal number.

3) Many TCP/IP programs such as ping and telnet that accept a dotted decimal address as an argument follow the C conventon.

I suppose that someone who was unaware that software could be confused by leading zeroes chose to represent 70 as 070 when they handed out your address. They probably thought it would make the printed version look nicer...

Q & A on New Top-Level Domains for DNS,

Q: I thought the elaborated domain name set (most significant segment list) shown in Figure 26.1 (p. 367) of the 2nd ed. had not received final approval and therefore was not (yet) in use. Did I miss a post on this and am I mistaken? Please advise as to the status of this.

A: Well... I made a bad call on this one. While I was revising the text last Spring, the new list was being considered. I each a tutorial with Paul Mockapetris (the guy who invented DNS), and he thought adoption had high probability. So, I gambled that it would be in place by now.

But... as far as I can tell, there's been no formal action yet. Furthermore, with the untimely death of Jon Postel, many things are changing, including the imminent creation of the Domain Name Service Organization.

I'll add this item to the errata.

Q & A on WAP and TCP.

Q: I would like to know why is that why WAP doesn't use TCP?

A: WAP (Wireless Access Protocol) isn't a transfer protocol like HTTP. Instead, it's a complete protocol stack. Although WAP doesn't rule out using TCP, the main focus is on handheld devices:

1) WAP is intended to run over existing protocols that have been developed for delivering data across the cellular telephone system (e.g., CDPD).

2) WAP is optimized for delivery channels that have low bandwidth.

If reliability is needed, the Wireless Session Protocol (WSP) component of the WAP stack must provide it.

Q & A on TCP Segment Lengths.

Q: I have a couple of quick questions regarding the TCP protocol.

1. When I checked the TCP segment format, as shown in fig 22.6 of your Computer Networks and Internets book, I did not find any field in the header to indicate the segment length. And the question is: - How does the IP protocol in the same host know the length of the segment?

A: The length is not stored in the header. However, when TCP manufactures a segment, it passes the length (and other information) to IP along with the segment.

Q: - Also, how does the TCP protocol in the other side know the length of the segment?

A: When IP receives a datagram carrying TCP, IP computes the length of the segment (from the IP header length and total datagram length), and then passes the length to TCP along with the segment.

Q: 2. As far as I know, a TCP segment will be sent to IP to transfer it to the other side. The TCP header only has DESTINATION PORT in its header, which is just 16 bits. From where the IP protocol will know the IP address of the destination/source?

A: The IP destination address is among the additional information that TCP must pass to IP along with an outgoing segment.

Q: As far as I know, the application layer knows about the ``connection'' and its two endpoints. However, there is no direct link between the application layer and the IP layer. That is why, I am asking my question.

A: There must be an Application Program Interface (API) that allows the application to specify details such as the IP address and protocol port number of a remote site. Once the information has been specified, protocol software has access to it.

Q & A on TCP/IP Between Hosts on a Single Network.

Q: I just wanted to know if TCP/IP is required when the client and the server are located on the same physical network.

A: If the operating systems on the two computer provide support for some other suite (or direct access to the underlying network), TCP/IP is not required. In practice, however, chances of being able to use an alternative are extremely slim -- no protocols are available on as many computer systems as TCP/IP, which has become the universal language of networking.

Q & A on "Internetworking with TCP/IP, Volume 1".

Q: What is the title of this book (Volume 1 of Internetworking with TCP/IP)?

A: The book to which I referred is:

 D. Comer,  Internetworking With TCP/IP Volume 1: Principles,
Protocols, and Architectures, 3rd edition, Prentice Hall, 1995.
ISBN 0-13-216987-8

You can find a list of all my books on my Web page:

 http://www.cs.purdue.edu/people/comer

Q & A on TPC/IP Layering Model,

Q: why does the book, at pp. 230, show that the TCP/IP has 5 layers, while other books (e.g., Tanenbaum's and Hunt's books) say it is 4 layers? Is it network interface layer and physical layer?, or is it host-to-network layer?

A: When I wrote Volume 1 of Internetworking with TCP/IP, I was on the IAB working with the researchers who created the protocols. I documented what they had created: a 5-layer model. Furthermore, I used the names we commonly used for the layers (e.g., network interface layer). Since then, other authors have tried to rephrase the model (e.g., at least one author omits the hardware layer). I suppose they hope such changes will increase sales of their books.

Q & A on IP Address Prefixes and Suffixes

Q: Our class had a question about table 16.13 on page 245 (2nd edition).

The headers in the table are "prefix" and "suffix", implying that these address the bits AFTER the bits identifying the address class.

A: When I use the term ``prefix'', I include the bits that identify the class as well as bits that identify network.

Q: We had a question about the entries for "this computer" and "limited broadcast". Is this really referring to the prefix (where self-identifying bits for address class are still used), or are all octets in the address 0's or 1's.

A: The address labeled ``this computer'' consists of all 32 zero bits, and the address for ``limited broadcast'' consists of all 32 one bits. The class bits are not interpreted in these special addresses.

Q & A on "Net 0" IP Addresses.

Q: Is it Ok to assign 0.xx.xx.xx to an IP host number, where xx != 0, i.e., class A with a prefix = all-0s and suffix is any thing, but not all-0's.

A: The question doesn't need an asnwer: addresses on the Internet are assigned by a central authority, so the question is irrelevant. Addresses on private networks are assigned to avoid global addresses (e.g., the IETF recommends using the class A address 10.0.0.0, which will never again be assigned to any network in the Internet). Thus, one would never assign 0.x.x.x in either case.

Q: But according to Tanenbaum, pp. 417, he said that when a prefix is all-0s and suffix is HOST, it means a host on this network. He added, these addresses allow machines to refer to their own network without knowing its number, but they have to know its class to know how many 0s to include.

A: That doesn't make sense. One cannot know the ``class'' of the local network address without knowing the address.

Q: This means, according to Tanenbaum, that 0.xx.xx.xx is a special address. However, I did not find it listed as a special address in Figure 16.7. That is why I got confused about this address.

A: There's no point in worrying about it because it's not used that way in practice.

Q: With reference to:

Is it Ok to assign 0.xx.xx.xx to an IP host number, where xx != 0, i.e., class A with a prefix = all-0s and suffix is any thing, but not all-0's.

Would it be a simple case of xx != 0? (Even with an ordinary class A prefix: 40.0.0.8) Obviously not all zeros, but some zeros are permitted.

A: I understood the question to be whether it was permissible to use the Class A prefix that consists of eight zero bits. At least some of the host part (the last three octets) will be nonzero, but that doesn't answer the question of whether Class A prefixes start at 0 or 1.

Q & A on Network Standard Byte Order and User Data.

Q: I can understand the neccessary of the internet standard for byte order. But, why the user data field in packet is exempt from the standard?

If i communicate between a Little Endian machine and a Big Endian machine, the data would be misunderstand or my program must deal with the byte order, which means that my program is related to the unique machine, right?

A: You are correct in asserting that all data must be translated. If an application running on a Little Endian computer merely transfers a copy of the bits of an integer to an application running on a Big endian computer, the receiver will interpret the value of the bits differently, resulting in an error.

However, it does not make sense for network protocol to require translations because only the application programmer understands the data being sent across the network. If an application uses non-numeric data or has a reason to specify a particular representation, the network protocols should not interfere.

As a result, application programmers have complete freedom to choose a data representation, but also have the responsibility to handle any byte-order conversions or their clients and servers will not work correctly when communicating between two computers that have different native byte orders.

Q & A on Network Topologies,

Q: 1) Can a ring topology be used on Ethernet? If yes, how?

A: No, Ethernet uses a bus topology.

Q: 2) Would a pure ring or a star ring topology be easier to maintain and troubleshoot? Why?

A: Is this a homework problem?

Q: 3) What is the maximum distance (in meters and feet) a node can be from a hub without any repeaters in between?

The nominal length of a twisted pair segment is 100 meters; slightly longer wiring *may* work, depending on the amount of electrical noise in the environment and the exact type of cable.

Q & A on Code for Internetworking with TCP/IP, Volume 3

Q: In your book, (sorry forget the title -Networking with TCP/IP?) Volume III, is the example code for client and server available on the Internet for download?

A: All the code from my books is available for download. Volume 3 comes in three versions that use slightly different interfaces: Sockets, TLI, and Windows sockets. The easiest way to obtain the code is from the following Web page which has a link to the code for each networking book:

Q & A on Attenuation in Ethernet Network Design

Q: Another reason for maximum bus segment length it that there is more attenuation and more noice on a long cable, and therefor more bit errors, but I don't think that that is the main reason.

A: Yes, attenuation is a minor design issue -- for a given transmitter power level and type of cable, the signal will only reach a certain distance before becoming too weak to receive realiably. However, if attenuation were a major limitation issue, it could be overcome by more stringent cable requirements or increased transmitter power levels.

Q & A on Hardware Technologies

Q: CNAI, p.32D. Does the fact that Ethernet uses CSMA/CD preclude an Ethernet system from using frequency division multiplexing? That is, does the existence of one carrier wave on the ether keep every other host off?

A: Yes. When one host is transmitting on a segment (or a hub) other hosts refrain from transmitting. You can imagine that they all use the same "frequency". Thus, there is no FDM.

Q: Is X25net a connection oriented technology?

A: Yes. Like ATM, X.25 is connection-oriented.

Q: When you state that ' "tunneling" treats packets like data' do you mean this technique treats packets like a continuous stream of data where individual packets are sent contiguously, one after another?

A: Technically, the difference between *tunneling* and *encapsulation* is that encapsulation sends datagrams over hardware frames, while tunneling sends datagrams over some "higher level" protocol system. In terms of X.25 the term *tunneling* is appropriate because X.25 adds several layers of protocols on top of the underlying hardware.

Whether the interface is stream-oriented or message-oriented is completely independent of the underlying transmission scheme (e.g., TCP offers a stream-oriented interface, but sends data in individual segments, with one segment per datagram). Thus, one can tunnel over a stream-oriented interface or a message-oriented interface.

Q: LAN's vs. WAN's. Can the nodes of a LAN be a subset of the nodes of a WAN (or are they disjoint sets)? Are WAN's ever aggregates of LAN's?

A: The quick answer is that because LANs and WANs use completely different technologies, one cannot build a WAN by aggregating LANs. However.... some WAN technologies provide an interface that *appears* to be a LAN. For example, if one leases a satellite channel between San Francisco and new York, the equipment might appear as an Ethernet bridge to the computers using it. That is, a computer in San Francisco plugs into a 10BASE-T port, and appears to send and receive Ethernet frames. The bridge takes each transmitted frame, encodes it for transmission, sends the result across the satellite channel to New York, which then decodes the frame and delivers it to a 10BASE-T port. The advantage of using a 10BASE-T interface is that the attached computers can use standard hardware and software. That doesn't mean there's an Ethernet underneath (i.e., it's only the interface that appears to be an Ethernet). By the way, the same is true of ISDN and DSL technologies -- they accept and deliver Ethernet frames.

Q: Is it correct that a computer (host or router) has a physical address, but that its _connection_ to the Internet has an IP address? Or--is the physical address actually associated with the connection also?

A: Every network interface card has a physical address. If a computer connects to more than one network, it has more than one physical address. Thus, a router *always* has multiple physical addresses.

Q: Is the mapping from IP addresses to physical addresses one-to-one? In particular, if a host is multi-homed with two IP addresses, must it also have two physical addresses?

A: In almost all real internets the mapping is one-to-one. People sometimes play games where they assign *more* than one IP address to a given hardware interface (e.g. to simulate two subnets on the same physical wire). These many-one configurations fall outside the original intended use of IP. :-)

Q: In volume I you assert that routers must choose between routes employing physical networks that have properties of delay, throughput, and reliability. How do routers actually store this information? Is there some kind of static evaluation function the output of which characterizes the 'goodness' of a prospective route?

A: Although there has been much research on routing, the real Internet usually chooses the route that minimizes the hop count. Thus, the *type of service* routing field in the IP header is seldom used and the type of service routing you describe is seldom implemented. If it were, routers would need to keep detailed information about the throughput and delay along all paths. Delay changes so quickly that keeping accurate information is impossible.

Q: You state that each hardware technology imposes its own upper bound (MTU's) on frame size (e.g., Ethernet 1500, FDDI around 4K). Are all frames emanating from a given host 'A' of exactly the same size all the time? Do all hosts attached to Ethernet nets send frames of size 1500?

A: No, in most technologies, a frame is only as large as needed. For example, if you need to send 200 octets across an Ethernet, the outgoing frame will have a header followed by exactly 200 octets of data. For example, if a 600-octet datagram is sent over an Ethernet, the resulting frame has 600 octets of data following the Ethernet header.

As a practical matter, TCP/IP tries to optimize efficiency. Thus, if you use TCP/IP to transfer a file across an Ethernet, IP will create datagrams that are each 1500 octets long.

Another technical point: some technologies require a minimum frame size (so the hardware can distinguish real frames from a small burst of electrical noise or so the MAC protocols function properly). For example, Ethernet requires a frame to contain at least 64 octets of data. If the data being sent is less than the minimum size, it must be padded (e.g., with zeroes).

By the way, if a technology sends packets of a fixed size, they are called *cells*, not *frames*. For example, because each packet sent by ATM is the same size (53-octets), they are called *cells*, and ATM is known as a *cell-switching technology*.

Q: Please verify: when a host sends datagrams, they can be of *varying* size, but the frames emanating from the host will always be the same size.

A: Not correct -- both datagrams and frames can be of *varying* size.

Q: Are there actually two routing algorithms employed for forwarding data: one for frames on the physical net and one for datagrams on the virtual net?

A: In most LAN technologies, there is no "routing" -- one sends the packet across the LAN, all computers receive the frame, and all interface cards except the intended destination discard the frame. In most WAN technologies (at least the WANs that connect multiple hosts), the WAN needs to route frames among the switches that make up the WAN. Thus, when you send a packet across an X.25 network, switches inside the network route the packet from the port where it entered the network to the port where it exits.

So, the general answer is that routing occurs only at the IP level, not at the physical net (a handful of WAN technologies being the exception).

Q: Bridges vs. Routers: Can a bridge attach two different types of LAN's say, an Ethernet and a CDDI? How about an Ethernet and an FDDI?

A: In general, no. Bridges do not change the *shape* of the frame or the addresses. Thus, the technologies must have compatible frame formats and compatible addressing schemes. Thus, one could bridge CDDI and FDDI, but could not bridge Ethernet and FDDI.

Computer Network Questions and Answers Part 1

Can you be able to identify between Straight- through and Cross- over cable wiring?
Straight-through is type of wiring that is one to to one connection Cross- over is type of wiring which those wires are got switchedWe use Straight-through cable when we connect between NIC Adapter and Hub. Using Cross-over cable when connect between two NIC Adapters or sometime between two hubs.

What is the significance of the IP address 255.255.255.255?
The limited broadcast address is utilized when an IP node must perform a one-to-everyone delivery on the local network but the network ID is unknown.

What tool have you used to create and analyze packet captures?
Network Monitor in Win2K / Win2K3, Ethereal in Linux, OptiView Series II (by Fluke Networks).

What is LDAP used for?
LDAP is a set of protocol used for providing access to information directories.

What is the difference between a domain local group and a global group?
Domain local groups grant permissions to objects within the domain in which the reside. Global groups contain grant permissions tree or forest wide for any objects within the Active Directory

How do you set a default route on an IOS Cisco router?
ip route 0.0.0.0 0.0.0.0 x.x.x.x [where x.x.x.x represents the destination address]

What is a default gateway?
The exit-point from one network and entry-way into another network, often the router of the network.

What is Kerberos?
It is an authentication service developed at the Massachusetts Institute of Technology. Kerberos uses encryption to prevent intruders from discovering passwords and gaining unauthorized access to files.

What is NVT (Network Virtual Terminal)?
It is a set of rules defining a very simple virtual terminal interaction. The NVT is used in the start of a Telnet session.

What is silly window syndrome?
It is a problem that can ruin TCP performance. This problem occurs when data are passed to the sending TCP entity in large blocks, but an interactive application on the receiving side

Computer Network Questions and Answers Part 2.

What is region?
When hierarchical routing is used, the routers are divided into what we will call regions, with each router knowing all the details about how to route packets to destinations within its own region, but knowing nothing about the internal structure of other regions.

What is traffic shaping?
One of the main causes of congestion is that traffic is often busy. If hosts could be made to transmit at a uniform rate, congestion would be less common. Another open loop method to help manage congestion is forcing the packet to be transmitted at a more predictable rate. This is called traffic shaping.

What is packet filter?
Packet filter is a standard router equipped with some extra functionality. The extra functionality allows every incoming or outgoing packet to be inspected. Packets meeting some criterion are forwarded normally. Those that fail the test are dropped.

What is virtual path?
Along any transmission path from a given source to a given destination, a group of virtual circuits can be grouped together into what is called path.

What is virtual channel?
Virtual channel is normally a connection from one source to one destination, although multicast connections are also permitted. The other name for virtual channel is virtual circuit.

What is LLC?
LLC is Logical Link Control, one of two sublayers of the data link layer of OSI reference model, as defined by the IEEE 802 standard. This sublayer is responsible for maintaining the link between computers when they are sending data across the physical network connection.

What is the difference between routable and non- routable protocols?
Routable protocols can work with a router and can be used to build large networks. Non-Routable protocols are designed to work on small, local networks and cannot be used with a router

What is MAU?
In token Ring , hub is called Multistation Access Unit(MAU).

Explain 5-4-3 rule?
In a Ethernet network, between any two points on the network ,there can be no more than five network segments or four repeaters, and of those five segments only three of segments can be populated.

What is the difference between TFTP and FTP application layer protocols?
The Trivial File Transfer Protocol (TFTP) allows a local host to obtain files from a remote host but does not provide reliability or security. It uses the fundamental packet delivery services offered by UDP.
The File Transfer Protocol (FTP) is the standard mechanism provided by TCP / IP for copying a file from one host to another. It uses the services offer by TCP and so is reliable and secure. It establishes two connections (virtual circuits) between the hosts, one for data transfer and another for control information.

Computer Network Questions and Answers Part 3.

What is the range of addresses in the classes of internet addresses?
Class A 0.0.0.0 - 127.255.255.255
Class B 128.0.0.0 - 191.255.255.255
Class C 192.0.0.0 - 223.255.255.255
Class D 224.0.0.0 - 239.255.255.255
Class E 240.0.0.0 - 247.255.255.255

What is difference between ARP and RARP?
The address resolution protocol (ARP) is used to associate the 32 bit IP address with the 48 bit physical address, used by a host or a router to find the physical address of another host on its network by sending a ARP query packet that includes the IP address of the receiver. The reverse address resolution protocol (RARP) allows a host to discover its Internet address when it knows only its physical address.

What are the data units at different layers of the TCP / IP protocol suite?
The data unit created at the application layer is called a message, at the transport layer the data unit created is called either a segment or an user datagram, at the network layer the data unit created is called the datagram, at the data link layer the datagram is encapsulated in to a frame and finally transmitted as signals along the transmission media.

What is ICMP?
ICMP is Internet Control Message Protocol, a network layer protocol of the TCP/IP suite used by hosts and gateways to send notification of datagram problems back to the sender. It uses the echo test / reply to test whether a destination is reachable and responding. It also handles both control and error messages.

What is Protocol Data Unit?
The data unit in the LLC level is called the protocol data unit (PDU). The PDU contains of four fields a destination service access point (DSAP), a source service access point (SSAP), a control field and an information field. DSAP, SSAP are addresses used by the LLC to identify the protocol stacks on the receiving and sending machines that are generating and using the data. The control field specifies whether the PDU frame is a information frame (I - frame) or a supervisory frame (S - frame) or a unnumbered frame (U - frame).

Difference between bit rate and baud rate.
Bit rate is the number of bits transmitted during one second whereas baud rate refers to the number of signal units per second that are required to represent those bits.
Baud rate = bit rate / N ?: where N is no-of-bits represented by each signal shift.

How Gateway is different from Routers?
A gateway operates at the upper levels of the OSI model and translates information between two completely different network architectures or data formats.

What is passive topology?
When the computers on the network simply listen and receive the signal, they are referred to as passive because they don’t amplify the signal in any way. Example for passive topology - linear bus.

What is NETBIOS and NETBEUI?
NETBIOS is a programming interface that allows I/O requests to be sent to and received from a remote computer and it hides the networking hardware from applications.
NETBEUI is NetBIOS extended user interface. A transport protocol designed by microsoft and IBM for the use on small subnets.

What is redirector?
Redirector is software that intercepts file or prints I/O requests and translates them into network requests. This comes under presentation layer.

Computer Network Questions and Answers Part 4.

What is Beaconing?
The process that allows a network to self-repair networks problems. The stations on the network notify the other stations on the ring when they are not receiving the transmissions. Beaconing is used in Token ring and FDDI networks.

What is terminal emulation, in which layer it comes?
Telnet is also called as terminal emulation. It belongs to application layer.

What do you meant by “triple X” in Networks?
The function of PAD (Packet Assembler Disassembler) is described in a document known as X.3. The standard protocol has been defined between the terminal and the PAD, called X.28; another standard protocol exists between hte PAD and the network, called X.29. Together, these three recommendations are often called “triple X”.

What is SAP?
SAP: Service Access Point , Series of interface points that allow other computers to communicate with the other layers of network protocol stack.

How does the browser know to go to a certain IP address when you enter a domain like crackthecampus.com?
It searches through local DNS cache, if nothing is there, it queries the ISP’s DNS server

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

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.

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.

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.

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 indirect contact with other people.

Computer Network Questions and Answers Part 5,

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.

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.

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.

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.

What are the building blocks of Client/Server?
The client ,The server and Middleware.

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”.
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.

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

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.

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.

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.

Computer Network Questions and Answers Part 6.

What is anonymous FTP and why would you use it?
Anonymous FTP enables users to connect to a host without using a valid login and password. Usually, anonymous FTP uses a login called anonymous or guest, with the password usually requesting the user’s ID for tracking purposes only. Anonymous FTP is used to enable a large number of users to access files on the host without having to go to the trouble of setting up logins for them all. Anonymous FTP systems usually have strict controls over the areas an anonymous user can access.

What is a DNS resource record?
A resource record is an entry in a name server’s database. There are several types of resource records used, including name-to-address resolution information. Resource records are maintained as ASCII files.

Explain the function of Transmission Control Block
A TCB is a complex data structure that contains a considerable amount of information about each connection.

What is virtual path?
Along any transmission path from a given source to a given destination, a group of virtual circuits can be grouped together into what is called path.

What protocol is used by DNS name servers?
DNS uses UDP for communication between servers. It is a better choice than TCP because of the improved speed a connectionless protocol offers. Of course, transmission reliability suffers with UDP.

What is External Data Representation?
External Data Representation is a method of encoding data within an RPC message, used to ensure that the data is not system-dependent.

What is Brouter?
Hybrid devices that combine the features of both bridges and routers.

Explain 5-4-3 rule.
In a Ethernet network, between any two points on the network, there can be no more than five network segments or four repeaters, and of those five segments only three of segments can be populated.

What is REX?
Request to Exit (REX) - A signal that informs the controller that someone has requested to exit from a secure area.

What are major types of networks and explain?
Server-based network.
Peer-to-peer network.
Peer-to-peer network, computers can act as both servers sharing resources and as clients using the resources.
Server-based networks provide centralized control of network resources and rely on server computers to provide security and network administration.

Computer Network Questions and Answers Part 7.

Explain the importance and use of each, Version, Culture and PublicKeyToken for an assembly.
This three alongwith name of the assembly provide a strong name or fully qualified name to the assembly. When a assebly is referenced with all three.
PublicKeyToken: Each assembly can have a public key embedded in its manifest that identifies the developer. This ensures that once the assembly ships, no one can modify the code or other resources contained in the assembly.
Culture: Specifies which culture the assembly supports
Version: The version number of the assembly.It is of the following form major.minor.build.revision.

How you will set the datarelation between two columns?
ADO.NET provides DataRelation object to set relation between two columns.It helps to enforce the following constraints,a unique constraint, which guarantees that a column in the table contains no duplicates and a foreign-key constraint,which can be used to maintain referential integrity.A unique constraint is implemented either by simply setting the Unique property of a data column to true, or by adding an instance of the UniqueConstraint class to the DataRelation object’s ParentKeyConstraint. As part of the foreign-key constraint, you can specify referential integrity rules that are applied at three points,when a parent record is updated,when a parent record is deleted and when a change is accepted or rejected.

What is source route?
It is a sequence of IP addresses identifying the route a datagram must follow. A source route may optionally be included in an IP datagram header.

What is SLIP (Serial Line Interface Protocol)?
It is a very simple protocol used for transmission of IP datagrams across a serial line.

What is Proxy ARP?
It is using a router to answer ARP requests. This will be done when the originating host believes that a destination is local, when in fact is lies beyond router.

What is OSPF?
It is an Internet routing protocol that scales well, can route traffic along multiple paths, and uses knowledge of an Internet’s topology to make accurate routing decisions.

What is BGP (Border Gateway Protocol)?
It is a protocol used to advertise the set of networks that can be reached with in an autonomous system. BGP enables this information to be shared with the autonomous system. This is newer than EGP (Exterior Gateway Protocol).

What is autonomous system?
It is a collection of routers under the control of a single administrative authority and that uses a common Interior Gateway Protocol.

What is EGP (Exterior Gateway Protocol)?
It is the protocol the routers in neighboring autonomous systems use to identify the set of networks that can be reached within or via each autonomous system

Computer Network Questions and Answers Part 8.

What is Mail Gateway?
It is a system that performs a protocol translation between different electronic mail delivery protocols

What is wide-mouth frog?
Wide-mouth frog is the simplest known key distribution center (KDC) authentication protocol.

What are Digrams and Trigrams?
The most common two letter combinations are called as digrams. e.g. th, in, er, re and an. The most common three letter combinations are called as trigrams. e.g. the, ing, and, and ion.

What is silly window syndrome?
It is a problem that can ruin TCP performance. This problem occurs when data are passed to the sending TCP entity in large blocks, but an interactive application on the receiving side reads 1 byte at a time.

What is region?
When hierarchical routing is used, the routers are divided into what we will call regions, with each router knowing all the details about how to route packets to destinations within its own region, but knowing nothing about the internal structure of other regions

What is multicast routing?
Sending a message to a group is called multicasting, and its routing algorithm is called multicast routing.

What is traffic shaping?
One of the main causes of congestion is that traffic is often busy. If hosts could be made to transmit at a uniform rate, congestion would be less common. Another open loop method to help manage congestion is forcing the packet to be transmitted at a more predictable rate. This is called traffic shaping.

What is virtual channel?
Virtual channel is normally a connection from one source to one destination, although multicast connections are also permitted. The other name for virtual channel is virtual circuit.

What is logical link control?
One of two sublayers of the data link layer of OSI reference model, as defined by the IEEE 802 standard. This sublayer is responsible for maintaining the link between computers when they are sending data across the physical network connection.

What is the difference between routable and non- routable protocols?
Routable protocols can work with a router and can be used to build large networks. Non-Routable protocols are designed to work on small, local networks and cannot be used with a router

Computer Network Questions and Answers Part 9,

What MAU?
In token Ring , hub is called Multistation Access Unit(MAU).

What is difference between baseband and broadband transmission?
In a baseband transmission, the entire bandwidth of the cable is consumed by a single signal. In broadband transmission, signals are sent on multiple frequencies, allowing multiple signals to be sent simultaneously.

What are the important topologies for networks?
BUS topology:In this each computer is directly connected to primary network cable in a single line.
Advantages:Inexpensive, easy to install, simple to understand, easy to extend.
STAR topology:In this all computers are connected using a central hub.
Advantages:Can be inexpensive, easy to install and reconfigure and easy to trouble shoot physical problems.
RING topology:In this all computers are connected in loop.
Advantages:All computers have equal access to network media, installation can be simple, and signal does not degrade as much as in other topologies because each computer regenerates it

What is the difference between TFTP and FTP application layer protocols?
The Trivial File Transfer Protocol (TFTP) allows a local host to obtain files from a remote host but does not provide reliability or security. It uses the fundamental packet delivery services offered by UDP.The File Transfer Protocol (FTP) is the standard mechanism provided by TCP / IP for copying a file from one host to another. It uses the services offer by TCP and so is reliable and secure. It establishes two connections (virtual circuits) between the hosts, one for data transfer and another for control information.

What are the data units at different layers of the TCP / IP protocol suite?
The data unit created at the application layer is called a message, at the transport layer the data unit created is called either a segment or an user datagram, at the network layer the data unit created is called the datagram, at the data link layer the datagram is encapsulated in to a frame and finally transmitted as signals along the transmission media.

What are the different type of networking / internetworking devices?
Repeater:Also called a regenerator, it is an electronic device that operates only at physical layer. It receives the signal in the network before it becomes weak, regenerates the original bit pattern and puts the refreshed copy back in to the link.
Bridges: These operate both in the physical and data link layers of LANs of same type. They divide a larger network in to smaller segments. They contain logic that allow them to keep the traffic for each segment separate and thus are repeaters that relay a frame only the side of the segment containing the intended recipent and control congestion.
Routers:They relay packets among multiple interconnected networks (i.e. LANs of different type). They operate in the physical, data link and network layers. They contain software that enable them to determine which of the several possible paths is the best for a particular transmission.
Gateways:They relay packets among networks that have different protocols (e.g. between a LAN and a WAN). They accept a packet formatted for one protocol and convert it to a packet formatted for another protocol before forwarding it. They operate in all seven layers of the OSI model.

What is Project 802?
It is a project started by IEEE to set standards to enable intercommunication between equipment from a variety of manufacturers. It is a way for specifying functions of the physical layer, the data link layer and to some extent the network layer to allow for interconnectivity of major LAN
protocols.It consists of the following:
802.1 is an internetworking standard for compatibility of different LANs and MANs across protocols.
802.2 Logical link control (LLC) is the upper sublayer of the data link layer which is non-architecture-specific, that is remains the same for all IEEE-defined LANs.
Media access control (MAC) is the lower sublayer of the data link layer that contains some distinct modules each carrying proprietary information specific to the LAN product being used.
The modules are Ethernet LAN (802.3), Token ring LAN (802.4), Token bus LAN (802.5).
802.6 is distributed queue dual bus (DQDB) designed to be used in MANs.

What are the types of Transmission media?
Signals are usually transmitted over some transmission media that are broadly classified in to two categories.
a)Guided Media:These are those that provide a conduit from one device to another that include twisted-pair, coaxial cable and fiber-optic cable. A signal traveling along any of these media is directed and is contained by the physical limits of the medium. Twisted-pair and coaxial cable use metallic that accept and transport signals in the form of electrical current. Optical fiber is a glass or plastic cable that accepts and transports signals in the form of light.
b) Unguided Media: This is the wireless media that transport electromagnetic waves without using a physical conductor. Signals are broadcast either through air. This is done through radio communication, satellite communication and cellular telephony.

What is Bandwidth?
Every line has an upper limit and a lower limit on the frequency of signals it can carry. This limited range is called the bandwidth

Difference between bit rate and baud rate.
Bit rate is the number of bits transmitted during one second whereas baud rate refers to the number of signal units per second that are required to represent those bits.

networking 146

What is MAC address?
The address for a device as it is identified at the Media Access Control (MAC) layer in the network architecture. MAC address is usually stored in ROM on the network adapter card and is unique.

What is cladding?
A layer of a glass surrounding the center fiber of glass inside a fiber-optic cable.

How Gateway is different from Routers?
A gateway operates at the upper levels of the OSI model and translates information between two completely different network architectures or data formats

What is passive topology?
When the computers on the network simply listen and receive the signal, they are referred to as passive because they don’t amplify the signal in any way. Example for passive topology - linear bus.

What is SAP?
Series of interface points that allow other computers to communicate with the other layers of network protocol stack.

What is subnet?
A generic term for section of a large networks usually separated by a bridge or router.

What is IP?
IP is Internet Protocol. It is the network protocol which is used to send information from one computer to another over the network over the internet in the form of packets

What’s the meaning of ARP in TCP/IP?
The “ARP” stands for Address Resolution Protocol. The ARP standard defines two basic message types: a request and a response. a request message contains an IP address and requests the corresponding hardware address; a replay contains both the IP address, sent in the request, and the hardware address.

What is data link layer in the OSI reference model responsible for?
Data link layer is located above the physical layer, but below the network layer. Taking raw data bits and packaging them into frames. The network layer will be responsible for addressing the frames, while the physical layer is reponsible for retrieving and sending raw data bits.

What is binding order?
The order by which the network protocols are used for client-server communications. The most frequently used protocols should be at the top.

How do cryptography-based keys ensure the validity of data transferred across the network?
Each IP packet is assigned a checksum, so if the checksums do not match on both receiving and transmitting ends, the data was modified or corrupted.

What is UTP?
UTP — Unshielded twisted pair 10BASE-T is the preferred Ethernet medium of the 90s. It is based on a star topology and provides a number of advantages over coaxial media.
It uses inexpensive, readily available copper phone wire. UTP wire is much easier to install and debug than coax. UTP uses RG-45 connectors, which are cheap and reliable.

What is a router? What is a gateway?
Routers are machines that direct a packet through the maze of networks that stand between its source and destination. Normally a router is used for internal networks while a gateway acts a door for the packet to reach the ‘outside’ of the internal network

What is Semaphore? What is deadlock?
Semaphore is a synchronization tool to solve critical-section problem, can be used to control access to the critical section for a process or thread. The main disadvantage (same of mutual-exclusion) is require busy waiting. It will create problems in a multiprogramming system, where a single CPU is shared among many processes.
Busy waiting wastes CPU cycles.
Deadlock is a situation when two or more processes are waiting indefinitely for an event that can be caused by only one of the waiting processes. The implementation of a semaphore with a waiting queue may result in this situation.

Basic Networkin Questions - 2, 142

What does the Mount protocol do ?
The Mount protocol returns a file handle and the name of the file system in which a requested file resides. The message is sent to the client from the server after reception of a client's request.

What is anonymous FTP and why would you use it?
Anonymous FTP enables users to connect to a host without using a valid login and password. Usually, anonymous FTP uses a login called anonymous or guest, with the password usually requesting the user's ID for tracking purposes only. Anonymous FTP is used to enable a large number of users to access files on the host without having to go to the trouble of setting up logins for them all. Anonymous FTP systems usually have strict controls over the areas an anonymous user can access.

What is the Network Time Protocol?
The Network Time Protocol is a protocol for synchronizing the clocks of computer systems over packet-switched, variable-latency data networks. NTP uses UDP port 123 as its transport layer. It is designed particularly to resist the effects of variable latency (Jitter).NTP is one of the oldest Internet protocols still in use (since before 1985).

What is a pseudo tty?
In Unix, a pseudo terminal is a pseudo-device pair that provides a text terminal interface without associated virtual console, computer terminal or serial port hardware. Instead, a process replaces the role of the underlying hardware for the pseudo terminal session.For each pseudo terminal, the operating system kernel provides two character devices: a master device and a slave device.The master and slave devices, in their most common deployment, form an association between a Unix shell and a terminal emulation program or some sort of network server.The slave device file, which generally has a nomenclature of /dev/ttyp*, has the appearance and supported system calls of any text terminal. Thus it has the understanding of a login session and session leader process (which is typically the shell program).The master device file, which generally has a nomenclature of /dev/ptyp*, is the endpoint for communication with the terminal emulator. It receives the control requests and information from the other party over this interface and responds accordingly.

What is External Data Representation?
eXternal Data Representation (XDR) is an IETF standard from 1995 of the presentation layer in the OSI model. XDR allows data to be wrapped in an architecture independent manner so data can be transferred between heterogeneous computer systems. Converting from the local representation to XDR is called encoding. Converting from XDR to the local representation is called decoding. XDR is implemented as a software library of functions that is portable between different operating systems and is also independent of the transport layer.

What is the difference between interior and exterior neighbor gateways?
Interior gateways connect LANs of one organization, whereas exterior gateways connect the organization to the outside world.

What are 10Base2, 10Base5 and 10BaseT Ethernet LANs ?
10Base2—An Ethernet term meaning a maximum transfer rate of 10 Megabits per second that uses baseband
signaling, with a contiguous cable segment length of 100
meters and a maximum of 2 segments.
10Base5—An Ethernet term meaning a maximum transfer rate of 10 Megabits per second that uses baseband
signaling, with 5 continuous segments not exceeding 100
meters per segment.
10BaseT—An Ethernet term meaning a maximum transfer rate of 10 Megabits per second that uses baseband
signaling and twisted pair cabling.

BOOTP helps a diskless workstation boot. How does it get a message to the network looking for its IP address and the location of its operating system boot files ?
BOOTP sends a UDP message with a subnetwork broadcast address and waits for a reply from a server that gives it the IP address. The same message might contain the name of the machine that has the boot files on it. If the boot image location is not specified, the workstation sends another UDP message to query the server

What protocol is used by DNS name servers ?
DNS uses UDP for communication between servers. It is a better choice than TCP because of the improved speed a connectionless protocol offers. Of course, transmission reliability suffers with UDP.

Which are the three types of routing tables ?
The three types of routing tables are fixed, dynamic, and fixed central. The fixed table must be manually modified every time there is a change. A dynamic table changes its information based on network traffic, reducing the amount of manual maintenance. A fixed central table lets a manager modify only one table, which is then read by other devices. The fixed central table reduces the need to update each machine's table, as with the fixed table. Usually a dynamic table causes the fewest problems for a network administrator, although the table's contents can change without the administrator being aware of the change.

Basic Networkin Questions - 1 140

What is source-route bridging algorithm ?
The source-route bridging (SRB) algorithm was developed by IBM and was proposed to the IEEE 802.5 committee as the means to bridge between all LANs. SRBs are so named because they assume that the complete source-to-destination route is placed in all inter-LAN frames sent by the source. SRBs store and forward the frames as indicated by the route appearing in the appropriate frame field. Assume that Host X wants to send a frame to Host Y. Initially, Host X does not know whether Host Y resides on the same LAN or a different LAN. To determine this, Host X sends out a test frame. If that frame returns to Host X without a positive indication that Host Y has seen it, Host X assumes that Host Y is on a remote segment. To determine the exact remote location of Host Y, Host X sends an explorer frame. Each bridge receiving the explorer frame copies the frame onto all outbound ports. Route information is added to the explorer frames as they travel through the internetwork. When Host X's explorer frames reach Host Y, Host Y replies to each individually, using the accumulated route information. Upon receipt of all response frames, Host X chooses a path based on some predetermined criteria. Host X must select one of these two routes. The IEEE 802.5 specification does not mandate the criteria that Host X should use in choosing a route, but it does make several suggestions, including the following:
•First frame received
•Response with the minimum number of hops
•Response with the largest allowed frame size
•Various combinations of the preceding criteria
In most cases, the path contained in the first frame received is used.


What is Transparent Bridge ?
Transparent bridges were first developed at Digital Equipment Corporation (Digital) in
the early 1980s. Transparent bridges are so named because their presence and operation are transparent to network hosts. When transparent bridges are powered on, they learn the workstation locations by analyzing the source address of incoming frames from all attached networks. For example, if a bridge sees a frame arrive on port 1 from Host A, the bridge concludes that Host A can be reached through the segment connected to port 1. Through this process, transparent bridges build a table. The bridge uses its table as the basis for traffic forwarding. When a frame is received on one of the bridge's interfaces, the bridge looks up the frame's destination address in its internal table. If the table contains an association between the destination address and any of the bridge's ports aside from the one on which the frame was received, the frame is forwarded out the indicated port. If no association is found, the frame is flooded to all ports except the inbound port. Broadcasts and multicasts also are flooded in this way. Transparent bridges successfully isolate intrasegment traffic, thereby reducing the traffic seen on each individual segment. This is called filtering and occurs when the source and destination MAC addresses reside on the same bridge interface. Filtering usually improves network response times, as seen by the user. The extent to which traffic is reduced and response times are improved depends on the volume of intersegment traffic relative to the total traffic, as well as the volume of broadcast and multicast traffic.


What is the basic difference between transparent bridges and source-route bridges relative to the forwarding processes ?
In a transparent bridged environment, bridges determine whether a frame needs to be forwarded, and through what path based upon local bridge tables. In an SRB network, the source device prescribes the route to the destination and indicates the desired path in the RIF.


What is Switched Multimegabit Data Service ?
Switched Multimegabit Data Service (SMDS) is a high-speed, packet-switched, datagram-based WAN networking technology used for communication over public data networks (PDNs). SMDS can use fiber- or copper-based media. SMDS networks consist of several underlying devices to provide high-speed data service. These include customer premises equipment (CPE), carrier equipment, and the subscriber network interface (SNI). CPE is terminal equipment typically owned and maintained by the customer. CPE includes end devices, such as terminals and personal computers, and intermediate nodes, such as routers, modems, and multiplexers. Intermediate nodes, however, sometimes are provided by the SMDS carrier. Carrier equipment generally consists of high-speed WAN switches that must conform to certain network equipment specifications. These specifications define network operations, the interface between a local carrier network and a long-distance carrier network, and the interface between two switches inside a single carrier network.


Where is SMDS Interface Protocol used ?
The SMDS Interface Protocol (SIP) is used for communications between CPE (Customer premises equipment) and SMDS (Switched Multimegabit Data Service) carrier equipment. SIP provides connectionless service across the subscriber network interface (SNI), allowing the CPE to access the SMDS network.

What is Data-Link Switching ?
Data-link switching (DLSw) provides a means of transporting IBM Systems Network Architecture (SNA) and network basic input/output system (NetBIOS) traffic over an IP network. It serves as an alternative to source-route bridging (SRB), a protocol for transporting SNA and NetBIOS traffic in Token Ring environments that was widely deployed before the introduction of DLSw. In general, DLSw addresses some of the shortcomings of SRB for certain communication requirements—particularly in WAN implementations. This chapter contrasts DLSw with SRB, summarizes underlying protocols, and provides a synopsis of normal protocol operations. The three primary functions of DLSw are :
•The Switch-to-Switch Protocol (SSP) is the protocol maintained between two DLSw nodes or routers.
•The termination of SNA data-link control (DLC) connections helps to reduce the likelihood of link layer timeouts across WANs.
•The local mapping of DLC connections to a DLSw circuit.

What is Banyan VINES ?

Banyan Virtual Integrated Network Service (VINES) implements a distributed network operating system based on a proprietary protocol family derived from the Xerox Corporation's Xerox Network Systems (XNS) protocols. VINES uses a client/server architecture in which clients request certain services, such as file and printer access, from servers.

What is Enhanced Interior Gateway Routing Protocol ?

The Enhanced Interior Gateway Routing Protocol (EIGRP) represents an evolution from its predecessor IGRP. This evolution resulted from changes in networking and the demands of diverse, large-scale internetworks. EIGRP integrates the capabilities of link-state protocols into distance vector protocols. Additionally, EIGRP contains several important protocols that greatly increase its operational efficiency relative to other routing protocols. One of these protocols is the Diffusing update algorithm (DUAL). DUAL enables EIGRP routers to determine whether a path advertised by a neighbor is looped or loop-free, and allows a router running EIGRP to find alternate paths without waiting on updates from other routers. EIGRP provides compatibility and seamless interoperation with IGRP routers. An automatic-redistribution mechanism allows IGRP routes to be imported into EIGRP, and vice versa, so it is possible to add EIGRP gradually into an existing IGRP network. Because the metrics for both protocols are directly translatable, they are as easily comparable as if they were routes that originated in their own autonomous systems (ASs). In addition, EIGRP treats IGRP routes as external routes and provides a way for the network administrator to customize them.

Name the four key technologies that are used by EIGRP ?
EIGRP employs four key technologies, including neighbor discover/recovery, Reliable Transport Protocol (RTP), Diffusing Update ALgorithm (DUAL) finite-state machine, and a modular architecture that enables support for new protocols to be easily added to an existing network.

Why EIGRP is more efficient in operation than IGRP ?
Unlike most other distance vector routing protocols, EIGRP does not mandate a periodic update of routing tables between neighboring routers. Instead, it employs a neighbor discovery/recovery mechanism to ensure that neighbors remain aware of each other's accessibility. As long as a router receives periodic hello packets from its neighbors, it can assume that those neighbors remain functional. More importantly, it can assume that all of its routes that rely upon passage through those neighbors remain usable. Thus, EIGRP is much more efficient than conventional distance vector routing protocols because it imposes much less overhead on routers and transmission facilities during normal operation.

What is Interior Gateway Protocol ?
IGRP is a distance vector Interior Gateway Protocol (IGP). Distance vector routing protocols mathematically compare routes using some measurement of distance. This measurement is known as the distance vector. Routers using a distance vector protocol must send all or a portion of their routing table in a routing-update message at regular intervals to each of their neighboring routers. As routing information proliferates through the network, routers can identify new destinations as they are added to the network, learn of failures in the network, and, most importantly, calculate distances to all known destinations.

Networking, Socket Programming, Inter-Process Communication... 138

  • How do I monitor the activity of sockets?
  • How would I put my socket in non-blocking mode?
  • What are RAW sockets?
  • What is the role of TCP protocol and IP protocol.
  • What is UDP?
  • How can I make my server a daemon?
  • How should I choose a port number for my server?
  • Layers in TCP/IP
  • How can I be sure that a UDP message is received?
  • How to get IP header of a UDP message
  • Writing UDP/SOCK_DGRAM applications
  • How many bytes in an IPX network address?
  • What is the difference between MUTEX and Semaphore?
  • What is priority inversion?
  • Different Solutions to dining philosophers problem.
  • What is a message queue?
  • Questions on Shared Memory.
  • What is DHCP?
  • Working of ping, telnet, gopher.
  • Can I connect two computers to internet using same line ?
  • Working of TCP and SSL Handshake
  • How P2P softwares work?
  • Setting up TOMCAT web service
  • Port numbers for FTP, HTTP, telnet, POP, finger
  • Difference - Passive FTP, Active FTP
  • Maximum Transmission Unit (MTU) what is it?
  • Security threats due to use of CGI
  • What is "spoofing"
  • Where could you find Apache server web log
  • Find web visitors by country
  • What is Virtual Private Network (VPN) and how does it work?
  • How does routing work?
  • User(s) are complaining of delays when using the network. What would you do?
  • What are some of the problems associated with operating a switched LAN?
  • Name some of the ways of combining TCP/IP traffic and SNA traffic over the same link.
  • What sort of cabling is suitable for Fast Ethernet protocols?
  • What is a Class D IP address?
  • Why do I sometimes lose a server's address when using more than one server?

Networking Interview questions 134

Computer Networking Interview Questions

Here are the basic interview questions for the network administrators, system administrators and IT manager posts. These questions provide the basic information about the network communication technology, network topologies, network troubleshooting techniques, network devices and the basic overview of the LAN/WAN communication model.

What is DHCP?

DHCP stands for Dynamic Host Configuration Technology. The basic purpose of the DHCP is to assign the IP addresses and the other network configuration such as DNS, Gateway and other network settings to the client computers. DHCP reduces the administrative task of manually assigning the IP addresses to the large number of the computers in a network.

What is DNS and how it works?

DNS stands for Domain name system and it translates (converts) the host name into the IP address and IP address into to the host name. Every domain and the computer on the internet is assigned a unique IP address. The communication on the internet and in the network is based on the IP addresses. IP addresses are in this format 10.1.1.100, 220.12.1.22.3, 1.1.1.1 etc. IP addresses can’t be remembered but the host names (e.g. www.networktutorials.info, xyz.com, abc.com) are easy to remember instead of their IP addresses.

What is a Firewall?

Firewall is a protective boundary for a network and it prevents the unauthorized access to a network. Most of the Windows operating system such as Windows XP Professional has built-in firewall utilities. There are the large number of the third party firewall software and the basic purpose of all the firewall software and hardware is same i.e. to block the unauthorized user access to a network.

What is WAN?

WAN stands for wide area network and it covers the broader geographical area. Basically there are three types of a computer network LAN (Local Area Network), MAN (Metropolitan Area Network) and WAN (Wide Area Network). The communication in a WAN is based on the Routers. A WAN network can cover a city, country or continents.

Define VOIP Communication Technology

VOIP stands for Voice over IP and this technology is used for transmitted the voice over the IP based long distance network to make phone calls. VOIP phone calls are very cheap and a large number of the corporate offices and home users are using VOIP technology to make long distance phone calls.

What is Wi Max Technology?

Wi Max is a wireless broadband technology and it is a advance shape of the Wi Fi (which was a base band technology). Wi Max supports data, video and audio communication at the same time at a very high speed up to 70 Mbps.

Define Network Gateway

Network Gateway can be software or a hardware. A gateway is usually a joining point in a network i.e. it connects two networks. A computer with two LAN cards can act as a gateway.

What is a Router?

A router routes the traffic to its destination based on the source and destination IP addresses, which are placed in the routing software known as routing table.

How Fiber Optic Cable Works

Fiber optics provides the fastest communication medium for data and voice. Data can travel at the speed of light through the fiber optic cables. ISPs and corporate offices are usually connected with each other with the fiber optic cables to provide high speed connectivity.

What is File Server?

A file server is a computer in a network that authenticates the user access in a network such as Windows 2000/2003 Servers.

Define Seven Layers of OSI Model

There are seven layers of the OSI model. The basic purpose of these layers is to understand the communication system and data transmission steps. The seven layers are Application, Presentation, Session, Transport, Network, Data Link and Physical. You can remember the name of these layers by this phrase. “All people seems to need data processing”.

Define GSM Technology

GSM is a short range wireless technology and is usually used in the mobile phones, hand help devices, MP3 players, Laptops, computers and in cars.

B. Bashir manages this website Networking Tutorials and regularly writes articles on various topics such as Computer Networking, www.networktutorials.info/communication_types.html" title="Networking Tutorials">Network Communication Technology Wireless Networking, Computer Hardware, Certifications, How Tos.

Networking Interview questions 130

Learn the basic interview questions for the network administrator, system administrator and IT manager jobs. You will get an basic overview of LAN, WAN, Router, Gateway, Wi Max technology, DNS, DHCP, Fiber optic, GSM and voip communication technology.


Computer Networking Interview Questions

Here are the basic interview questions for the network administrators, system administrators and IT manager posts. These questions provide the basic information about the network communication technology, network topologies, network troubleshooting techniques, network devices and the basic overview of the LAN/WAN communication model.

What is DHCP?

DHCP stands for Dynamic Host Configuration Technology. The basic purpose of the DHCP is to assign the IP addresses and the other network configuration such as DNS, Gateway and other network settings to the client computers. DHCP reduces the administrative task of manually assigning the IP addresses to the large number of the computers in a network.

What is DNS and how it works?

DNS stands for Domain name system and it translates (converts) the host name into the IP address and IP address into to the host name. Every domain and the computer on the internet is assigned a unique IP address. The communication on the internet and in the network is based on the IP addresses. IP addresses are in this format 10.1.1.100, 220.12.1.22.3, 1.1.1.1 etc. IP addresses can’t be remembered but the host names (e.g. www.networktutorials.info, xyz.com, abc.com) are easy to remember instead of their IP addresses.

What is a Firewall?

Firewall is a protective boundary for a network and it prevents the unauthorized access to a network. Most of the Windows operating system such as Windows XP Professional has built-in firewall utilities. There are the large number of the third party firewall software and the basic purpose of all the firewall software and hardware is same i.e. to block the unauthorized user access to a network.

What is WAN?

WAN stands for wide area network and it covers the broader geographical area. Basically there are three types of a computer network LAN (Local Area Network), MAN (Metropolitan Area Network) and WAN (Wide Area Network). The communication in a WAN is based on the Routers. A WAN network can cover a city, country or continents.

Define VOIP Communication Technology

VOIP stands for Voice over IP and this technology is used for transmitted the voice over the IP based long distance network to make phone calls. VOIP phone calls are very cheap and a large number of the corporate offices and home users are using VOIP technology to make long distance phone calls.

What is Wi Max Technology?

Wi Max is a wireless broadband technology and it is a advance shape of the Wi Fi (which was a base band technology). Wi Max supports data, video and audio communication at the same time at a very high speed up to 70 Mbps.

Define Network Gateway

Network Gateway can be software or a hardware. A gateway is usually a joining point in a network i.e. it connects two networks. A computer with two LAN cards can act as a gateway.

What is a Router?

A router routes the traffic to its destination based on the source and destination IP addresses, which are placed in the routing software known as routing table.

How Fiber Optic Cable Works

Fiber optics provides the fastest communication medium for data and voice. Data can travel at the speed of light through the fiber optic cables. ISPs and corporate offices are usually connected with each other with the fiber optic cables to provide high speed connectivity.

What is File Server?

A file server is a computer in a network that authenticates the user access in a network such as Windows 2000/2003 Servers.

Define Seven Layers of OSI Model

There are seven layers of the OSI model. The basic purpose of these layers is to understand the communication system and data transmission steps. The seven layers are Application, Presentation, Session, Transport, Network, Data Link and Physical. You can remember the name of these layers by this phrase. “All people seems to need data processing”.

Define GSM Technology

GSM is a short range wireless technology and is usually used in the mobile phones, hand help devices, MP3 players, Laptops, computers and in cars.

About Author

B. Bashir manages this website Networking Tutorials and regularly writes articles on various topics such as Computer Networking, Designing a Network Server Wireless Networking, Computer Hardware, Certifications, How Tos, Optical Network Tutorial and computer tips.

Computer Networking Interview Questions 128

10Base2—An Ethernet term meaning a maximum transfer rate of 10 Megabits per second that uses baseband
signaling, with a contiguous cable segment length of 100
meters and a maximum of 2 segments.
10Base5—An Ethernet term meaning a maximum transfer rate of 10 Megabits per second that uses baseband
signaling, with 5 continuous segments not exceeding 100
meters per segment.
10BaseT—An Ethernet term meaning a maximum transfer rate of 10 Megabits per second that uses baseband
signaling and twisted pair cabling.
4. Explain a Management Information Base (MIB)
A Management Information Base is part of every SNMP-managed device. Each SNMP agent has the MIB database that
contains information about the device's status, its
performance, connections, and configuration. The MIB is queried by SNMP.
5. Explain anonymous FTP and why would you use it
Anonymous FTP enables users to connect to a host without using a valid login and password. Usually, anonymous FTP
uses a login called anonymous or guest, with the
password usually requesting the user's ID for tracking purposes only. Anonymous FTP is used to enable a large number
of users to aCNess files on the host without having
to go to the trouble of setting up logins for them all. Anonymous FTP systems usually have strict controls over the areas
an anonymous user can aCNess.

Networking Interview Questions 126

Basics
· Can you define protocol?
· Can you explain the concept of OSI layer?
· Can you explain the different layers in OSI model?
· Can you explain Application layer in OSI model?
· Can you explain Presentation layer in OSI model?
· Is it compulsory that compression, encryption and translation functions will be
used during communication?
· Can you explain Session layer in OSI model?
· What’s the concept of Simplex, Half Duplex and Full Duplex dialogs?
· What are the different types of dialogs in Session layer?
· Can you explain Transport layer in OSI model?
· Can you explain the concept of Congestion?
· Can you explain Network Layer?
· Can you explain Data link Layer?
· Can you explain the Physical layer?
· Can you explain what an IP address is?
· How to convert Decimal to Binary?
· How many IP addresses can come in IPV4?
· Can you explain the concept of Unicast IP address?
· Can you explain the concept of IP multicasting or multicast IP address?
· How many different types of subnet classful networks are present?
· What are the IP address ranges for public and private IP address?
· Why do we need class and how many different types of class exists?
· How are the IP addresses distributed between different classes?
· Can you explain what is classful IP addressing?
· Can you explain the concept of subnetting?
· What are the advantages of using subneting?
· If the host has the subnet ID why do we need a subnet mask?
· How is network address calculated from the subnet?
· What is the advantage of using classless addressing over classful addressing
scheme?
· Can you explain the concept of CIDR?
· Twist: - Can you explain superneting?
· Can you explain concept of custom subneting?
· What is the implication of increasing and decreasing subnet Bits?
· Why do we need to subtract two from number of hosts?
· Can you explain the concept of VLSM?
· Can you explain IP packet in detail?

Routers
· Can you explain the concept of DPU, Segments, Datagram, Frame and packet?
· What is IP datagram fragmentation and MTU?
· Can you explain in detail with example how data fragmentation works?
· Larger the IP datagram less the overhead, is it true or false?
· What is the minimum size of MTU bytes?
· Can you explain how optimal MTU size is calculated?
· How does the IP message finally reassemble?
· Can you explain the concept of Repeaters, Hubs, Bridges, Switches and Routers?
· On what layers do router, switches, bridges and hubs operate?
· Can you explain the concept of Layer 3 switches?
· What are CSU, DSU and TSU?
· What are the basic components of the router?
· Can you explain the WAN and LAN Interface in Routers?
· What are DB-15, DB-60 and RJ-45 in CISCO routers?
· Can you explain the concept of TTL?
· What is the concept of ICMP packets?
· Which operating system does CISCO have?
· Can you explain the concept of NAT?
· How is NAT implemented?
· Can you explain how actually NAT works?
· Why does collision occur in HUBS and repeaters?
· Can you explain the concept of Collision domain?
· What is the concept of routing tables?
· What is the use of route print?
· Can you explain how in detail how routing table looks like?
· How can you see route tables on the router?
· Can you explain the concept of static and dynamic routing?
· When to use Static routes and dynamic routes?
· How do you configure static routes on a router?
· Can you explain static default routes?
· What is the advantage of using Static default routes?
· Why do workstations have route tables?
· What is the concept of gateway of last resort?
· Can you explain the concept of routing protocol?
· What activities does routing protocol perform?
· What metrics are used by routing protocols to determine the best path?
· Can you explain what is interior and exterior routing protocols?
· Can you explain the concept of intradomain and interdomain routing protocols?
· Can you explain the concept of internet work and intranet work routing protocols?
· Which method does routing protocol use to determine shortest path?
· What is distance vector routing protocol?
· How do routers share information in Distance Vector routing?
· What is the main issue with routing by rumor?
· Can you explain the count-to- infinity problem in distance vector?
· How is metric or the cost calculated for Distance Vector routing protocol?
· What is the main issue with hop count metric issue?
· Can you explain how Link-State routing protocols work?
· Can you explain the concept of broad cast and multi-cast?
· Can you tell which protocols falls in Distance vector and which in Link-State?
· What’s the difference between distance vector and link-state protocol?
· Can you explain difference between Single path and Multipath?
· Can you explain route summarization?
· How are the series of IP combined in to one route path in route summarization?
· Can you explain RIP protocol?
· How is route table populated by RIP protocol?
· Can you explain convergence in networks?
· Can you explain RIP timers in detail?
· Can you explain routing loop issue in RIP protocol?
· How do we avoid routing loop issue in RIP?
· In RIP why do we have HOP count of 15?
· How do we disable auto-summarization in RIP?
· Can you explain IGRP?
· How does IGRP work?
· How many timers does IGRP have?
· How does IGRP calculate metric?
· Can multiple instance of IGRP run on one physical router?
· How is load balancing done in IGRP?
· What’s the command to configure IGRP?
· Can you explain EIGRP?
· What does neighbor terminology mean in EIGRP?
· What are different types of packets in EIGRP?
· How does EIGRP protocol update route information to its neighbors?
· What is the concept of successor in EIGRP?
· What is DUAL in EIGRP?
· Can you explain reported distance (RD), feasibility distance (FD) and Feasibility
condition (FC)?
· Can you explain the concept of successor and feasible successor?
· Can you explain passive and active route states?
· What is SIA or stuck in active?
· How do packets and timers in EIGRP work?
· What are the different tables used in EIGRP?
· Can you explain EIGRP metrics?
· Can you explain how EIGRP finds its successor and feasible successor?
· Can you explain Active and Passive route?
· Can you explain OSPF?
· How does OSPF populate route table?
· What are the different tables in OSPF?
· Can you explain different areas in OSPF?
· Can you explain different router types in OSPF?
· Can you explain Designated Router and Backup designated router?
· Can you explain different router states in OSPF?
· Can you explain different OSPF packet types?
· What are the different types of OSPF timers?
· How SPF algorithm does the route determination?
· Can you explain autonomous system?
· What are different types of dynamic protocols?
· Can you explain autonomous numbers in EGP?
· What is BGP?
· What is the concept of BGP speakers and Peers?
· What is EBGP and IBGP?
· What is RIB?
· Can you explain the concept of BGP confederations?
· What are BGP path attributes?
· What is the concept of NLRI?
· How are routing neighbors discovered in BGP?
· Can you explain how BGP does the decision process?
· What is the concept of redistribution?
· Can you explain the concept of one way redistribution and mutual distribution?
· How does metric translation takes place in redistributing routes?

Firewall
· Can you define what a FIREWALL is?
· What are the different types of firewalls?
· Can you explain packet filtering firewall?
· Can you explain circuit level gateway?
· Can you explain stateful inspection?
· What is Application Gateway?
· Is NAT a firewall?
· Are personal firewall actually firewalls?
· Can you explain the concept of demilitarized zone?
· What is the meaning of bastion host?
· What are the different types of firewall architectures?
· Can you explain dual home architecture?
· Can you explain screened host architecture?
· Can you explain screened subnet architecture?
· What is the use of perimeter area?
· What is IP spoofing and how can it be prevented?
· Which firewall have you worked with?

VPN
· Can you explain the difference between trusted and untrusted networks?
· Can you define in short what VPN is?
· What are the different types of VPN?
· What requirements should a VPN fulfill?
· How many ways are there to implement VPN architecture?
· What are the different ways authentication mechanism in VPN?
· Can you explain the basic of encryption in VPN?
· What’s the difference between Symmetric and Asymmetric cryptosystem?
· What are the different symmetric algorithms?
· What are the disadvantages of symmetric algorithms?
· What are the different asymmetric algorithms?
· Can you explain different components in PKI?
· What is a digital certificate?
· Can you explain tunneling?
· What is the concept of HA and FA in VPN tunneling?
· Can you explain VPN tunneled packet in detail?
· Can you explain voluntary and compulsory tunnels?
· Can you explain static and dynamic tunnels?
· Can you explain encapsulating, carrier and passenger protocol?
· On which layer does L2F, PPTP and L2TP operate?
· Can you explain PPP protocol?
· Can you explain PPP link process step by step?
· Can you explain PPP packet format?
· How does PPP use LCP for link control?
· Can you explain PPTP (Point-to-Point Tunneling Protocol)?
· What is GRE in PPTP?
· How does PPTP encapsulate data?
· Can you explain CHAP?
· Can you explain PAP?
· What does PPTP use for encryption and authentication?
· What is a L2F protocol?
· Can you explain the broader steps of how L2F establishes the tunnel?
· Can you explain how L2F data tunneling process works?
· How do we do encryption and authentication in L2F?
· Can you explain L2TP?
· Can you define LAC and LNS?
· How does L2TP process?
· How do we do encryption and authentication in L2TP?
· Can you explain what IPSec is?
· Can you give an overview of various components in IPSec?
· In IPSec what is SAD, SPD and SA’s?
· Can you explain in a generic manner the packet of IPSec?
· Can you describe the Authentication Header (AH) Protocol?
· What is ESP (Encapsulating Security Payload)?
· What is Transport and Tunnel mode?
· Can you explain IKE (Internet Key Exchange)?
· Can you explain IKE phases?
· Can you explain IKE modes?
· Can you explain transport and tunnel mode in detail with datagram packets?

Protocols and other questions
· What is NetBIOS protocol?
· Can you explain what the use of IGMP Protocol is?
· What are the different types of host in multicasting?
· Can you explain Ping and Tracert?
· How do you continuously ping an IP Address?
· How does Tracert actually work?
· What is the use of RTP and RTCP Protocol?
· Can you explain RTP in Detail?
· Can you explain RTP multiplexing in detail?
· Can you explain format of RTP and RTCP packets?
· Can you explain RSVP?
· Can you explain in detail how RSVP actually works?
· Can you explain RPC (Remote Procedure Calls)?
· Can you explain the RPC and Client server Architecture?
· Can you explain TCP IP Protocol?
· Can you explain the architecture of TCP IP Protocol?
· Can you explain TCP header in detail?
· Can you explain IP protocol?
· Can you explain the concept of CDMA?
· Can you explain the concept of DHCP?
· How does DHCP work?
· How can we configure DHCP?
· What is DNS?
· How do we control USB through a network?
· What is the difference between Windows 2000 and Windows 2003?
· What is a difference between a domain and workgroup?

Monday, April 14, 2008

JAVA QUESTIONS 125

JAVA QUESTIONS

What is the difference between an Abstract class and Interface?
What is user defined exception?
What do you know about the garbage collector?
What is the difference between java and c++?
In an HTML form I have a button which makes us to open another page in 15 seconds. How will you do that?
What is the difference between process and threads?
What is update method called?
Have you ever used HashTable and Directory?
What are statements in Java?
What is a JAR file?
What is JNI?
What is the base class for all swing components?
What is JFC?
What is the difference between AWT and Swing?
Considering notepad/IE or any other thing as process, What will happen if you start notepad or IE 3 times ? Where three processes are started or three threads are started?
How does thread synchronization occur in a monitor?
Is there any tag in HTML to upload and download files?
Why do you canvas?
How can you know about drivers and database information ?
What is serialization?
Can you load the server object dynamically? If so what are the 3 major steps involved in it?
What is the layout for toolbar?
What is the difference between Grid and Gridbaglayout?
How will you add panel to a frame?
Where are the card layouts used?
What is the corresponding layout for card in swing?
What is light weight component?
Can you run the product development on all operating systems?
What are the benefits if Swing over AWT?
How can two threads be made to communicate with each other?
What are the files generated after using IDL to java compiler?
What is the protocol used by server and client?
What is the functionability stubs and skeletons?
What is the mapping mechanism used by java to identify IDL language?
What is serializable interface?
What is the use of interface?
Why is java not fully objective oriented?
Why does java not support multiple inheritance?
What is the root class for all java classes?
What is polymorphism?
Suppose if we have a variable 'I' in run method, if I can create one or more thread each thread will occupy a separate copy or same variable will be shared?
What are virtual functions?
Write down how will you create a Binary tree?
What are the traverses in binary tree?
Write a program for recursive traverse?
What are session variable in servlets?
What is client server computing?
What is constructor and virtual function? Can we call a virtual function in a constructor?
Why do we use oops concepts? What is its advantage?
What is middleware? What is the functionality of web server?
Why is java not 100% pure oops?
When will you use an interface and abstract class?
What is the exact difference in between Unicast and Multicast object? Where will it be used?
What is the main functionality of the remote reference layer?
How do you download stubs from Remote place?
I want to store more than 10 objects in a remote server? Which methodology will follow?
What is the main functionality of Prepared Statement?
What is meant by Static query and Dynamic query?
What are Normalization Rules? Define Normalization?
What is meant by Servelet? What are the parameters of service method?
What is meant by Session? Explain something about HTTP Session Class?
In a container there are 5 components. I want to display all the component names, how will you do that?
Why there are some null interface in JAVA? What does it mean? Give some null interface in JAVA?
Tell some latest versions in JAVA related areas?
What is meant by class loader? How many types are there? When will we use them?
What is meant by flickering?
What is meant by distributed application? Why are we using that in our application?
What is the functionality of the stub?
Explain about version control?
Explain 2-tier and 3-tier architecture?
What is the role of Web Server?
How can we do validation of the fields in a project?
What is meant by cookies? Explain the main features?
Why java is considered as platform independent?
What are the advantages of java over C++?
How java can be connected to a database?
What is thread?
What is difference between Process and Thread?
Does java support multiple inheritance? if not, what is the solution?
What are abstract classes?
What is an interface?
What is the difference abstract class and interface?
What are adapter classes?
what is meant wrapper classes?
What are JVM.JRE, J2EE, JNI?
What are swing components?
What do you mean by light weight and heavy weight components?
What is meant by function overloading and function overriding?
Does java support function overloading, pointers, structures, unions or linked lists?
What do you mean by multithreading?
What are byte codes?
What are streams?
What is user defined exception?
In an HTML page form I have one button which makes us to open a new page in 15 seconds. How will you do that?

JAVA INTERVIEW QUESTIONS 120

Basic concepts
 What is it object serialization ?
Serialization is a way to convert objects (including complex data structures such as lists and trees) into a stream of bytes.
 What is it reflection (introspection) ? Why is reflection possible in the Java language?
Reflection (introspection) is querying a class about its properties, and operating on methods and fields by the name for a given object instance. Reflection is possible in the Java language because of late binding.
 How do I synchronize a block of code without declaring the entire method synchronized?
One should use something like synchronized(this){...}
 Can you synchronize a block of code within a static method?
Of course. You should write something like that:
class C
{
static char[] x = new int[5];
static void setX(int i, char value)
{
synchronized(x)
{
x[i] = value;
}
}
}
 What are the four member access level for Java?
public,private,protected,package.
User interface
 What is the purpose of the toolkit in the Abstract Window Toolkit (AWT)? How does AWT work ?
The AWT toolkit is an interface between the abstract window layer and a specific windowing implementation.
 What is layout manager ? How does it work ?
A layout manager is an object that positions and resizes the components in a Container according to some algorithm; for example, the FlowLayout layout manager lays out components from left to right until it runs out of room and then continues laying out components below that row.
 Advantages and disadvantages of layout manager?
The biggest advantage is the standard way of implementing the user interface for cross-platform application. Disadvantages are:
- Challenge to create a custom layout if the standard one does not fit in your model
- Inability to use native UI features of concrete operating system that might be quite useful especially for complex UI tasks (however, this is against the Java philosophy and quite understandable drawback)
 Compare SWING components to standard AWT.
Swing is an extension of, and not a replacement for the AWT. There is some overlap between AWT and Swing (for example a Swing JButton component might be viewed as an improved functional replacement for an AWT Button component.) One of the advantages of Swing components is that because the components are not rendered on the screen by the operating system, the look and feel of a component does not change as the application or applet is executed on different platforms running under different operating systems. Furthermore, it is possible to cause Swing components to mimic the look and feel of a specific platform no matter what platform the program is running on. This is known as pluggable look and feel. Swing components support the JDK 1.1 Delegation Event Model. From an event handling viewpoint, Swing components operate the same as AWT components (except that Swing provides a number of new event types). Many Swing components don't have an AWT counterpart. A number of new and exciting components are included in the Swing library that don't exist in the AWT (tooltips, progress bars, trees, etc.)
Java Beans
 What is Java Beans ?
According to JavaSoft, "A Java Bean is a reusable software component that can be manipulated visually in a builder tool."
Networking
 What you know about Corba implementation in Java?
Java 1.2 promises full CORBA IDL support.
 What do you know about networking support in Java?
Java supports "low-level" and "high-level" classes. "Low-level" classes provide support for socket programming: Socket, DatagramSocket, and ServerSocket classes. "High-level" classes provide "Web programming": URL, URLEncoder, and URLConnection classes. Networking programming classes ease the programming of network applications, but do not substitute your knowledge of networking. Java networking like anything else in Java is platform-independent.
Threads
 How to make application thread-safe ?
You should use the word synchronized to mark the critical section of code. You may also use other methods of thread synchronization (see wait(), notify(), notifyAll() etc.
Deployment
 Why are Java ARchive (JAR) files important?
JAR files bundle .class files and optimize applet downloads.

Core Java Test Paper1 116

Which of the following will output -4.0
1) System.out.println(Math.floor(-4.7));
2) System.out.println(Math.round(-4.7));
3) System.out.println(Math.ceil(-4.7));
4) System.out.println(Math.min(-4.7));
Question 25)
What will happen if you attempt to compile and run the
following code?
Integer ten=new Integer(10);
Long nine=new Long (9);
System.out.println(ten + nine);
int i=1;
System.out.println(i + ten);
1) 19 followed by 20
2) 19 followed by 11
3) Error: Can't convert java lang Integer
4) 10 followed by 1
Question 33)
What will happen when you attempt to compile and run the
following code?.
1) It will compile and the run method will print out the
increasing value of i.
2) It will compile and calling start will print out the
increasing value of i.
3) The code will cause an error at compile time.
4) Compilation will cause an error because while cannot take a
parameter of true.
class Background implements Runnable{
int i=0;
public int run(){
while(true){
i++;
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
System.out.println("i="+i);
} //End while
return 1;
}//End run
}//End class
Question 38)
How can you change the current working directory using an
instance of the File class called FileName?
1) FileName.chdir("DirName")
2) FileName.cd("DirName")
3) FileName.cwd("DirName")
4) The File class does not support directly changing the
current directory.
Question 46)
You need to create a class that will store a unique object
elements. You do not need to sort these elements but they must
be unique.
What interface might be most suitable to meet this need?
1)Set
2)List
3)Map
4)Vector
Question 47)
Which of the following will successfully create an instance of
the Vector class and add an element?
1) Vector v=new Vector(99);
v[1]=99;
2) Vector v=new Vector();
v.addElement(99);
3) Vector v=new Vector();
v.add(99);
4 Vector v=new Vector(100);
v.addElement("99");
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
Question 49)
What will be the result when you attempt to compile this
program?
public class Rand{
public static void main(String argv[]){
int iRand;
iRand = Math.random();
System.out.println(iRand);
}
}
1) Compile time error referring to a cast problem
2) A random number between 1 and 10
3) A random number between 0 and 1
4) A compile time error about random being an unrecognised
method
Question 50)
Given the following code
import java.io.*;
public class Th{
public static void main(String argv[]){
Th t = new Th();
t.amethod();
}
public void amethod(){
try{
ioCall();
}catch(IOException ioe){}
}
}
What code would be most likely for the body of the ioCall
method
1) public void ioCall ()throws IOException{
DataInputStream din = new DataInputStream(System.in);
din.readChar();
}
2) public void ioCall ()throw IOException{
DataInputStream din = new DataInputStream(System.in);
din.readChar();
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
}
3) public void ioCall (){
DataInputStream din = new DataInputStream(System.in);
din.readChar();
}
4) public void ioCall throws IOException(){
DataInputStream din = new DataInputStream(System.in);
din.readChar();
}
Question 53)
Which of the following can you perform using the File class?
1) Change the current directory
2) Return the name of the parent directory
3) Delete a file
4) Find if a file contains text or binary information
Question 55)
You are concerned that your program may attempt to use more
memory than is available. To avoid this situation you want to
ensure that the Java Virtual Machine will run its garbage
collection just before you start a complex routine. What can
you do to be certain that garbage collection will run when you
want .
1) You cannot be certain when garbage collection will run
2) Use the Runtime.gc() method to force garbage collection
3) Ensure that all the variables you require to be garbage
collected are set to null
4) Use the System.gc() method to force garbage collection
jd2
8) What will happen when you attempt to compile and run this
code?
private class Base{}
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
public class Vis{
transient int iVal;
public static void main(String elephant[]){
}
}
1)Compile time error: Base cannot be private
2)Compile time error indicating that an integer cannot be
transient
3)Compile time error transient not a data type
4)Compile time error malformed main method
9) What happens when you attempt to compile and run these two
files in the same directory?
//File P1.java
package MyPackage;
class P1{
void afancymethod(){
System.out.println("What a fancy method");
}
}
//File P2.java
public class P2 extends P1{
afancymethod();
}
1) Both compile and P2 outputs "What a fancy method" when run
2) Neither will compile
3) Both compile but P2 has an error at run time
4) P1 compiles cleanly but P2 has an error at compile time
Question 18)
What will happen when you attempt to compile and run the
following code?
public class Bground extends Thread{
public static void main(String argv[]){
Bground b = new Bground();
b.run();
}
public void start(){
for (int i = 0; i <10; i++){
System.out.println("Value of i = " +
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
i);
}
}
}
Question 20)
Which most closely matches a description of a Java Map?
1) A vector of arrays for a 2D geographic representation
2) A class for containing unique array elements
3) A class for containing unique vector elements
4) An interface that ensures that implementing classes cannot
contain duplicate keys
Question 21)
How does the set collection deal with duplicate elements?
1) An exception is thrown if you attempt to add an element
with a duplicate value
2) The add method returns false if you attempt to add an
element with a duplicate value
3) A set may contain elements that return duplicate values
from a call to the equals method
4) Duplicate values will cause an error at compile time
Question 22)
What can cause a thread to stop executing?
1) The program exits via a call to System.exit(0);
2) Another thread is given a higher priority
3) A call to the thread's stop method.
4) A call to the halt method of the Thread class
Question 23)
For a class defined inside a method, what rule governs access
to the variables of the enclosing method?
1) The class can access any variable
2) The class can only access static variables
3) The class can only access transient variables
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
4) The class can only access final variables
Question 24)
Under what circumstances might you use the yield method of the
Thread class
1) To call from the currently running thread to allow another
thread of the same priority to run
2) To call on a waiting thread to allow it to run
3) To allow a thread of higher priority to run
4) To call from the currently running thread with a parameter
designating which thread should be allowed to run
Question 25)
What will happen when you attempt to compile and run the
following code
public class Hope{
public static void main(String argv[]){
Hope h = new Hope();
}
protected Hope(){
for(int i =0; i <10; i ++){
System.out.println(i);
}
}
}
1) Compilation error: Constructors cannot be declared
protected
2) Run time error: Constructors cannot be declared protected
3) Compilation and running with output 0 to 10
4) Compilation and running with output 0 to 9
Question 26)
What will happen when you attempt to compile and run the
following code
public class MySwitch{
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
public static void main(String argv[]){
MySwitch ms= new MySwitch();
ms.amethod();
}
public void amethod(){
int k=10;
switch(k){
default: //Put the default at the bottom, not here
System.out.println("This is the default output");
break;
case 10:
System.out.println("ten");
case 20:
System.out.println("twenty");
break;
}
}
}
1) None of these options
2) Compile time errror target of switch must be an integral
type
3) Compile and run with output "This is the default output"
4) Compile and run with output "ten"
Question 27)
Which of the following is the correct syntax for suggesting
that the JVM performs garbage collection
1) System.free();
2) System.setGarbageCollection();
3) System.out.gc();
4) System.gc();
Question 28)
What will happen when you attempt to compile and run the
following code
public class As{
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
int i = 10;
int j;
char z= 1;
boolean b;
public static void main(String argv[]){
As a = new As();
a.amethod();
}
public void amethod(){
System.out.println(j);
System.out.println(b);
}
}
1) Compilation succeeds and at run time an output of 0 and
false
2) Compilation succeeds and at run time an output of 0 and
true
3) Compile time error b is not initialised
4) Compile time error z must be assigned a char value
Question 29)
What will happen when you attempt to compile and run the
following code with the command line "hello there"
public class Arg{
String[] MyArg;
public static void main(String argv[]){
MyArg=argv;
}
public void amethod(){
System.out.println(argv[1]);
}
}
1) Compile time error
2) Compilation and output of "hello"
3) Compilation and output of "there"
4) None of the above
Question 30)
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
What will happen when you attempt to compile and run the
following code
public class StrEq{
public static void main(String argv[]){
StrEq s = new StrEq();
}
private StrEq(){
String s = "Marcus";
String s2 = new String("Marcus");
if(s == s2){
System.out.println("we have a match");
}else{
System.out.println("Not equal");
}
}
}
1) Compile time error caused by private constructor
2) Output of "we have a match"
3) Output of "Not equal"
4) Compile time error by attempting to compare strings using
==
Question 31)
1) What will happen when you attempt to compile and run the
following code
import java.io.*;
class Base{
public static void amethod()throws FileNotFoundException{}
}
public class ExcepDemo extends Base{
public static void main(String argv[]){
ExcepDemo e = new ExcepDemo();
}
public static void amethod(){}
protected ExcepDemo(){
try{
DataInputStream din = new DataInputStream(System.in);
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
System.out.println("Pausing");
din.readChar();
System.out.println("Continuing");
this.amethod();
}catch(IOException ioe) {}
}
}
1)Compile time error caused by protected constructor
2) Compile time error caused by amethod not declaring
Exception
3) Runtime error caused by amethod not declaring Exception
4) Compile and run with output of "Pausing" and "Continuing"
after a key is hit
Question 32)
What will happen when you attempt to compile and run this
program
public class Outer{
public String name = "Outer";
public static void main(String argv[]){
Inner i = new Inner();
i.showName();
}//End of main
private class Inner{
String name =new String("Inner");
void showName(){
System.out.println(name);
}
}//End of Inner class
}
1) Compile and run with output of "Outer"
2) Compile and run with output of "Inner"
3) Compile time error because Inner is declared as private
4) Compile time error because of the line creating the
instance of Inner
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
Question 34)
Which option most fully describes will happen when you attempt
to compile and run the following code
public class MyAr{
public static void main(String argv[]) {
MyAr m = new MyAr();
m.amethod();
}
public void amethod(){
static int i;
System.out.println(i);
}
}
1) Compilation and output of the value 0
2) Compile time error because i has not been initialized
3) Compilation and output of null
4) Compile time error
Question 35)
Which of the following will compile correctly
1) short myshort = 99S;
2) String name = 'Excellent tutorial Mr Green';
3) char c = 17c;
4)int z = 015;
Question 36)
Which of the following are Java key words
1)double
2)Switch
3)then
4)instanceof
Question 37
What will be output by the following line?
System.out.println(Math.floor(-2.1));
1) -2
2) 2.0
3) -3
4) -3.0
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
Question 38)
Given the following main method in a class called Cycle and a
command line of
java Cycle one two
what will be output?
public static void main(String bicycle[]){
System.out.println(bicycle[0]);
}
1) None of these options
2) cycle
3) one
4) two
Question 39)
Which of the following statements are true?
1) At the root of the collection hierarchy is a class called
Collection
2) The collection interface contains a method called
enumerator
3) The interator method returns an instance of the Vector
class
4) The set interface is designed for unique elements
Question 41)
Given the following code
class Base{}
public class MyCast extends Base{
static boolean b1=false;
static int i = -1;
static double d = 10.1;
public static void main(String argv[]){
MyCast m = new MyCast();
Base b = new Base();
//Here
}
}
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
Which of the following, if inserted at the comment //Here will
allow the code to compile and run without error
1) b=m;
2) m=b;
3) d =i;
4) b1 =i;
Question 42)
Which of the following statements about threading are true
1) You can only obtain a mutually exclusive lock on methods in
a class that extends Thread or implements runnable
2) You can obtain a mutually exclusive lock on any object
3) A thread can obtain a mutually exclusive lock on a method
declared with the keyword synchronized
4) Thread scheduling algorithms are platform dependent
Question 43)
Your chief Software designer has shown you a sketch of the new
Computer parts system she is about to create. At the top of
the hierarchy is a Class called Computer and under this are
two child classes. One is called LinuxPC and one is called
WindowsPC. The main difference between the two is that one
runs the Linux operating System and the other runs the Windows
System (of course another difference is that one needs
constant re-booting and the other runs reliably). Under the
WindowsPC are two Sub classes one called Server and one Called
Workstation. How might you appraise your designers work?
1) Give the goahead for further design using the current
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
scheme
2) Ask for a re-design of the hierarchy with changing the
Operating System to a field rather than Class type
3) Ask for the option of WindowsPC to be removed as it will
soon be obsolete
4) Change the hierarchy to remove the need for the superfluous
Computer Class.
Question 44)
Objective 4.1)
Which of the following statements are true
1) An inner class may be defined as static
2) There are NO circumstances where an inner class may be
defined as private
3) An anonymous class may have only one constructor
4) An inner class may extend another class
Question 45)
What will happen when you attempt to compile and run the
following code
int Output=10;
boolean b1 = false;
if((b1==true) && ((Output+=10)==20)){
System.out.println("We are equal "+Output);
}else
{
System.out.println("Not equal! "+Output);
}
1) Compile error, attempting to peform binary comparison on
logical data type
2) Compilation and output of "We are equal 10"
3) Compilation and output of "Not equal! 20"
4) Compilation and output of "Not equal! 10"
Question 49)
Which of the following will compile without error?
1) File f = new File("/","autoexec.bat");
2) DataInputStream d = new DataInputStream(System.in);
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
3) OutputStreamWriter o = new OutputStreamWriter(System.out);
4) RandomAccessFile r = new RandomAccessFile("OutFile");
Question 50)
Given the folowing classes which of the following will compile
without error?
interface IFace{}
class CFace implements IFace{}
class Base{}
public class ObRef extends Base{
public static void main(String argv[]){
ObRef ob = new ObRef();
Base b = new Base();
Object o1 = new Object();
IFace o2 = new CFace();
}
}
1)o1=o2;
2)b=ob;
3)ob=b;
4)o1=b;
Question 51)
Given the following code what will be the output?
class ValHold{
public int i = 10;
}
public class ObParm{
public static void main(String argv[]){
ObParm o = new ObParm();
o.amethod();
}
public void amethod(){
int i = 99;
ValHold v = new ValHold();
v.i=30;
another(v,i);
System.out.println(v.i);
}//End of amethod
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
public void another(ValHold v, int i){
i=0;
v.i = 20;
ValHold vh = new ValHold();
v = vh;
System.out.println(v.i+ " "+i);
}//End of another
}
1) 10,0, 30
2) 20,0,30
3) 20,99,30
4) 10,0,20
Question 52)
Given the following class definition, which of the following
methods could be legally placed after the comment
//Here
public class Rid{
public void amethod(int i, String s){}
//Here
}
1)public void amethod(String s, int i){}
2)public int amethod(int i, String s){}
3)public void amethod(int i, String mystring){}
4) public void Amethod(int i, String s) {}
Question 53)
Given the following class definition which of the following
can be legally placed after the comment line
//Here ?
class Base{
public Base(int i){}
}
public class MyOver extends Base{
public static void main(String arg[]){
MyOver m = new MyOver(10);
}
MyOver(int i){
super(i);
}
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
MyOver(String s, int i){
this(i);
//Here
}
}
1)MyOver m = new MyOver();
2)super();
3)this("Hello",10);
4)Base b = new Base(10);
Question 54)
Given the following class definition, which of the following
statements would be legal after the comment //Here
class InOut{
String s= new String("Between");
public void amethod(final int iArgs){
int iam;
class Bicycle{
public void sayHello(){
//Here
}//End of bicycle class
}
}//End of amethod
public void another(){
int iOther;
}
}
1)System.out.println(s);
2) System.out.println(iOther);
3) System.out.println(iam);
4) System.out.println(iArgs);
Question 55)
Which of the following are methods of the Thread class?
1) yield()
2) sleep(long msec)
3) go()
4) stop()
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
Question 56)
Which of the following methods are members of the Vector class
and allow you to input a new element
1) addElement
2) insert
3) append
4) addItem
Question 57)
Which of the following statements are true?
1) Adding more classes via import statements will cause a
performance overhead, only import classes you actually use.
2) Under no circumstances can a class be defined with the
private modifier
3) A inner class may under some circumstances be defined with
the protected modifier
4) An interface cannot be instantiated
Question 59)
Which of the following are methods of the Collection
interface?
1) iterator
2) isEmpty
3) toArray
4) setText
Question 60)
Which of the following best describes the use of the
synhronized keyword?
1) Allows two process to run in paralell but to communicate
with each other
2) Ensures only one thread at a time may access a class or
object
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
3) Ensures that two or more processes will start and end at
the same time
4) Ensures that two or more Threads will start and end at the
same time
JD4
Q 1. What is the output of the following
StringBuffer sb1 = new StringBuffer("Amit");
StringBuffer sb2= new StringBuffer("Amit");
String ss1 = "Amit";
System.out.println(sb1==sb2);
System.out.println(sb1.equals(sb2));
System.out.println(sb1.equals(ss1));
System.out.println("Poddar".substring(3));
Ans:
a) false
false
false
dar
b) false
true
false
Poddar
c) Compiler Error
d) true
true
false
dar
Q9. What is the output of following if the return value is "the value 0 if the argument
string is equal to this string; a value less than 0 if this string is lexicographically less than
the string argument; and a value greater than 0 if this string is lexicographically greater
than the string argument" (Assuming written inside main)
String s5 = "AMIT";
String s6 = "amit";
System.out.println(s5.compareTo(s6));
System.out.println(s6.compareTo(s5));
System.out.println(s6.compareTo(s6));
Ans
a> -32
32
0
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
b> 32
32
0
c> 32
-32
0
d> 0
0
0
Q 10) What is the output (Assuming written inside main)
String s1 = new String("amit");
String s2 = s1.replace('m','i');
s1.concat("Poddar");
System.out.println(s1);
System.out.println((s1+s2).charAt(5));
a) Compile error
b) amitPoddar
o
c) amitPoddar
i
d) amit
i
Q 11) What is the output (Assuming written inside main)
String s1 = new String("amit");
System.out.println(s1.replace('m','r'));
System.out.println(s1);
String s3="arit";
String s4="arit";
String s2 = s1.replace('m','r');
System.out.println(s2==s3);
System.out.println(s3==s4);
a) arit
amit
false
true
b) arit
arit
false
true
c) amit
amit
false
true
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
d) arit
amit
true
true
Q12) Which one does not extend java.lang.Number
1)Integer
2)Boolean
3)Character
4)Long
5)Short
Q13) Which one does not have a valueOf(String) method
1)Integer
2)Boolean
3)Character
4)Long
5)Short
Q.14) What is the output of following (Assuming written inside main)
String s1 = "Amit";
String s2 = "Amit";
String s3 = new String("abcd");
String s4 = new String("abcd");
System.out.println(s1.equals(s2));
System.out.println((s1==s2));
System.out.println(s3.equals(s4));
System.out.println((s3==s4));
a) true
true
true
false
b) true
true
true
true
c) true
false
true
false
Q17) What will be the output of line 5
1 Choice c1 = new Choice();
2 c1.add("First");
3 c1.addItem("Second");
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
4 c1.add("Third");
5 System.out.println(c1.getItemCount());
a) 1
b) 2
c) 3
d) None of the above
Q18) What will be the order of four items added
Choice c1 = new Choice();
c1.add("First");
c1.addItem("Second");
c1.add("Third");
c1.insert("Lastadded",2);
System.out.println(c1.getItemCount());
a) First,Second,Third,Fourth
b) First,Second,Lastadded,Third
c) Lastadded,First,Second,Third
Q19) Answer based on following code
1 Choice c1 = new Choice();
2 c1.add("First");
3 c1.addItem("Second");
4 c1.add("Third");
5 c1.insert("Lastadded",1000);
6 System.out.println(c1.getItemCount());
a) Compile time error
b) Run time error at line 5
c) No error and line 6 will print 1000
d) No error and line 6 will print 4
Q24. Q. What will be the output of follwing
{
double d1 = -0.5d;
System.out.println("Ceil for d1 " + Math.ceil(d1));
System.out.println("Floor for d1 " +Math.floor(d1));
}
Answers:
a) Ceil for d1 0
Floor for d1 -1;
b) Ceil for d1 0
Floor for d1 -1.0;
c) Ceil for d1 0.0
Floor for d1 -1.0;
d) Ceil for d1 -0.0
Floor for d1 -1.0;
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
Q25. What is the output of following
{
float f4 = -5.5f;
float f5 = 5.5f;
float f6 = -5.49f;
float f7 = 5.49f;
System.out.println("Round f4 is " + Math.round(f4));
System.out.println("Round f5 is " + Math.round(f5));
System.out.println("Round f6 is " + Math.round(f6));
System.out.println("Round f7 is " + Math.round(f7));
}
a)Round f4 is -6
Round f5 is 6
Round f6 is -5
Round f7 is 5
b)Round f4 is -5
Round f5 is 6
Round f6 is -5
Round f7 is 5
Q26. Given Integer.MIN_VALUE = -2147483648
Integer.MAX_VALUE = 2147483647
What is the output of following
{
float f4 = Integer.MIN_VALUE;
float f5 = Integer.MAX_VALUE;
float f7 = -2147483655f;
System.out.println("Round f4 is " + Math.round(f4));
System.out.println("Round f5 is " + Math.round(f5));
System.out.println("Round f7 is " + Math.round(f7));
}
a)Round f4 is -2147483648
Round f5 is 2147483647
Round f7 is -2147483648
b)Round f4 is -2147483648
Round f5 is 2147483647
Round f7 is -2147483655
Q27)
1 Boolean b1 = new Boolean("TRUE");
2 Boolean b2 = new Boolean("true");
3 Boolean b3 = new Boolean("JUNK");
4 System.out.println("" + b1 + b2 + b3);
a) Comiler error
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
b) RunTime error
c)truetruefalse
d)truetruetrue
Q 28) In the above Question if line 4 is changed to
System.out.println(b1+b2+b3); The output is
a) Compile time error
b) Run time error
c) truetruefalse
d) truetruetrue
Q 29. What is the output
{
Float f1 = new Float("4.4e99f");
Float f2 = new Float("-4.4e99f");
Double d1 = new Double("4.4e99");
System.out.println(f1);
System.out.println(f2);
System.out.println(d1);
}
a) Runtime error
b) Infinity
-Infinity
4.4E99
c) Infinity
-Infinity
Infinity
d) 4.4E99
-4.4E99
4.4E99
Q30 Q. Which of the following wrapper classes can not
take a "String" in constructor
1) Boolean
2) Integer
3) Long
4) Character
5) Byte
6) Short
Q31. What is the output of following
Double d2 = new Double("-5.5");
Double d3 = new Double("-5.5");
System.out.println(d2==d3);
System.out.println(d2.equals(d3));
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
a) true
true
b) false
false
c) true
false
d) false
true
Q37) Consider a directory structure like this (NT or 95)
C:\JAVA\12345.msg --FILE
\dir1\IO.class -- IO.class is under dir1
Consider the following code
import java.io.*;
public class IO {
public static void main(String args[]) {
File f = new File("..\\12345.msg");
try{
System.out.println(f.getCanonicalPath());
System.out.println(f.getAbsolutePath());
}catch(IOException e){
System.out.println(e);
}
}
}
What will be the output of running "java IO" from C:\java\dir1
a) C:\java\12345.msg
C:\java\dir1\..\12345.msg
b) C:\java\dir1\12345.msg
C:\java\dir1\..\12345.msg
c) C:\java\dir1\..\12345.msg
C:\java\dir1\..\12345.msg
Q 38) Suppose we copy IO.class from C:\java\dir1 to c:\java
What will be the output of running "java IO" from C:\java.
a) C:\java\12345.msg
C:\java\..\12345.msg
b) C:\12345.msg
C:\java\..\12345.msg
c) C:\java\..\12345.msg
C:\java\\..\12345.msg
Q39) Which one of the following methods of java.io.File throws IOException and why
a) getCanonicalPath and getAbsolutePath both require filesystem queries.
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
b) Only getCannonicalPath as it require filesystem queries.
c) Only getAbsolutePath as it require filesystem queries.
Q40) What will be the output if
Consider a directory structure like this (NT or 95)
C:\JAVA\12345.msg --FILE
\dir1\IO.class -- IO.class is under dir1
import java.io.*;
public class IO {
public static void main(String args[]) {
File f = new File("12345.msg");
String arr[] = f.list();
System.out.println(arr.length);
}
}
a) Compiler error as 12345.msg is a file not a directory
b) java.lang.NullPointerException at run time
c) No error , but nothing will be printed on screen
Q41) What will be the output
Consider a directory structure like this (NT or 95)
C:\JAVA\12345.msg --FILE
import java.io.*;
public class IO {
public static void main(String args[]) {
File f1 = new File("\\12345.msg");
System.out.println(f1.getPath());
System.out.println(f1.getParent());
System.out.println(f1.isAbsolute());
System.out.println(f1.getName());
System.out.println(f1.exists());
System.out.println(f1.isFile());
}
}
a) \12345.msg
\
true
12345.msg
true
true
b) \12345.msg
\
true
\12345.msg
false
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
false
c) 12345.msg
\
true
12345.msg
false
false
d) \12345.msg
\
true
12345.msg
false
false
Q42) If in Question no 41 the line
File f1 = new File("\\12345.msg"); is replaced with File f1 = new File("12345.msg");
What will be the output
a) 12345.msg
\
true
12345.msg
true
true
b) 12345.msg
null
true
12345.msg
true
true
c) 12345.msg
null
false
12345.msg
true
true
d) \12345.msg
\
true
12345.msg
false
false
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
Question 1
What will happen if you compile/run this code?
1: public class Q1 extends Thread
2: {
3: public void run()
4: {
5: System.out.println("Before start method");
6: this.stop();
7: System.out.println("After stop method");
8: }
9:
10: public static void main(String[] args)
11: {
12: Q1 a = new Q1();
13: a.start();
14: }
15: }
A) Compilation error at line 7.
B) Runtime exception at line 7.
C) Prints "Before start method" and "After stop method".
D) Prints "Before start method" only.
Question 2
What will happen if you compile/run the following code?
1: class Test
2: {
3: static void show()
4: {
5: System.out.println("Show method in Test class");
6: }
7:}
8:
9: public class Q2 extends Test
10: {
11: static void show()
12: {
13: System.out.println("Show method in Q2 class");
14: }
15: public static void main(String[] args)
16: {
17: Test t = new Test();
Haaris Infotech - Shoiab - 9840135749
Core Java - Test - 50 Marks
18: t.show();
19: Q2 q = new Q2();
20: q.show();
21:
22: t = q;
23: t.show();
24:
25: q = t;
26: q.show();
27: }
28: }
A) prints "Show method in Test class"
"Show method in Q2 class"
"Show method in Q2 class"
"Show method in Q2 class"
B) prints "Show method in Test class"
"Show method in Q2 class"
"Show method in Test class"
"Show method in Test class"
C) prints "Show method in Test class"
"Show method in Q2 class"
"Show method in Test class"
"Show method in Q2 class"
D) Compilation error.

Java Interview Questions And Answers 112

What if the main method is declared as private?

The program compiles properly but at runtime it will give "Main method not public." message.

What is meant by pass by reference and pass by value in Java?

Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value.

If you’re overriding the method equals() of an object, which other method you might also consider?

hashCode()

What is Byte Code?

Or

What gives java it’s “write once and run anywhere” nature?

All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.

Expain the reason for each keyword of public static void main(String args[])?

public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.

static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.

void: main does not return anything so the return type must be void

The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line.

What are the differences between == and .equals() ?

Or

what is difference between == and equals

Or

Difference between == and equals method

Or

What would you use to compare two String variables - the operator == or the method equals()?

Or

How is it possible for two String objects with identical values not to be equal under the == operator?

The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.

== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.

public class EqualsTest {



public static void main(String[] args) {



String s1 = "abc";

String s2 = s1;

String s5 = "abc";

String s3 = new String("abc");

String s4 = new String("abc");

System.out.println("== comparison : " + (s1 == s5));

System.out.println("== comparison : " + (s1 == s2));

System.out.println("Using equals method : " + s1.equals(s2));

System.out.println("== comparison : " + s3 == s4);

System.out.println("Using equals method : " + s3.equals(s4));

}

}


Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true

What if the static modifier is removed from the signature of the main method?

Or

What if I do not provide the String array as the argument to the method?

Program compiles. But at runtime throws an error "NoSuchMethodError".

Why oracle Type 4 driver is named as oracle thin driver?

Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.

What is the difference between final, finally and finalize? What do you understand by the java final keyword?

Or

What is final, finalize() and finally?

Or

What is finalize() method?

Or

What is the difference between final, finally and finalize?

Or

What does it mean that a class or member is final?

o final - declare constant
o finally - handles exception
o finalize - helps in garbage collection

Variables defined in an interface are implicitly final. A final class can't be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.

What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.

Why there are no global variables in Java?

Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:

* The global variables breaks the referential transparency
* Global variables creates collisions in namespace.

How to convert String to Number in java program?

The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = "1000";
int id=Integer.valueOf(numString).intValue();

What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

What is the difference between a while statement and a do statement?

A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the loop body at least once.

What is the Locale class?

The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region.

Describe the principles of OOPS.

There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

Explain the Inheritance principle.

Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places

What is implicit casting?

Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.

Example

int i = 1000;

long j = i; //Implicit casting

Is sizeof a keyword in java?

The sizeof operator is not a keyword.

What is a native method?

A native method is a method that is implemented in a language other than Java.

In System.out.println(), what is System, out and println?

System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.

What are Encapsulation, Inheritance and Polymorphism

Or

Explain the Polymorphism principle. Explain the different forms of Polymorphism.

Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation.

Polymorphism exists in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface

What is explicit casting?

Explicit casting in the process in which the complier are specifically informed to about transforming the object.

Example

long i = 700.20;

int j = (int) i; //Explicit casting

What is the Java Virtual Machine (JVM)?

The Java Virtual Machine is software that can be ported onto various hardware-based platforms

What do you understand by downcasting?

The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy

What are Java Access Specifiers?

Or

What is the difference between public, private, protected and default Access Specifiers?

Or

What are different types of access modifiers?

Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing
privileges to parts of a program such as functions and variables. These are:
• Public : accessible to all classes
• Protected : accessible to the classes within the same package and any subclasses.
• Private : accessible only to the class to which they belong
• Default : accessible to the class to which they belong and to subclasses within the same package

Which class is the superclass of every class?

Object.

Name primitive Java types.

The 8 primitive types are byte, char, short, int, long, float, double, and boolean.

What is the difference between static and non-static variables?

Or

What are class variables?

Or

What is static in java?

Or

What is a static method?

A static variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static variables i.e. there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class. These are declared outside a class and stored in static memory. Class variables are mostly used for constants. Static variables are always called by the class name. This variable is created when the program starts and gets destroyed when the programs stops. The scope of the class variable is same an instance variable. Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than any object of the class and doesn't apply to an object or even require that any objects of the class have been instantiated.
Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a non-static method. In other words, you can't change a static method into an instance method in a subclass.

Non-static variables take on unique values with each object instance.

What is the difference between the boolean & operator and the && operator?

If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. I

How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

What if I write static public void instead of public static void?

Program compiles and runs properly.

What is the difference between declaring a variable and defining a variable?

In declaration we only mention the type of the variable and its name without initializing it. Defining means declaration + initialization. E.g. String s; is just a declaration while String s = new String ("bob"); Or String s = "bob"; are both definitions.

What type of parameter passing does Java support?

In Java the arguments (primitives and objects) are always passed by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.

Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. Objects allow procedures to be encapsulated with their data to reduce potential interference. One way t

Java Interview Questions And Answers 108

The program compiles properly but at runtime it will give "Main method not public." message.

What is meant by pass by reference and pass by value in Java?

Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value.

If you’re overriding the method equals() of an object, which other method you might also consider?

hashCode()

What is Byte Code?

Or

What gives java it’s “write once and run anywhere” nature?

All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.

Expain the reason for each keyword of public static void main(String args[])?

public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.

static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.

void: main does not return anything so the return type must be void

The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line.

What are the differences between == and .equals() ?

Or

what is difference between == and equals

Or

Difference between == and equals method

Or

What would you use to compare two String variables - the operator == or the method equals()?

Or

How is it possible for two String objects with identical values not to be equal under the == operator?

The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.

== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.

public class EqualsTest {



public static void main(String[] args) {



String s1 = "abc";

String s2 = s1;

String s5 = "abc";

String s3 = new String("abc");

String s4 = new String("abc");

System.out.println("== comparison : " + (s1 == s5));

System.out.println("== comparison : " + (s1 == s2));

System.out.println("Using equals method : " + s1.equals(s2));

System.out.println("== comparison : " + s3 == s4);

System.out.println("Using equals method : " + s3.equals(s4));

}

}


Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true

What if the static modifier is removed from the signature of the main method?

Or

What if I do not provide the String array as the argument to the method?

Program compiles. But at runtime throws an error "NoSuchMethodError".

Why oracle Type 4 driver is named as oracle thin driver?

Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.

What is the difference between final, finally and finalize? What do you understand by the java final keyword?

Or

What is final, finalize() and finally?

Or

What is finalize() method?

Or

What is the difference between final, finally and finalize?

Or

What does it mean that a class or member is final?

o final - declare constant
o finally - handles exception
o finalize - helps in garbage collection

Variables defined in an interface are implicitly final. A final class can't be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.

What is the Java API?

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

What is the ResourceBundle class?

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run.

Why there are no global variables in Java?

Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:

* The global variables breaks the referential transparency
* Global variables creates collisions in namespace.

How to convert String to Number in java program?

The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = "1000";
int id=Integer.valueOf(numString).intValue();

What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

What is the difference between a while statement and a do statement?

A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the loop body at least once.

What is the Locale class?

The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region.

Describe the principles of OOPS.

There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

Explain the Inheritance principle.

Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places

What is implicit casting?

Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.

Example

int i = 1000;

long j = i; //Implicit casting

Is sizeof a keyword in java?

The sizeof operator is not a keyword.

What is a native method?

A native method is a method that is implemented in a language other than Java.

In System.out.println(), what is System, out and println?

System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.

What are Encapsulation, Inheritance and Polymorphism

Or

Explain the Polymorphism principle. Explain the different forms of Polymorphism.

Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation.

Polymorphism exists in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface

What is explicit casting?

Explicit casting in the process in which the complier are specifically informed to about transforming the object.

Example

long i = 700.20;

int j = (int) i; //Explicit casting

What is the Java Virtual Machine (JVM)?

The Java Virtual Machine is software that can be ported onto various hardware-based platforms

What do you understand by downcasting?

The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy

What are Java Access Specifiers?

Or

What is the difference between public, private, protected and default Access Specifiers?

Or

What are different types of access modifiers?

Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing
privileges to parts of a program such as functions and variables. These are:
• Public : accessible to all classes
• Protected : accessible to the classes within the same package and any subclasses.
• Private : accessible only to the class to which they belong
• Default : accessible to the class to which they belong and to subclasses within the same package

Which class is the superclass of every class?

Object.

Name primitive Java types.

The 8 primitive types are byte, char, short, int, long, float, double, and boolean.

What is the difference between static and non-static variables?

Or

What are class variables?

Or

What is static in java?

Or

What is a static method?

A static variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static variables i.e. there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class. These are declared outside a class and stored in static memory. Class variables are mostly used for constants. Static variables are always called by the class name. This variable is created when the program starts and gets destroyed when the programs stops. The scope of the class variable is same an instance variable. Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than any object of the class and doesn't apply to an object or even require that any objects of the class have been instantiated.
Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a non-static method. In other words, you can't change a static method into an instance method in a subclass.

Non-static variables take on unique values with each object instance.

What is the difference between the boolean & operator and the && operator?

If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. I

How does Java handle integer overflows and underflows?

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

What if I write static public void instead of public static void?

Program compiles and runs properly.

What is the difference between declaring a variable and defining a variable?

In declaration we only mention the type of the variable and its name without initializing it. Defining means declaration + initialization. E.g. String s; is just a declaration while String s = new String ("bob"); Or String s = "bob"; are both definitions.

What type of parameter passing does Java support?

In Java the arguments (primitives and objects) are always passed by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.

Explain the Encapsulation principle.

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. Objects allow procedures to be encapsulated with their data to reduce potential interference. One way t

Advanced enterprise Java interview questions 106

1) What is the purpose of garbage collection in Java, and when is it used?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

2) Describe synchronization in respect to multithreading.

With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

>

3) How is JavaBeans differ from Enterprise JavaBeans?

The JavaBeans architecture is meant to provide a format for general-purpose components. On the other hand, the Enterprise JavaBeans architecture provides a format for highly specialized business logic components.

4) In what ways do design patterns help build better software?

Design patterns helps software developers to reuse successful designs and architectures. It helps them to choose design alternatives that make a system reusuable and avoid alternatives that compromise reusability through proven techniques as design patterns.

5) Describe 3-Tier Architecture in enterprise application development.

In 3-tier architecture, an application is broken up into 3 separate logical layers, each with a well-defined set of interfaces. The presentation layer typically consists of a graphical user interfaces. The business layer consists of the application or business logic, and the data layer contains the data that is needed for the application.

Advanced JAVA questions 104

What is RMI?
Explain about RMI Architecture?
What are Servelets?
What is the use of servlets?
Explain RMI Architecture?
How will you pass values from htm page to the servlet?
How do you load an image in a Servelet?
What is purpose of applet programming?
How will you communicate between two applets?
What IS the difference between Servelets and Applets?
How do you communicate in between Applets and Servlets?
What is the difference between applet and application?
What is the difference between CGI and Servlet?
In the servlets, we are having a web page that is invoking servlets ,username and password? which is checks in database? Suppose the second page also if we want to verify the same information whether it will connect to the database or it will be used previous information?
What are the difference between RMI and Servelets?
How will you call an Applet using Java Script Function?
How can you push data from an Applet to a Servlet?
What are 4 drivers available in JDBC? At what situation are four of the drivers used?
If you are truncated using JDBC , how can you that how much data is truncated?
How will you perform truncation using JDBC?
What is the latest version of JDBC? What are the new features added in that?
What is the difference between RMI registry and OS Agent?
To a server method, the client wants to send a value 20, with this value exceeds to 20 a message should be sent to the client . What will you do for achieving this?
How do you invoke a Servelet? What is the difference between doPost method and doGet method?
What is difference between the HTTP Servelet and Generic Servelet? Explain about their methods and parameters?
Can we use threads in Servelets?
Write a program on RMI and JDBC using Stored Procedure?
How do you swing an applet?
How will you pass parameters in RMI? Why do you serialize?
In RMI ,server object is first loaded into memory and then the stub reference is sent to the client. true or false?
Suppose server object not loaded into the memory and the client request for it. What will happen?
What is the web server used for running the servelets?
What is Servlet API used for connecting database?
What is bean? Where can it be used?
What is the difference between java class and bean?
Can we sent objects using Sockets?
What is the RMI and Socket?
What is CORBA?
Can you modify an object in corba?
What is RMI and what are the services in RMI?
What are the difference between RMI and CORBA?
How will you initialize an Applet?
What is the order of method invocation in an Applet?
What is ODBC and JDBC? How do you connect the Database?
What do you mean by Socket Programming?
What is difference between Generic Servlet and HTTP Servelet?
What you mean by COM and DCOM?
what is e-commerce?

(FAQ) Advanced Java Interview Questions 100

1. What is RMI?
2. Explain about RMI Architecture?
3. What are Servelets?
4. What is the use of servlets?
5. Explain RMI Architecture?
6. How will you pass values from htm page to the servlet?
7. How do you load an image in a Servelet?
8. What is purpose of applet programming?
9. How will you communicate between two applets?
10. What IS the difference between Servelets and Applets?
11. How do you communicate in between Applets and Servlets?
12. What is the difference between applet and application?
13. What is the difference between CGI and Servlet?
14. In the servlets, we are having a web page that is invoking servlets ,username and password? which is checks in database? Suppose the second page also if we want to verify the same information whether it will connect to the database or it will be used previous information?
15. What are the difference between RMI and Servelets?
16. How will you call an Applet using Java Script Function?
17. How can you push data from an Applet to a Servlet?
18. What are 4 drivers available in JDBC? At what situation are four of the drivers used?
19. If you are truncated using JDBC , how can you that how much data is truncated?
20. How will you perform truncation using JDBC?
21. What is the latest version of JDBC? What are the new features added in that?
22. What is the difference between RMI registry and OS Agent?
23. To a server method, the client wants to send a value 20, with this value exceeds to 20 a message should be sent to the client . What will you do for achieving this?
24. How do you invoke a Servelet? What is the difference between doPost method and doGet method?
25. What is difference between the HTTP Servelet and Generic Servelet? Explain about their methods and parameters?
26. Can we use threads in Servelets?
27. Write a program on RMI and JDBC using Stored Procedure?
28. How do you swing an applet?
29. How will you pass parameters in RMI? Why do you serialize?
30. In RMI ,server object is first loaded into memory and then the stub reference is sent to the client. true or false?
31. Suppose server object not loaded into the memory and the client request for it. What will happen?
32. What is the web server used for running the servelets?
33. What is Servlet API used for connecting database?
34. What is bean? Where can it be used?
35. What is the difference between java class and bean?
36. Can we sent objects using Sockets?
37. What is the RMI and Socket?
38. What is CORBA?
39. Can you modify an object in corba?
40. What is RMI and what are the services in RMI?
41. What are the difference between RMI and CORBA?
42. How will you initialize an Applet?
43. What is the order of method invocation in an Applet?
44. What is ODBC and JDBC? How do you connect the Database?
45. What do you mean by Socket Programming?
46. What is difference between Generic Servlet and HTTP Servelet?
47. What you mean by COM and DCOM?
48. what is e-commerce?

TrainJava Blog interviews 98

This is a interview test for a Java programmer at an advanced level. There are 10 questions but more than a single answer to most of the questions. The correct answers are given at the end of the article together with the points awarded for each correct option and the difficulty of the question on a 1-10 scale. The best score you can get is 100 by answering correctly to all questions.

1. Question : Language Features - OO rules

What is going to happen when the following program executes?

class A {
public void a() {
b();
}
private void b() {
System.out.println(“Executing A’s b()”);
}
}
class B extends A {
public void b() {
System.out.println(“Executing B’s b()”);
}
}

public static void main(String[] argv) {
B b = new B();
b.b();
b.a();
}
1. B’s b() will run and then A’s b() will run
2. A’s b() is going to be called twice
3. B’s b() is going to be called twice
4. A’s b() will run and the B’s b() will run
5. The compiler will not allow the above code to compile

2. Question : APIs - Swing

Swing Components can change their look and feel (l&F) at runtime.
Which of the l&f come standard with swing?

1. macintosh l&f
2. metal l&f
3. motif l&f
4. windows l&f
5. vax l&f

3. Question : VM Architecture : Parts and Design

Which of the following statements concerning the Virtual Machine are true and which are false?

1. Object are stored in the heap, local variables are stored in the stack.
2. The Virtual Machine has 8 registers, each one has the length of one word.
3. The Virtual Machine does not differentiate between an instance method and a constructor method.
4. A StackFrame gets created into the VM’s stack area for every thread executed.
5. The VM keeps a program counter for every thread.

4. Question : VM Architecture : Performance

Which of the following statements concerning performance are true and which are false?

1. Methods called through an interface reference are slower than those called through abstract methods because they can never be pointed directly by fields in the class pool of the caller
2. The invocation of an interface method is slower than Instantiation
3. The statement x = 3 executes faster than the statement x = 15.
4. Hotspot compilers convert all the bytecode into native code at runtime
5. Polymorphic calls are almost as fast as static method calls.

5. Question : Language Features - Classloaders

When two objects loaded through different Classloaders can they communicate?

1. When the invoker object access the other object through an interface that has been loaded using the invoker object’s classloader.
2. When they belong to the same package
3. When the invoker’s classloader has resolved the class of the other object
4. When the Security Manager allows it
5. Never, objects loaded using different Classloaders can’t communicate.

6. Question : Language Features - Reflection

Which of the following are valid ways of making an instance from class X

1. X myX = new X();
2. X myX = (X)((X.class).newInstance())
3. X myX = (X)Class.instantiate(X);
4. X myX = (X)(X.class).getClass().forName(”X”).newInstance();
5. X myX = (X)(Class.forName(”X”)).newInstance())

7. Question : Language Tools - Debuggers - Dissassemblers - Profilers

Which of the following statements are true and which are false?

1. JPDA stands for Java Personal Digital Assistant
2. SerVer is a jdk tool that allows serial verification of test profiles
3. The 4 first bytes on the header of any valid class file says JAVABABE
4. The bytecode form of a program can’t store the identifier names
5. Changing a String value of a bytecode class file will damage the file and render it unloadable.

8. Question : Object Orientation Principles - Patterns Basic

What is the pattern that best expresses the relationship between AWT’s classes Component and Container?

1. Factory
2. Strategy
3. Composite
4. Decorator
5. Proxy

9. Question : Object Orientation Principles - Patterns Advanced

Which of the following statements concerning the use of design patterns into the various java API’s are true and which are false?

1. An AWT’s Toolkit plays the role of an “Abstract Factory”
2. The LayoutManager in AWT plays the role of a “Decorator”
3. The Enumeration Interface reveals actually a “Mediator”
4. A Point in AWT is a “Wrapper”
5. A File is implemented in java using the “Composite” pattern

10. Question : Java API Design

The implementation of which design pattern would significantly improve the layout mechanism in terms of simplicity and readability?

1. State
2. Singleton
3. Null Object
4. Decorator
5. Facade

1. Answer to Question 1:

Answer : 1 = true
Grading : 10 points for the correct answer
Difficulty : 9/10 A.

2. Answer to Question 2:

Answer : 2 = true, 3 = true, 4=true
Grading : 10 points for all the correct answers
Difficulty : 1/10 A.

3. Answer to Question 3:

Answer : 1 = true, 2 = false, 3 = false, 4 = false, 5 = true
Grading : 2 points per correct answer
Difficulty : 4/10 A.

4. Answer to Question 4:

Answer : 1 = true, 2 = false, 3 = true, 4 = false, 5 = false
Grading : 2 points per correct answer
Difficulty : 8/10 A.

5. Answer to Question 5:

Answer : 1 = true
Grading : 10 points for the correct answer
Rational : This question assesses the delegate’s understanding of
Difficulty : 8/10 A.

6. Answer to Question 6:

Answer : 1 = true, 2 = true, 3 = false, 4 = true, 5 = true
Grading : 10 points for giving all four correct answers
Difficulty : 5/10 A.

7. Answer to Question 7:

Answer : 1 = false, 2 = false, 3 = false, 4 = false, 5 = false
Grading : 2 points for every correct answer
Difficulty : 1/10 A.

8. Answer to Question 8:

Answer :3 = true
Grading :10 points for correct answer
Difficulty : 4/10 A.

9. Answer to Question 9:

Answer : 1 = true, 2 = false, 3 = false, 4 = false, 5 = false
Grading : 2 points for every correct answer
Difficulty : 10/10 A.

10. Answer to Question 10:

Answer : 3 = true
Grading : Grading: 10 points for correct answer
Difficulty : 10/10 A.

Java Exceptions Questions 94

Explain the user defined Exceptions?

User defined Exceptions are custom Exception classes defined by the user for specific purpose. A user defined exception can be created by simply sub-classing an Exception class or a subclass of an Exception class. This allows custom exceptions to be generated (using throw clause) and caught in the same way as normal exceptions.
Example:

class CustomException extends Exception {

}

What classes of exceptions may be caught by a catch clause?

A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Errors are generally irrecoverable conditions

What is the difference between exception and error?

Error's are irrecoverable exceptions. Usually a program terminates when an error is encountered.

What is the difference between throw and throws keywords?

The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as an argument. The exception will be caught by an enclosing try-catch block or propagated further up the calling hierarchy. The throws keyword is a modifier of a method that denotes that an exception may be thrown by the method. An exception can be rethrown.

What class of exceptions are generated by the Java run-time system?

The Java runtime system generates Runtime Exceptions and Errors.

What is the base class for Error and Exception?

Throwable

What are Checked and Unchecked Exceptions?

A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the exception may be thrown. Checked exceptions must be caught at compile time. Example: IOException.
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBoundsException. Errors are often irrecoverable conditions.

Does the code in finally block get executed if there is an exception and a return statement in a catch block?

Or

What is the purpose of the finally clause of a try-catch-finally statement?

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(0) statement is executed earlier or on system shut down earlier or the memory is used up earlier before the thread goes to finally block.

try{
//some statements
}
catch{
//statements when exception is caught
}
finally{
//statements executed whether exception occurs or not
}

Does the order of placing catch statements matter in the catch block?

Yes, it does. The FileNoFoundException is inherited from the IOException. So FileNoFoundException is caught before IOException. Exception’s subclasses have to be caught first before the General Exception

Java technical interview guide - part 1 90

I did a technical evaluation for a candidate my employer was looking at awhile ago, so I had an opportunity to try and figure out a good set of technical questions for a prospective intermediate level Java web developer. I’ll just present a whole bunch of questions I came up with - no answers though. I might start up an answers post at a later date, but I don’t want to make this too easy for those trying to fool interviewers. =) Obviously, if you ask every question I have listed here your interview could take hours, so pick and choose what you like. I’d be interested in feedback for ideas on important topics I’ve overlooked or questions that are unfair or unnecessary. I’ve tried to avoid things that can be easily answered with a quick google search, such as basic syntax and API method questions.

Anyways, on to the questions.

General Intro Questions

Just laying the ground work to help lead the way for areas to focus on…

  • Give me a high level description of your experience with the Java platform. What APIs do you have experience with? Servlets? J2EE? Swing?
  • What development methodologies have you used? Which one have you liked the most? The least?
  • What open source frameworks do you have experience with?
  • What other languages have you used?

Object Oriented Principles

  • Define object oriented programming (quite a loaded question…). What are the key OO principles?
  • Describe polymorphism.
  • Describe inheritance (”is-a”) and composition (”has-a”). Can you give an example of a use case for each?
  • What is coupling? Why do we want loose coupling in our systems?

Java Basics

Some very fundamental questions I think any “non-beginner” level dev should know. If there are a lot of problems with these it may not be worth continuing.

  • What is the difference between abstract classes and interfaces?
  • Explain the access modifiers in Java.
  • Talk about method overriding and method overloading and their differences.
  • Why does Java have exceptions? What is the difference between checked and unchecked exceptions?
  • What are constructors? Are they inherited?
  • What is the static modifier used for in regards to classes and methods?
  • What are the equals() and hashcode() ? Describe their contracts.
  • When do you use String and when do you use StringBuffer/StringBuilder

Java Intermediate/Advanced

  • Explain the following statement: Java is always pass-by-value.
  • How do you create an immutable type? What are the advantages of immutability?
  • What is a static inner class? Can you provide an example from the Java API?
  • What are the implications of implementing serializable in an object?
  • Why would you declare a private constructor?
  • When do you want to use unchecked exceptions and when do you want to use checked?
  • Can you explain how Strings are “interned” in Java?
  • What are enumerated types? Why would you use them?

Java Collections

  • What are the core interfaces of the Collection framework?
  • How do Vector and HashTable relate to Collections?
  • Desribe typical use cases or examples of common uses for Map, Set, and Lists.
  • What method(s) should override for objects you plan to add to sets or maps?
  • How do you get an immutable collection?

Threading

If a developer works only in the heavily abstracted world of Spring/Hibernate/whatever, they may not have had to touch an actual Runnable since college. Still, its good to know about threading at least on a basic level.

  • What does the synchronized key word do? Where is it valid to use it (ie inside a method call, static block, etc)?
  • Explain the two ways to instantiate threads in Java.
  • What is “double-checked locking“? What design pattern is it typically associated with? What is wrong with it?
  • What is a daemon thread? How do you create one?
  • What method do you use to start a thread?

Servlets and JSPs

  • What are the steps to create a basic servlet?
  • Describe the lifecycle of a basic servlet - for instance, when are they created? What method is called from a typical HTTP request? What about requests and threads?
  • What does it mean to say that HTTP is stateless? How do servlets provide a possible solution to maintain state for web applications?
  • Are JSP’s thread safe?
  • What are Listeners? What is a typical use for a StartupListener?
  • What are filters and why would you use them?
  • Describe the four different scopes available with servlets?

Design Patterns

  • What are the three types of design patterns?
  • Can you talk about the history of design patterns?
  • Why use design patterns?
  • What is the role of composition (aggregation) in design patterns?
  • What design patterns do you use often and have the most experience with? Can you talk about a typical use case?
  • Can you provide a description of any of the following patterns? Strategy, State, or Template method?
  • What is Model View Controller, and why would you want to use it? What are some of the disadvantages of it?
  • What is inversion of control, and what does it give you?

Open Ended Questions

These questions are more to just stir discussion and debate and to get a feel for the candidate, rather then to get the “right” answer.

  • How would you build a software version of Monopoly?
  • Can you compare (insert dynamic language of choice here - Ruby/Python/Lisp/etc) to Java? When would you prefer one over the other?
  • What do you think is the most common cause of project failure in the software development business?
  • What do you think of the rise of open source over the last ten years? Where do you see open source in the future?
  • What does agile development mean to you?
  • What is your ideal development environment like? Both in terms of hardware and software, and location and surroundings?
  • What was the last technical book you read? Give me the Cliff Notes version of it.
  • What are some of your favorite resources beyond Google? This could include websites, magazines, technical authors, experts, favorite blogs, etc.
  • Do you have experience with Test Driven Development? If so, what do you think of it?
  • What will be the next language or development topic you want to learn about?

Advanced Java Interview Questions And Answers 88

What is purpose of applet programming?

How will you communicate between two applets?

What IS the difference between Servelets and Applets?

How do you communicate in between Applets and Servlets?

What is the difference between applet and application?

What is the difference between CGI and Servlet?

In the servlets, we are having a web page that is invoking servlets ,username and password? which is checks in database? Suppose the second page also if we want to verify the same information whether it will connect to the database or it will be used previous information?

What are the difference between RMI and Servelets?

How will you call an Applet using Java Script Function?

How can you push data from an Applet to a Servlet?

What are 4 drivers available in JDBC? At what situation are four of the drivers used?

If you are truncated using JDBC , how can you that how much data is truncated?

How will you perform truncation using JDBC?

What is the latest version of JDBC? What are the new features added in that?

What is the difference between RMI registry and OS Agent?

To a server method, the client wants to send a value 20, with this value exceeds to 20 a message should be sent to the client . What will you do for achieving this?

How do you invoke a Servelet? What is the difference between doPost method and doGet method?

What is difference between the HTTP Servelet and Generic Servelet? Explain about their methods and parameters?

Can we use threads in Servelets?

Write a program on RMI and JDBC using Stored Procedure?

How do you swing an applet?

How will you pass parameters in RMI? Why do you serialize?

In RMI ,server object is first loaded into memory and then the stub reference is sent to the client. true or false?

Suppose server object not loaded into the memory and the client request for it. What will happen?

What is the web server used for running the servelets?

What is Servlet API used for connecting database?

What is bean? Where can it be used?

What is the difference between java class and bean?

Can we sent objects using Sockets?

What is the RMI and Socket?

What is CORBA?

Can you modify an object in corba?

What is RMI and what are the services in RMI?

What are the difference between RMI and CORBA?

How will you initialize an Applet?

What is the order of method invocation in an Applet?

What is ODBC and JDBC? How do you connect the Database?

What do you mean by Socket Programming?

What is difference between Generic Servlet and HTTP Servelet?

What you mean by COM and DCOM?

what is e-commerce?


Java J2EE Interview Questions and Answers 84

Java Language Fundamentals Questions 1

2. Is Java a pure object oriented language ?

3. Explain encapsulation

4. Explain inheritance

5. Explain polymorphism

6. What are classes and objects? What is the relationship between them?

7. What do you understand by API

8. Name atleast 10 Java API class you have used while programming

9. What are reserved words in Java ?

10. What is size of int in Java?

11. What is the difference between Java Key words and reserved words?

12. What do you understand by private, protected and public?
A. private, protected and public are access modifiers.

13. Public is least restrictive while private is most restrictive.

14. How many static init can you have?
A. As many as you can

15. What is reference in Java?

16. Explain main() method modifiers?

17. In system.out.println what is out and println ? Can this be redirected to a file ? How ?

18. What is the difference between instanceof and isInstance?

19. What is an instance variable and instance method?

20. Explain terms subclass and superclass.

21. What is the difference between string and stringbuffer ?

22. What is the purpose of garbage collection?
A. The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused.

23. What do you mean by Classpath and Classloader?
A. Classpath is the path where Compiller / JRE looks for dependent java sources

24. Classloader loads the classes into the Java virtual machine.

25. What package in java is implicitly imported
A. java.lang

26. What is the difference between a field variable and local variable?
A. A field variable is declared as a member of a class. A local variable is declared in a method (local to a method).

27. Significance of this and super() in constructors

28. What is a constructor?

29. What is reflection? What do you understand by Class.forName()

30. Does importing a package imports the subpackages as well?

31. What is the difference between declaring a variable and defining a variable?

32. What is the difference of signed and unsigned integer?

33. Significance of interface in java?

Java Architect Interview Questions 82

1. What do you understand by UML. How to interpret UML diagrams?
2. State the effect of encapsulation, inheritance, and use of interfaces on architectural characteristics?
3. Differentiate between 2 tier, 3 tier and n-tier architectures.
4. How do the following characteristics scalability,performance, high availabilty behave based on the above architecture selected.
5. In what all ways (methods/concepts) can we achieve integration with legacy/n-n-legacy applications using JAVA technologies.
6. List the required classes/interfaces that must be provided for an EJB technology.
7. Distinguish stateful and stateless Session beans.
8. Distinguish Session and Entity beans.
9. Recognize appropriate uses for Entity, Stateful Session, and Stateless Session beans.
10. State the transactional behavior in a given scenario for an enterprise bean method with a specified transactional deployment descriptor.
11.Given a requirement specification detailing security and flexibility needs, identify architectures that would fulfill those requirements.
12. Identify costs and benefits of using an intermediate data-access object between an entity bean and the data resource.
13. State the benefits of bean pooling in an EJB container.
14. State the benefits of Passivation in an EJB container.
15. State the benefit of monitoring of resources in an EJB container.
16. Explain how the EJB container does lifecycle management and has the capability to increase scalability.
17. Given a scenario description, distinguish appropriate from inappropriate protocols to implement that scenario.
18. Identify a protocol, given a list of some of its features, where the protocol is one of the following: HTTP, HTTPS, IIOP, JRMP.
19. Select from a list, common firewall features that might interfere with the normal operation of a given protocol.
20. State the benefits of using design patterns.
21. State the name of a design pattern given the UML diagram and/or a brief description of the pattern’s functionality.
22. Select from a list benefits of a specified design pattern.
23. Identify the design pattern associated with a specified J2EE feature.
24. Identify scenarios that are appropriate to implementation using messaging, EJB, or both.
25. List benefits of synchronous and asynchronous messaging.
26. Select scenarios from a list that are appropriate to implementation using synchronous and asynchronous messaging.
27. State three aspects of any application that might need to be varied or customized in different deployment locales.
28. Match the following features of the Java 2 platform with descriptions of their functionality, purpose or typical uses: Properties, Locale, ResourceBundle, Unicode, java.text package, 29. InputStreamReader and OutputStreamWriter.
30. Select from a list security restrictions that Java 2 environments normally impose on applets running in a browser.
31. Given an architectural system specification, identify appropriate locations for implementation of specified security features, and select suitable technologies for implementation of those features.

Advanced enterprise Java Interview Questions 80

1) What is the purpose of garbage collection in Java, and when is it used?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

2) Describe synchronization in respect to multithreading.

With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

>

3) How is JavaBeans differ from Enterprise JavaBeans?

The JavaBeans architecture is meant to provide a format for general-purpose components. On the other hand, the Enterprise JavaBeans architecture provides a format for highly specialized business logic components.

4) In what ways do design patterns help build better software?

Design patterns helps software developers to reuse successful designs and architectures. It helps them to choose design alternatives that make a system reusuable and avoid alternatives that compromise reusability through proven techniques as design patterns.

5) Describe 3-Tier Architecture in enterprise application development.

In 3-tier architecture, an application is broken up into 3 separate logical layers, each with a well-defined set of interfaces. The presentation layer typically consists of a graphical user interfaces. The business layer consists of the application or business logic, and the data layer contains the data that is needed for the application.

Source:
http://interviewinfo.net

java script interview questions 78

41 :: How to determine the state of a checkbox using JavaScript?

var checkedP = window.document.getElementById("myCheckBox").checked;

42 :: How to set the focus in an element using Javascript?


43 :: How to access an external JavaScript file that is stored externally and not embedded?

This can be achieved by using the following tag between head tags or between body tags.
How to access an external JavaScript file that is stored externally and not embedded? where abc.js is the external JavaScript file to be accessed.

44 :: What is the difference between an alert box and a confirmation box?

An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel.

45 :: What is a prompt box?

A prompt box allows the user to enter input by providing a text box.

46 :: Can JavaScript code be broken in different lines?

Breaking is possible within a string statement by using a backslash \ at the end but not within any other javascript statement.
that is ,
document.write("Hello \ world");
is possible but not document.write \
("hello world");

47 :: Taking a developer’s perspective, do you think that that JavaScript is easy to learn and use?

One of the reasons JavaScript has the word "script" in it is that as a programming language, the vocabulary of the core language is compact compared to full-fledged programming languages. If you already program in Java or C, you actually have to unlearn some concepts that had been beaten into you. For example, JavaScript is a loosely typed language, which means that a variable doesn't care if it's holding a string, a number, or a reference to an object; the same variable can even change what type of data it holds while a script runs.
The other part of JavaScript implementation in browsers that makes it easier to learn is that most of the objects you script are pre-defined for the author, and they largely represent physical things you can see on a page: a text box, an image, and so on. It's easier to say, "OK, these are the things I'm working with and I'll use scripting to make them do such and such," instead of having to dream up the user interface, conceive of and code objects, and handle the interaction between objects and users. With scripting, you tend to write a _lot_ less code.

48 :: What Web sites do you feel use JavaScript most effectively (i.e., best-in-class examples)? The worst?

The best sites are the ones that use JavaScript so transparently, that I'm not aware that there is any scripting on the page. The worst sites are those that try to impress me with how much scripting is on the page.

49 :: How about 2+5+"8"? ?

Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, it’s concatenation, so 78 is the result.

50 :: What is the difference between SessionState and ViewState?

ViewState is specific to a page in a session. Session state refers to user specific data that can be accessed across all pages in the web application.

importent java interviews and answers

31 :: Are Java and JavaScript the Same?

No. java and JavaScript are two different languages.
Java is a powerful object - oriented programming language like C++, C whereas JavaScript is a client-side scripting language with some limitations.

32 :: How to embed JavaScript in a web page?

JavaScript code can be embedded in a web page between langugage="javascript"> tags


33 :: What and where are the best JavaScript resources on the Web?

The Web has several FAQ areas on JavaScript. The best place to start is something called the meta-FAQ [14-Jan-2001 Editor's Note: I can't point to it anymore, it is broken!], which provides a high-level overview of the JavaScript help available on the Net. As for fact-filled FAQs, I recommend one maintained by Martin Webb and a mini-FAQ that I maintain.

For interactive help with specific problems, nothing beats the primary JavaScript Usenet newsgroup, comp.lang.javascript. Depending on my work backlog, I answer questions posted there from time to time. Netscape and Microsoft also have vendor-specific developer discussion groups as well as detailed documentation for the scripting and object model implementations.

34 :: What are the problems associated with using JavaScript, and are there JavaScript techniques that you discourage?

Browser version incompatibility is the biggest problem. It requires knowing how each scriptable browser version implements its object model. You see, the incompatibility rarely has to do with the core JavaScript language (although there have been improvements to the language over time); the bulk of incompatibility issues have to do with the object models that each browser version implements. For example, scripter who started out with Navigator 3 implemented the image rollover because it looked cool. But they were dismayed to find out that the image object wasn't scriptable in Internet Explorer 3 or Navigator 2. While there are easy workarounds to make this feature work on newer browsers without disturbing older ones, it was a painful learning experience for many.

The second biggest can of worms is scripting connections between multiple windows. A lot of scripter like to have little windows pop up with navigation bars or some such gizmos. But the object models, especially in the older browser versions, don't make it easy to work with these windows the minute you put a user in front of them--users who can manually close windows or change their stacking order. More recently, a glitch in some uninstall routines for Windows 95 applications can disturb vital parts of the system Registry that Internet Explorer 4 requires for managing multiple windows. A scripter can't work around this problem, because it's not possible to detect the problem in a user's machine. I tend to avoid multiple windows that interact with each other. I think a lot of inexperienced Web surfers can also get confused by them.

35 :: What Boolean operators does JavaScript support?

&&, || and !

36 :: What does "1"+2+4 evaluate to?

Since 1 is a string, everything is a string, so the result is 124.

37 :: What are the ways to emit client-side JavaScript from server-side code in ASP. NET?

The Page object in ASP. NET has two methods that allow emitting of client-side JavaScript:
RegisterClientScriptBlock and RegisterStartupScript.
Example usage:
Page.RegisterClientScriptBlock("ScriptKey", "");
Page.RegisterStartupScript("ScriptKey", "");
ScriptKey is used to suppress the same JavaScript from being emitted more than once. Multiple calls to RegisterClientScriptBlock or RegisterStartupScript with the same value of ScriptKey emit the script only once, on the first call.


38 :: What is the difference between RegisterClientScriptBlock and RegisterStartupScript?

RegisterClientScriptBlock emits the JavaScript just after the opening tag. RegisterStartupScript emits the JavaScript at the bottom of the ASP. NET page just before the closing tag.

39 :: What is the difference between a web-garden and a web-farm?

Web-garden - An IIS6.0 feature where you can configure an application pool as a web-garden and also specify the number of worker processes for that pool. It can help improve performance in some cases.
Web-farm - a general term referring to a cluster of physically separate machines, each running a web-server for scalability and performance (contrast this with web-garden which refers to multiple processes on one single physical machine).

40 :: How to get the contents of an input box using JavaScript?

Use the "value" property.
var myValue = window.document.getElementById("MyTextBox").value;

importent study interview questions in java 74

21 :: Are you concerned that older browsers don't support JavaScript and thus exclude a set of Web users? individual users?

Fragmentation of the installed base of browsers will only get worse. By definition, it can never improve unless absolutely everyone on the planet threw away their old browsers and upgraded to the latest gee-whiz versions. But even then, there are plenty of discrepancies between the script ability of the latest Netscape Navigator and Microsoft Internet Explorer.

The situation makes scripting a challenge, especially for newcomers who may not be aware of the limitations of earlier browsers. A lot of effort in my books and ancillary material goes toward helping scripter know what features work in which browsers and how to either workaround limitations in earlier browsers or raise the compatibility common denominator.

Designing scripts for a Web site requires making some hard decisions about if, when, and how to implement the advantages scripting offers a page to your audience. For public Web sites, I recommend using scripting in an additive way: let sufficient content stand on its own, but let scriptable browser users receive an enhanced experience, preferably with the same HTML document.

22 :: What does isNaN function do?

Return true if the argument is not a number.

23 :: What is negative infinity?

It’s a number in JavaScript, derived by dividing negative number by zero.

24 :: In a pop-up browser window, how do you refer to the main browser window that opened it?

Use window.opener to refer to the main window from pop-ups.

25 :: What is the data type of variables of in JavaScript?

All variables are of object type in JavaScript.

26 :: Methods GET and POST in HTML forms - what's the difference?

GET: Parameters are passed in the query string. Maximum amount of data that can be sent via the GET method is limited to about 2kb.

POST: Parameters are passed in the request body. There is no limit to the amount of data that can be transferred using POST. However, there are limits on the maximum amount of data that can be transferred in one name/value pair.

27 :: How to write a script for "Select" lists using JavaScript?

1. To remove an item from a list set it to null
mySelectObject.options[3] = null;
2. To truncate a list set its length to the maximum size you desire
mySelectObject.length = 2;
3. To delete all options in a select object set the length to 0.
mySelectObject.leng


28 :: Text From Your Clipboard?

It is true, text you last copied for pasting (copy & paste) can be stolen when you visit web sites using a combination of JavaScript and ASP (or PHP, or CGI) to write your possible sensitive data to a database on another server

29 :: What does the "Access is Denied" IE error mean?

The "Access Denied" error in any browser is due to the following reason.
A JavaScript in one window or frame is tries to access another window or frame whose
document's domain is different from the document containing the script.

30 :: Is a JavaScript script faster than an ASP script?

Yes. Since JavaScript is a client-side script it does require the web server's help for its
computation, so it is always faster than any server-side script like ASP, PHP, etc..

java total interview questions 68

Introduction to Java Programming
1) The Java interpreter is used for the execution of the source code.

a) True

b) False

Ans: a.

2) On successful compilation a file with the class extension is created.

a) True

b) False

Ans: a.

3) The Java source code can be created in a Notepad editor.

a) True

b) False

Ans: a.

4) The Java Program is enclosed in a class definition.

a) True

b) False

Ans: a.

5) What declarations are required for every Java application?

Ans: A class and the main( ) method declarations.

6) What are the two parts in executing a Java program and their purposes?

Ans: Two parts in executing a Java program are:

Java Compiler and Java Interpreter.

The Java Compiler is used for compilation and the Java Interpreter is used for execution of the application.

7) What are the three OOPs principles and define them?

Ans : Encapsulation, Inheritance and Polymorphism are the three OOPs Principles.

Encapsulation: Is the Mechanism that binds together code and the 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 a feature that allows one interface to be used for a general class of actions.

8) What is a compilation unit?

Ans : Java source code file.

9) What output is displayed as the result of executing the following statement?

System.out.println("// Looks like a comment.");

// Looks like a comment
The statement results in a compilation error
Looks like a comment
No output is displayed
Ans : a.

10) In order for a source code file, containing the public class Test, to successfully compile, which of the following must be true?

It must have a package statement
It must be named Test.java
It must import java.lang
It must declare a public class named Test
Ans : b

11) What are identifiers and what is naming convention?

Ans : Identifiers are used for class names, method names and variable names. An identifier may be any descriptive sequence of upper case & lower case letters,numbers or underscore or dollar sign and must not begin with numbers.

12) What is the return type of program’s main( ) method?

Ans : void

13) What is the argument type of program’s main( ) method?

Ans : string array.

14) Which characters are as first characters of an identifier?

Ans : A – Z, a – z, _ ,$

15) What are different comments?

Ans : 1) // -- single line comment

2) /* --

*/ multiple line comment

3) /** --

*/ documentation

16) What is the difference between constructor method and method?

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

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

Ans : Bin contains all tools such as javac, applet viewer, awt tool etc., whereas Lib contains all packages and variables

Top


--------------------------------------------------------------------------------

Data types,variables and Arrays
1) What is meant by variable?

Ans: Variables are locations in memory that can hold values. Before assigning any value to a variable, it must be declared.

2) What are the kinds of variables in Java? What are their uses?

Ans: Java has three kinds of variables namely, the instance variable, the local variable and the class variable.

Local variables are used inside blocks as counters or in methods as temporary variables and are used to store information needed by a single method.

Instance variables are used to define attributes or the state of a particular object and are used to store information needed by multiple methods in the objects.

Class variables are global to a class and to all the instances of the class and are useful for communicating between different objects of all the same class or keeping track of global states.

3) How are the variables declared?

Ans: Variables can be declared anywhere in the method definition and can be initialized during their declaration.They are commonly declared before usage at the beginning of the definition.

Variables with the same data type can be declared together. Local variables must be given a value before usage.

4) What are variable types?

Ans: Variable types can be any data type that java supports, which includes the eight primitive data types, the name of a class or interface and an array.

5) How do you assign values to variables?

Ans: Values are assigned to variables using the assignment operator =.

6) What is a literal? How many types of literals are there?

Ans: A literal represents a value of a certain type where the type describes how that value behaves.There are different types of literals namely number literals, character literals, boolean literals, string literals,etc.

7) What is an array?

Ans: An array is an object that stores a list of items.

8) How do you declare an array?

Ans: Array variable indicates the type of object that the array holds.

Ex: int arr[];

9) Java supports multidimensional arrays.

a)True

b)False

Ans: a.

10) An array of arrays can be created.

a)True

b)False

Ans: a.

11) What is a string?

Ans: A combination of characters is called as string.

12) Strings are instances of the class String.

a)True

b)False

Ans: a.

13) When a string literal is used in the program, Java automatically creates instances of the string class.

a)True

b)False

Ans: a.

14) Which operator is to create and concatenate string?

Ans: Addition operator(+).

15) Which of the following declare an array of string objects?

String[ ] s;
String [ ]s:
String[ s]:
String s[ ]:
Ans : a, b and d

16) What is the value of a[3] as the result of the following array declaration?

1
2
3
4
Ans : d

17) Which of the following are primitive types?

byte
String
integer
Float
Ans : a.

18) What is the range of the char type?

0 to 2 16
0 to 2 15
0 to 2 16-1
0 to 2 15-1
Ans. d

19) What are primitive data types?

Ans : byte, short, int, long

float, double

boolean

char

20) What are default values of different primitive types?

Ans :

int - 0

short - 0

byte - 0

long - 0 l

float - 0.0 f

double - 0.0 d

boolean - false

char - null

21) Converting of primitive types to objects can be explicitly.

a)True

b)False

Ans: b.

22) How do we change the values of the elements of the array?

Ans : The array subscript expression can be used to change the values of the elements of the array.

23) What is final varaible?

Ans : If a variable is declared as final variable, then you can not change its value. It becomes constant.

24) What is static variable?

Ans : Static variables are shared by all instances of a class.

Top


--------------------------------------------------------------------------------

Operators
1) What are operators and what are the various types of operators available in Java?

Ans: Operators are special symbols used in expressions. The following are the types of operators:

Arithmetic operators,

Assignment operators,

Increment & Decrement operators,

Logical operators,

Biwise operators,

Comparison/Relational operators and

Conditional operators

2) The ++ operator is used for incrementing and the -- operator is used for

decrementing.

a)True

b)False

Ans: a.

3) Comparison/Logical operators are used for testing and magnitude.

a)True

b)False

Ans: a.

4) Character literals are stored as unicode characters.

a)True

b)False

Ans: a.

5) What are the Logical operators?

Ans: OR(|), AND(&), XOR(^) AND NOT(~).

6) What is the % operator?

Ans : % operator is the modulo operator or reminder operator. It returns the reminder of dividing the first operand by second operand.

7) What is the value of 111 % 13?

3
5
7
9
Ans : c.

8) Is &&= a valid operator?

Ans : No.

9) Can a double value be cast to a byte?

Ans : Yes

10) Can a byte object be cast to a double value ?

Ans : No. An object cannot be cast to a primitive value.

11) What are order of precedence and associativity?

Ans : Order of precedence the order in which operators are evaluated in expressions.

Associativity determines whether an expression is evaluated left-right or right-left.

12) Which Java operator is right associativity?

Ans : = operator.

13) What is the difference between prefix and postfix of -- and ++ operators?

Ans : The prefix form returns the increment or decrement operation and returns the value of the increment or decrement operation.

The postfix form returns the current value of all of the expression and then

performs the increment or decrement operation on that value.

14) What is the result of expression 5.45 + "3,2"?

The double value 8.6
The string ""8.6"
The long value 8.
The String "5.453.2"
Ans : d

15) What are the values of x and y ?

x = 5; y = ++x;

Ans : x = 6; y = 6

16) What are the values of x and z?

x = 5; z = x++;

Ans : x = 6; z = 5

Top


--------------------------------------------------------------------------------

Control Statements
1) What are the programming constructs?

Ans:

a) Sequential

b) Selection -- if and switch statements

c) Iteration -- for loop, while loop and do-while loop

2) class conditional {

public static void main(String args[]) {

int i = 20;

int j = 55;

int z = 0;

z = i < j ? i : j; // ternary operator

System.out.println("The value assigned is " + z);

}

}

What is output of the above program?

Ans: The value assigned is 20

3) The switch statement does not require a break.

a)True

b)False

Ans: b.

4) The conditional operator is otherwise known as the ternary operator.

a)True

b)False

Ans: a.

5) The while loop repeats a set of code while the condition is false.

a)True

b)False

Ans: b.

6) The do-while loop repeats a set of code atleast once before the condition is tested.

a)True

b)False

Ans: a.

7) What are difference between break and continue?

Ans: The break keyword halts the execution of the current loop and forces control out of the loop.

The continue is similar to break, except that instead of halting the execution of the loop, it starts the next iteration.

8) The for loop repeats a set of statements a certain number of times until a condition is matched.

a)True

b)False

Ans: a.

9) Can a for statement loop indefintely?

Ans : Yes.

10) What is the difference between while statement and a do statement/

Ans : A while statement checks at the beginning of a loop to see whether the next loop iteration should occur.

A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

Top


--------------------------------------------------------------------------------

Introduction to Classes and Methods
1) Which is used to get the value of the instance variables?

Ans: Dot notation.

2) The new operator creates a single instance named class and returns a reference to that object.

a)True

b)False

Ans: a.

3) A class is a template for multiple objects with similar features.

a)True

b)False

Ans: a.

4) What is mean by garbage collection?

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.

5) 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.

6) What is calling method?

Ans: Calling methods are similar to calling or referring to an instance variable. These methods are accessed using dot notation.

Ex: obj.methodname(param1,param2)

7) Which method is used to determine the class of an object?

Ans: getClass( ) method can be used to find out what class the belongs to. This class is defined in the object class and is available to all objects.

8) All the classes in java.lang package are automatically imported when a program is compiled.

a)True

b)False

Ans: a.

9) How can class be imported to a program?

Ans: To import a class, the import keyword should be used as shown.;

import classname;

10) How can class be imported from a package to a program?

Ans: import java . packagename . classname (or) import java.package name.*;

11) What is a constructor?

Ans: A constructor is a special kind of method that determines how an object is initialized when created.

12) Which keyword is used to create an instance of a class?

Ans: new.

13) Which method is used to garbage collect an object?

Ans: finalize ().

14) Constructors can be overloaded like regular methods.

a)True

b)False

Ans: a.

15) What is casting?

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

16) Casting between primitive types allows conversion of one primitive type to another.

a)True

b)False

Ans: a.

17) Casting occurs commonly between numeric types.

a)True

b)False

Ans: a.

18) Boolean values can be cast into any other primitive type.

a)True

b)False

Ans: b.

19) Casting does not affect the original object or value.

a)True

b)False

Ans: a.

20) Which cast must be used to convert a larger value into a smaller one?

Ans: Explicit cast.

21) Which cast must be used to cast an object to another class?

Ans: Specific cast.

22) Which of the following features are common to both Java & C++?

A.The class declaration

b.The access modifiers

c.The encapsulation of data & methods with in objects

d.The use of pointers

Ans: a,b,c.

23) Which of the following statements accurately describe the use of access modifiers within a class definition?

a.They can be applied to both data & methods

b.They must precede a class's data variables or methods

c.They can follow a class's data variables or methods

d.They can appear in any order

e.They must be applied to data variables first and then to methods

Ans: a,b,d.

24) Suppose a given instance variable has been declared private. Can this instance variable be manipulated by methods out side its class?

a.yes

b.no

Ans: b.

25) Which of the following statements can be used to describe a public method?

a.It is accessible to all other classes in the hierarchy

b.It is accessablde only to subclasses of its parent class

c.It represents the public interface of its class

d.The only way to gain access to this method is by calling one of the public class

methods

Ans: a,c.

26) Which of the following types of class members can be part of the internal part of a class?

a.Public instance variables

b.Private instance variables

c.Public methods

d.Private methods

Ans: b,d.

27) You would use the ____ operator to create a single instance of a named class.

a.new

b.dot

Ans: a.

28) Which of the following statements correctly describes the relation between an object and the instance variable it stores?

a.Each new object has its own distinctive set of instance variables

b.Each object has a copy of the instance variables of its class

c.the instance variable of each object are seperate from the variables of other objects

d.The instance variables of each object are stored together with the variables of other objects

Ans: a,b,c.

29) If no input parameters are specified in a method declaration then the declaration will include __.

a.an empty set of parantheses

b.the term void

Ans: a.

30) What are the functions of the dot(.) operator?

a.It enables you to access instance variables of any objects within a class

b.It enables you to store values in instance variables of an object

c.It is used to call object methods

d.It is to create a new object

Ans: a,b,c.

31) Which of the following can be referenced by this variable?

a.The instance variables of a class only

b.The methods of a class only

c.The instance variables and methods of a class

Ans: c.

32) The this reference is used in conjunction with ___methods.

a.static

b.non-static

Ans: b.

33) Which of the following operators are used in conjunction with the this and super references?

a.The new operator

b.The instanceof operator

c.The dot operator

Ans: c.

34) A constructor is automatically called when an object is instantiated

a. true

b. false

Ans: a.

35) When may a constructor be called without specifying arguments?

a. When the default constructor is not called

b. When the name of the constructor differs from that of the class

c. When there are no constructors for the class

Ans: c.

36) Each class in java can have a finalizer method

a. true

b.false

Ans: a.

37) When an object is referenced, does this mean that it has been identified by the finalizer method for garbage collection?

a.yes

b.no

Ans: b.

38) Because finalize () belongs to the java.lang.Object class, it is present in all ___.

a.objects

b.classes

c.methods

Ans: b.

39) Identify the true statements about finalization.

a.A class may have only one finalize method

b.Finalizers are mostly used with simple classes

c.Finalizer overloading is not allowed

Ans: a,c.

40) When you write finalize() method for your class, you are overriding a finalizer inherited from a super class.

a.true

b.false

Ans: a.

41) Java memory management mechanism garbage collects objects which are no longer referenced

a true

b.false

Ans: a.

42) are objects referenced by a variable candidates for garbage collection when the variable goes out of scope?

a yes

b. no

Ans: a.

43) Java's garbage collector runs as a ___ priority thread waiting for __priority threads to relinquish the processor.

a.high

b.low

Ans: a,b.

44) The garbage collector will run immediately when the system is out of memory

a.true

b.false

Ans: a.

45) You can explicitly drop a object reference by setting the value of a variable whose data type is a reference type to ___

Ans: null

46) When might your program wish to run the garbage collecter?

a. before it enters a compute-intense section of code

b. before it enters a memory-intense section of code

c. before objects are finalized

d. when it knows there will be some idle time

Ans: a,b,d

47) For externalizable objects the class is solely responsible for the external format of its contents

a.true

b.false

Ans: a

48) When an object is stored, are all of the objects that are reachable from that object stored as well?

a.true

b.false

Ans: a

49) The default__ of objects protects private and trancient data, and supports the __ of the classes

a.evolution

b.encoding

Ans: b,a.

50) Which are keywords in Java?

a) NULL

b) sizeof

c) friend

d) extends

e) synchronized

Ans : d and e

51) When must the main class and the file name coincide?

Ans :When class is declared public.

52) What are different modifiers?

Ans : public, private, protected, default, static, trancient, volatile, final, abstract.

53) What are access modifiers?

Ans : public, private, protected, default.

54) What is meant by "Passing by value" and " Passing by reference"?

Ans : objects – pass by referrence

Methods - pass by value

55) Is a class a subclass of itself?

Ans : A class is a subclass itself.

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

Ans : public, abstract, final.

57) What is an example of polymorphism?

Inner class
Anonymous classes
Method overloading
Method overriding
Ans : c

Top


--------------------------------------------------------------------------------

Packages and interface
1) What are packages ? what is use of packages ?

Ans :The package statement defines a name space in which classes are stored.If you omit the package, the classes are put into the default package.

Signature... package pkg;

Use: * It specifies to which package the classes defined in a file belongs to. * Package is both naming and a visibility control mechanism.

2) What is difference between importing "java.applet.Applet" and "java.applet.*;" ?

Ans :"java.applet.Applet" will import only the class Applet from the package java.applet

Where as "java.applet.*" will import all the classes from java.applet package.

3) What do you understand by package access specifier?

Ans : public: Anything declared as public can be accessed from anywhere

private: Anything declared in the private can’t be seen outside of its class.

default: It is visible to subclasses as well as to other classes in the same package.

4) What is interface? What is use of interface?

Ans : It is similar to class which may contain method’s signature only but not bodies.

Methods declared in interface are abstract methods. We can implement many interfaces on a class which support the multiple inheritance.

5) Is it is necessary to implement all methods in an interface?

Ans : Yes. All the methods have to be implemented.

6) Which is the default access modifier for an interface method?

Ans : public.

7) Can we define a variable in an interface ?and what type it should be ?

Ans : Yes we can define a variable in an interface. They are implicitly final and static.

8) What is difference between interface and an abstract class?

Ans : All the methods declared inside an Interface are abstract. Where as abstract class must have at least one abstract method and others may be concrete or abstract.

In Interface we need not use the keyword abstract for the methods.

9) By default, all program import the java.lang package.

True/False

Ans : True

10) Java compiler stores the .class files in the path specified in CLASSPATH

environmental variable.

True/False

Ans : False

11) User-defined package can also be imported just like the standard packages.

True/False

Ans : True

12) When a program does not want to handle exception, the ______class is used.

Ans : Throws

13) The main subclass of the Exception class is _______ class.

Ans : RuntimeException

14) Only subclasses of ______class may be caught or thrown.

Ans : Throwable

15) Any user-defined exception class is a subclass of the _____ class.

Ans : Exception

16) The catch clause of the user-defined exception class should ______ its Base class catch clause.

Ans : Exception

17) A _______ is used to separate the hierarchy of the class while declaring an Import statement.

Ans : Package

18) All standard classes of Java are included within a package called _____.

Ans : java.lang

19) All the classes in a package can be simultaneously imported using ____.

Ans : *

20) Can you define a variable inside an Interface. If no, why? If yes, how?

Ans.: YES. final and static

21) How many concrete classes can you have inside an interface?

Ans.: None

22) Can you extend an interface?

Ans.: Yes

23) Is it necessary to implement all the methods of an interface while implementing the interface?

Ans.: No

24) If you do not implement all the methods of an interface while implementing , what specifier should you use for the class ?

Ans.: abstract

25) How do you achieve multiple inheritance in Java?

Ans: Using interfaces.

26) How to declare an interface example?

Ans : access class classname implements interface.

27) Can you achieve multiple interface through interface?

a)True

b) false

Ans : a.

28) Can variables be declared in an interface ? If so, what are the modifiers?

Ans : Yes. final and static are the modifiers can be declared in an interface.

29) What are the possible access modifiers when implementing interface methods?

Ans : public.

30) Can anonymous classes be implemented an interface?

Ans : Yes.

31) Interfaces can’t be extended.

a)True

b)False

Ans : b.

32) Name interfaces without a method?

Ans : Serializable, Cloneble & Remote.

33) Is it possible to use few methods of an interface in a class ? If so, how?

Ans : Yes. Declare the class as abstract.

Top


--------------------------------------------------------------------------------

Exception Handling
1) What is the difference between ‘throw’ and ‘throws’ ?And it’s application?

Ans : Exceptions that are thrown by java runtime systems can be handled by Try and catch blocks. With throw exception we can handle the exceptions thrown by the program itself. If a method is capable of causing an exception that it does not

handle, it must specify this behavior so the callers of the method can guard

against that exception.

2) What is the difference between ‘Exception’ and ‘error’ in java?

Ans : Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. With exception class we can subclass to create our own custom exception.

Error defines exceptions that are not excepted to be caught by you program. Example is Stack Overflow.

3) What is ‘Resource leak’?

Ans : Freeing up other resources that might have been allocated at the beginning of a method.

4)What is the ‘finally’ block?

Ans : Finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also execute.

5) Can we have catch block with out try block? If so when?

Ans : No. Try/Catch or Try/finally form a unit.

6) What is the difference between the following statements?

Catch (Exception e),

Catch (Error err),

Catch (Throwable t)

Ans :

7) What will happen to the Exception object after exception handling?

Ans : It will go for Garbage Collector. And frees the memory.

8) How many Exceptions we can define in ‘throws’ clause?

Ans : We can define multiple exceptions in throws clause.

Signature is..

type method-name (parameter-list) throws exception-list

9) The finally block is executed when an exception is thrown, even if no catch matches it.

True/False

Ans : True

10) The subclass exception should precede the base class exception when used within the catch clause.

True/False

Ans : True

11) Exceptions can be caught or rethrown to a calling method.

True/False

Ans : True

12) The statements following the throw keyword in a program are not executed.

True/False

Ans : True

13) The toString ( ) method in the user-defined exception class is overridden.

True/False

Ans : True

Top


--------------------------------------------------------------------------------

Multi Threading
1) What are the two types of multitasking?

Ans :

1.process-based

2.Thread-based

2) What are the two ways to create the thread?

Ans :

1.by implementing Runnable

2.by extending Thread

3) What is the signature of the constructor of a thread class?

Ans : Thread(Runnable threadob,String threadName)

4) What are all the methods available in the Runnable Interface?

Ans : run()

5) What is the data type for the method isAlive() and this method is available in which class?

Ans : boolean, Thread

6) What are all the methods available in the Thread class?

Ans :

1.isAlive()

2.join()

3.resume()

4.suspend()

5.stop()

6.start()

7.sleep()

8.destroy()

7) What are all the methods used for Inter Thread communication and what is the class in which these methods are defined?

Ans :

1. wait(),notify() & notifyall()

2. Object class

8) What is the mechanisam defind by java for the Resources to be used by only one Thread at a time?

Ans : Synchronisation

9) What is the procedure to own the moniter by many threads?

Ans : not possible

10) What is the unit for 1000 in the below statement?

ob.sleep(1000)

Ans : long milliseconds

11) What is the data type for the parameter of the sleep() method?

Ans : long

12) What are all the values for the following level?

max-priority

min-priority

normal-priority

Ans : 10,1,5

13) What is the method available for setting the priority?

Ans : setPriority()

14) What is the default thread at the time of starting the program?

Ans : main thread

15) The word synchronized can be used with only a method.

True/ False

Ans : False

16) Which priority Thread can prompt the lower primary Thread?

Ans : Higher Priority

17) How many threads at a time can access a monitor?

Ans : one

18) What are all the four states associated in the thread?

Ans : 1. new 2. runnable 3. blocked 4. dead

19) The suspend()method is used to teriminate a thread?

True /False

Ans : False

20) The run() method should necessary exists in clases created as subclass of thread?

True /False

Ans : True

21) When two threads are waiting on each other and can't proceed the programe is said to be in a deadlock?

True/False

Ans : True

22) Which method waits for the thread to die ?

Ans : join() method

23) Which of the following is true?

1) wait(),notify(),notifyall() are defined as final & can be called only from with in a synchronized method

2) Among wait(),notify(),notifyall() the wait() method only throws IOException

3) wait(),notify(),notifyall() & sleep() are methods of object class

1
2
3
1 & 2
1,2 & 3
Ans : D

24) Garbage collector thread belongs to which priority?

Ans : low-priority

25) What is meant by timeslicing or time sharing?

Ans : Timeslicing is the method of allocating CPU time to individual threads in a priority schedule.

26) What is meant by daemon thread? In java runtime, what is it's role?

Ans : Daemon thread is a low priority thread which runs intermittently in the background doing the garbage collection operation for the java runtime system.

Top


--------------------------------------------------------------------------------

Inheritance
1) What is the difference between superclass & subclass?

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

2) Which keyword is used to inherit a class?

Ans : extends

3) Subclasses methods can access superclass members/ attributes at all times?

True/False

Ans : False

4) When can subclasses not access superclass members?

Ans : When superclass is declared as private.

5) Which class does begin Java class hierarchy?

Ans : Object class

6) Object class is a superclass of all other classes?

True/False

Ans : True

7) Java supports multiple inheritance?

True/False

Ans : False

8) What is inheritance?

Ans : Deriving an object from an existing class. In the other words, Inheritance is the process of inheriting all the features from a class

9) What are the advantages of inheritance?

Ans : Reusability of code and accessibility of variables and methods of the superclass by subclasses.

10) Which method is used to call the constructors of the superclass from the subclass?

Ans : super(argument)

11) Which is used to execute any method of the superclass from the subclass?

Ans : super.method-name(arguments)

12) Which methods are used to destroy the objects created by the constructor methods?

Ans : finalize()

13) What are abstract classes?

Ans : Abstract classes are those for which instances can’t be created.

14) What must a class do to implement an interface?

Ans: It must provide all of the methods in the interface and identify the interface in its implements clause.

15) Which methods in the Object class are declared as final?

Ans : getClass(), notify(), notifyAll(), and wait()

16) Final methods can be overridden.

True/False

Ans : False

17) Declaration of methods as final results in faster execution of the program?

True/False

Ans: True

18) Final variables should be declared in the beginning?

True/False

Ans : True

19) Can we declare variable inside a method as final variables? Why?

Ans : Cannot because, local variable cannot be declared as final variables.

20) Can an abstract class may be final?

Ans : An abstract class may not be declared as final.

21) Does a class inherit the constructors of it's super class?

Ans: A class does not inherit constructors from any of it's super classes.

22) What restrictions are placed on method overloading?

Ans: Two methods may not have the same name and argument list but different return types.

23) What restrictions are placed on method overriding?

Ans : Overridden methods must have the same name , argument list , and return type. The overriding method may not limit the access of the method it overridees.The overriding method may not throw any exceptions that may not be thrown by the overridden method.

24) What modifiers may be used with an inner class that is a member of an outer class?

Ans : a (non-local) inner class may be declared as public, protected, private, static, final or abstract.

25) How this() is used with constructors?

Ans: this() is used to invoke a constructor of the same class

26) How super() used with constructors?

Ans : super() is used to invoke a super class constructor

27) Which of the following statements correctly describes an interface?

a)It's a concrete class

b)It's a superclass

c)It's a type of abstract class

Ans: c

28) An interface contains __ methods

a)Non-abstract

b)Implemented

c)unimplemented

Ans:c

Top


--------------------------------------------------------------------------------

String Handling
1) Which package does define String and StringBuffer classes?

Ans : java.lang package.

2) Which method can be used to obtain the length of the String?

Ans : length( ) method.

3) How do you concatenate Strings?

Ans : By using " + " operator.

4) Which method can be used to compare two strings for equality?

Ans : equals( ) method.

5) Which method can be used to perform a comparison between strings that ignores case differences?

Ans : equalsIgnoreCase( ) method.

6) What is the use of valueOf( ) method?

Ans : valueOf( ) method converts data from its internal format into a human-readable form.

7) What are the uses of toLowerCase( ) and toUpperCase( ) methods?

Ans : The method toLowerCase( ) converts all the characters in a string from uppercase to

lowercase.

The method toUpperCase( ) converts all the characters in a string from lowercase to

uppercase.

8) Which method can be used to find out the total allocated capacity of a StrinBuffer?

Ans : capacity( ) method.

9) Which method can be used to set the length of the buffer within a StringBuffer object?

Ans : setLength( ).

10) What is the difference between String and StringBuffer?

Ans : String objects are constants, whereas StringBuffer objects are not.

String class supports constant strings, whereas StringBuffer class supports growable, modifiable strings.

11) What are wrapper classes?

Ans : Wrapper classes are classes that allow primitive types to be accessed as objects.

12) Which of the following is not a wrapper class?

String
Integer
Boolean
Character
Ans : a.

13) What is the output of the following program?

public class Question {

public static void main(String args[]) {

String s1 = "abc";

String s2 = "def";

String s3 = s1.concat(s2.toUpperCase( ) );

System.out.println(s1+s2+s3);

}

}

abcdefabcdef
abcabcDEFDEF
abcdefabcDEF
None of the above
ANS : c.

14) Which of the following methods are methods of the String class?

delete( )
append( )
reverse( )
replace( )
Ans : d.

15) Which of the following methods cause the String object referenced by s to be changed?

s.concat( )
s.toUpperCase( )
s.replace( )
s.valueOf( )
Ans : a and b.

16) String is a wrapper class?

True
False
Ans : b.

17) If you run the code below, what gets printed out?

String s=new String("Bicycle");

int iBegin=1;

char iEnd=3;

System.out.println(s.substring(iBegin,iEnd));

Bic
ic
icy
error: no method matching substring(int,char)
Ans : b.

18) Given the following declarations

String s1=new String("Hello")

String s2=new String("there");

String s3=new String();

Which of the following are legal operations?

s3=s1 + s2;
s3=s1 - s2;
s3=s1 & s2
s3=s1 && s2
Ans : a.

19) Which of the following statements are true?

a)The String class is implemented as a char array, elements are addressed using the stringname[] convention

b) Strings are a primitive type in Java that overloads the + operator for concatenation

c) Strings are a primitive type in Java and the StringBuffer is used as the matching wrapper type

d) The size of a string can be retrieved using the length property.

Ans : b.

Top


--------------------------------------------------------------------------------

Exploring Java.lang
1) java.lang package is automatically imported into all programs.

True
False
Ans : a

2) What are the interfaces defined by java.lang?

Ans : Cloneable, Comparable and Runnable.

3) What are the constants defined by both Flaot and Double classes?

Ans : MAX_VALUE,

MIN_VALUE,

NaN ,

POSITIVE_INFINITY,

NEGATIVE_INFINITY and

TYPE.

4) What are the constants defined by Byte, Short, Integer and Long?

Ans : MAX_VALUE,

MIN_VALUE and

TYPE.

5) What are the constants defined by both Float and Double classes?

Ans : MAX_RADIX,

MIN_RADIX,

MAX_VALUE,

MIN_VALUE and

TYPE.

6) What is the purpose of the Runtime class?

Ans : The purpose of the Runtime class is to provide access to the Java runtime system.

7) What is the purpose of the System class?

Ans : The purpose of the System class is to provide access to system resources.

8) Which class is extended by all other classes?

Ans : Object class is extended by all other classes.

9) Which class can be used to obtain design information about an object?

Ans : The Class class can be used to obtain information about an object’s design.

10) Which method is used to calculate the absolute value of a number?

Ans : abs( ) method.

11) What are E and PI?

Ans : E is the base of the natural logarithm and PI is the mathematical value pi.

12) Which of the following classes is used to perform basic console I/O?

System
SecurityManager
Math
Runtime
Ans : a.

13) Which of the following are true?

The Class class is the superclass of the Object class.
The Object class is final.
The Class class can be used to load other classes.
The ClassLoader class can be used to load other classes.
Ans : c and d.

14) Which of the following methods are methods of the Math class?

absolute( )
log( )
cosine( )
sine( )
Ans : b.

15) Which of the following are true about the Error and Exception classes?

Both classes extend Throwable.
The Error class is final and the Exception class is not.
The Exception class is final and the Error is not.
Both classes implement Throwable.
Ans : a.

16) Which of the following are true?

The Void class extends the Class class.
The Float class extends the Double class.
The System class extends the Runtime class.
The Integer class extends the Number class.
Ans : d.

17) Which of the following will output -4.0

System.out.println(Math.floor(-4.7));
System.out.println(Math.round(-4.7));
System.out.println(Math.ceil(-4.7));
System.out.println(Math.Min(-4.7));
Ans : c.

18) Which of the following are valid statements

a) public class MyCalc extends Math
b) Math.max(s);
c) Math.round(9.99,1);
d) Math.mod(4,10);

e) None of the above.

Ans : e.

19) What will happen if you attempt to compile and run the following code?

Integer ten=new Integer(10);

Long nine=new Long (9);

System.out.println(ten + nine);

int i=1;

System.out.println(i + ten);

19 followed by 20
19 followed by 11
Error: Can't convert java lang Integer
d) 10 followed by 1

Ans : c.

Top


--------------------------------------------------------------------------------

Input/Output: Exploring Java.io
1) What is meant by Stream and what are the types of Streams and classes of the Streams?

Ans : A Stream is an abstraction that either produces or consumes information.

There are two types of Streams. They are:

Byte Streams : Byte Streams provide a convenient means for handling input and output of bytes.

Character Streams : Character Streams provide a convenient means for handling input and output of characters.

Byte Stream classes : Byte Streams are defined by using two abstract classes. They are:InputStream and OutputStream.

Character Stream classes : Character Streams are defined by using two abstract classes. They are : Reader and Writer.

2) Which of the following statements are true?

UTF characters are all 8-bits.
UTF characters are all 16-bits.
UTF characters are all 24-bits.
Unicode characters are all 16-bits.
Bytecode characters are all 16-bits.
Ans : d.

3) Which of the following statements are true?

When you construct an instance of File, if you do not use the filenaming semantics of the local machine, the constructor will throw an IOException.
When you construct an instance of File, if the corresponding file does not exist on the local file system, one will be created.
When an instance of File is garbage collected, the corresponding file on the local file system is deleted.
None of the above.
Ans : a,b and c.

4) The File class contains a method that changes the current working directory.

True
False
Ans : b.

5) It is possible to use the File class to list the contents of the current working directory.

True
False
Ans : a.

6) Readers have methods that can read and return floats and doubles.

True
False
Ans : b.

7) You execute the code below in an empty directory. What is the result?

File f1 = new File("dirname");

File f2 = new File(f1, "filename");

A new directory called dirname is created in the current working directory.
A new directory called dirname is created in the current working directory. A new file called filename is created in directory dirname.
A new directory called dirname and a new file called filename are created, both in the current working directory.
A new file called filename is created in the current working directory.
No directory is created, and no file is created.
Ans : e.

8) What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

Ans : The Reader/Writer class hierarchy is character-oriented and the InputStream/OutputStream class hierarchy is byte-oriented.

9) What is an I/O filter?

Ans : An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

10) What is the purpose of the File class?

Ans : The File class is used to create objects that provide access to the files and directories of a local file system.

11) What interface must an object implement before it can be written to a stream as an object?

Ans : An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

12) What is the difference between the File and RandomAccessFile classes?

Ans : The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

13) What class allows you to read objects directly from a stream?

Ans : The ObjectInputStream class supports the reading of objects from input streams.

14) What value does read( ) return when it has reached the end of a file?

Ans : The read( ) method returns – 1 when it has reached the end of a file.

15) What value does readLine( ) return when it has reached the end of a file?

Ans : The readLine( ) method returns null when it has reached the end of a file.

16) How many bits are used to represent Unicode, ASCII, UTF-16 and UTF-8 characters?

Ans : Unicode requires 16-bits and ASCII requires 8-bits. Although the ASCII character set uses only 1-bits, it is usually represented as 8-bits. UTF-8 represents characters using 8, 16 and 18-bit patterns. UTF-16 uses 16-bit and larger bit patterns.

17) Which of the following are true?

The InputStream and OutputStream classes are byte-oriented.
The ObjectInputStream and ObjectOutputStream do not support serialized object input and output.
The Reader and Writer classes are character-oriented.
The Reader and Writer classes are the preferred solution to serialized object output.
Ans : a and c.

18) Which of the following are true about I/O filters?

Filters are supported on input, but not on output.
Filters are supported by the InputStream/OutputStream class hierarchy, but not by the Reader/Writer class hierarchy.
Filters read from one stream and write to another.
A filter may alter data that is read from one stream and written to another.
Ans : c and d.

java interviews 66

16) Which Font attributes are available through the FontMetrics class?

ascent
leading
case
height
Ans : a, b and d.

17) Which of the following are true?

The AWT automatically causes a window to be repainted when a portion of a window has been minimized and then maximized.
The AWT automatically causes a window to be repainted when a portion of a window has been covered and then uncovered.
The AWT automatically causes a window to be repainted when application data is changed.
The AWT does not support repainting operations.
Ans : a and b.

18) Which method is used to size a graphics object to fit the current size of the window?

Ans : getSize( ) method.

19) What are the methods to be used to set foreground and background colors?

Ans : setForeground( ) and setBackground( ) methods.

20) You have created a simple Frame and overridden the paint method as follows

public void paint(Graphics g){



g.drawString("Dolly",50,10);



}

What will be the result when you attempt to compile and run the program?

a) The string "Dolly" will be displayed at the centre of the frame

b) An error at compilation complaining at the signature of the paint method
c) The lower part of the word Dolly will be seen at the top of the form, with the top hidden.
d) The string "Dolly" will be shown at the bottom of the form

Ans : c.

21) Where g is a graphics instance what will the following code draw on the screen.

g.fillArc(45,90,50,50,90,180);

a) An arc bounded by a box of height 45, width 90 with a centre point of 50,50, starting
at an angle of 90 degrees traversing through 180 degrees counter clockwise.

b) An arc bounded by a box of height 50, width 50, with a centre point of 45,90 starting
at an angle of 90 degrees traversing through 180 degrees clockwise.

c) An arc bounded by a box of height 50, width 50, with a top left at coordinates of 45,
90, starting at 90 degrees and traversing through 180 degrees counter clockwise.

d) An arc starting at 45 degrees, traversing through 90 degrees clockwise bounded by a
box of height 50, width 50 with a centre point of 90, 180.

Ans : c.

22) Given the following code
import java.awt.*;
public class SetF extends Frame{
public static void main(String argv[]){
SetF s = new SetF();
s.setSize(300,200);
s.setVisible(true);
}
}
How could you set the frame surface color to pink

a)s.setBackground(Color.pink);
b)s.setColor(PINK);
c)s.Background(pink);
d)s.color=Color.pink

Ans : a.

Top


--------------------------------------------------------------------------------

AWT: Controls, Layout Managers and Menus
1) What is meant by Controls and what are different types of controls?

Ans : Controls are componenets that allow a user to interact with your application.

The AWT supports the following types of controls:

Labels
Push buttons
Check boxes
Choice lists
Lists
Scroll bars
Text components
These controls are subclasses of Component.

2) You want to construct a text area that is 80 character-widths wide and 10 character-heights tall. What code do you use?

new TextArea(80, 10)
new TextArea(10, 80)
Ans: b.

3) A text field has a variable-width font. It is constructed by calling new TextField("iiiii"). What happens if you change the contents of the text field to "wwwww"? (Bear in mind that is one of the narrowest characters, and w is one of the widest.)

The text field becomes wider.
The text field becomes narrower.
The text field stays the same width; to see the entire contents you will have to scroll by using the ß and à keys.
The text field stays the same width; to see the entire contents you will have to scroll by using the text field’s horizontal scroll bar.
Ans : c.

4) The CheckboxGroup class is a subclass of the Component class.

True
False
Ans : b.

5) What are the immediate super classes of the following classes?

a) Container class
b) MenuComponent class
c) Dialog class
d) Applet class
e) Menu class
Ans : a) Container - Component

b) MenuComponent - Object

c) Dialog - Window

d) Applet - Panel

e) Menu - MenuItem

6) What are the SubClass of Textcomponent Class?

Ans : TextField and TextArea

7) Which method of the component class is used to set the position and the size of a component?

Ans : setBounds()

8) Which TextComponent method is used to set a TextComponent to the read-only state?

Ans : setEditable()

9) How can the Checkbox class be used to create a radio button?

Ans : By associating Checkbox objects with a CheckboxGroup.

10) What Checkbox method allows you to tell if a Checkbox is checked?

Ans : getState()

11) Which Component method is used to access a component's immediate Container?

getVisible()
getImmediate
getParent()
getContainer
Ans : c.

12) What methods are used to get and set the text label displayed by a Button object?

Ans : getLabel( ) and setLabel( )

13) What is the difference between a Choice and a List?

Ans : A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice.

A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.

14) Which Container method is used to cause a container to be laid out and redisplayed?

Ans : validate( )

15) What is the difference between a Scollbar and a Scrollpane?

Ans : A Scrollbar is a Component, but not a Container.

A Scrollpane is a Container and handles its own events and performs its own

scrolling.

16) Which Component subclass is used for drawing and painting?

Ans : Canvas.

17) Which of the following are direct or indirect subclasses of Component?

Button
Label
CheckboxMenuItem
Toolbar
Frame
Ans : a, b and e.

18) Which of the following are direct or indirect subclasses of Container?

Frame
TextArea
MenuBar
FileDialog
Applet
Ans : a,d and e.

19) Which method is used to set the text of a Label object?

setText( )
setLabel( )
setTextLabel( )
setLabelText( )
Ans : a.

20) Which constructor creates a TextArea with 10 rows and 20 columns?

new TextArea(10, 20)
new TextArea(20, 10)
new TextArea(new Rows(10), new columns(20))
new TextArea(200)
Ans : a.

(Usage is TextArea(rows, columns)

21) Which of the following creates a List with 5 visible items and multiple selection enabled?

new List(5, true)
new List(true, 5)
new List(5, false)
new List(false,5)
Ans : a.

[Usage is List(rows, multipleMode)]

22) Which are true about the Container class?

The validate( ) method is used to cause a Container to be laid out and redisplayed.
The add( ) method is used to add a Component to a Container.
The getBorder( ) method returns information about a Container’s insets.
The getComponent( ) method is used to access a Component that is contained in a Container.
Ans : a, b and d.

23) Suppose a Panel is added to a Frame and a Button is added to the Panel. If the Frame’s font is set to 12-point TimesRoman, the Panel’s font is set to 10-point TimesRoman, and the Button’s font is not set, what font will be used to dispaly the Button’s label?

12-point TimesRoman
11-point TimesRoman
10-point TimesRoman
9-point TimesRoman
Ans : c.

24) A Frame’s background color is set to Color.Yellow, and a Button’s background color is to Color.Blue. Suppose the Button is added to a Panel, which is added to the Frame. What background color will be used with the Panel?

Colr.Yellow
Color.Blue
Color.Green
Color.White
Ans : a.

25) Which method will cause a Frame to be displayed?

show( )
setVisible( )
display( )
displayFrame( )
Ans : a and b.

26) All the componenet classes and container classes are derived from _________ class.

Ans : Object.

27) Which method of the container class can be used to add components to a Panel.

Ans : add ( ) method.

28) What are the subclasses of the Container class?

Ans : The Container class has three major subclasses. They are :

Window
Panel
ScrollPane
29) The Choice component allows multiple selection.

True.
False.
Ans : b.

30) The List component does not generate any events.

True.
False.
Ans : b.

31) Which components are used to get text input from the user.

Ans : TextField and TextArea.

32) Which object is needed to group Checkboxes to make them exclusive?

Ans : CheckboxGroup.

33) Which of the following components allow multiple selections?

Non-exclusive Checkboxes.
Radio buttons.
Choice.
List.
Ans : a and d.

34) What are the types of Checkboxes and what is the difference between them?

Ans : Java supports two types of Checkboxes. They are : Exclusive and Non-exclusive.

In case of exclusive Checkboxes, only one among a group of items can be selected at a time. I f an item from the group is selected, the checkbox currently checked is deselected and the new selection is highlighted. The exclusive Checkboxes are also called as Radio buttons.

The non-exclusive checkboxes are not grouped together and each one can be selected independent of the other.

35) What is a Layout Manager and what are the different Layout Managers available in java.awt and what is the default Layout manager for the panal and the panal subclasses?

Ans: A layout Manager is an object that is used to organize components in a container.

The different layouts available in java.awt are :

FlowLayout, BorderLayout, CardLayout, GridLayout and GridBag Layout.

The default Layout Manager of Panal and Panal sub classes is FlowLayout".

36) Can I exert control over the size and placement of components in my interface?

Ans : Yes.

myPanal.setLayout(null);

myPanal.setbounds(20,20,200,200);

37) Can I add the same component to more than one container?

Ans : No. Adding a component to a container automatically removes it from any previous parent(container).

38) How do I specify where a window is to be placed?

Ans : Use setBounds, setSize, or setLocation methods to implement this.

setBounds(int x, int y, int width, int height)

setBounds(Rectangle r)

setSize(int width, int height)

setSize(Dimension d)

setLocation(int x, int y)

setLocation(Point p)



39) How can we create a borderless window?

Ans : Create an instance of the Window class, give it a size, and show it on the screen.

eg. Frame aFrame = ......

Window aWindow = new Window(aFrame);

aWindow.setLayout(new FlowLayout());

aWindow.add(new Button("Press Me"));

aWindow.getBounds(50,50,200,200);

aWindow.show();

40) Can I create a non-resizable windows? If so, how?

Ans: Yes. By using setResizable() method in class Frame.

41) What is the default Layout Manager for the Window and Window subclasses (Frame,Dialog)?

Ans : BorderLayout().

42) How are the elements of different layouts organized?

Ans : FlowLayout : The elements of a FlowLayout are organized in a top to bottom, left to right fashion.

BorderLayout : The elements of a BorderLayout are organized at the

borders (North, South, East and West) and the center of a

container.

CardLayout : The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.

GridLayout : The elements of a GridLayout are of equal size and are laid out using the square of a grid.

GridBagLayout : The elements of a GridBagLayout are organized according to a grid.However, the elements are of different sizes and may occupy

more than one row or column of the grid. In addition, the rows and columns may have different sizes.

43) Which containers use a BorderLayout as their default layout?

Ans : The Window, Frame and Dialog classes use a BorderLayout as their default layout.

44) Which containers use a FlowLayout as their default layout?

Ans : The Panel and the Applet classes use the FlowLayout as their default layout.

45) What is the preferred size of a component?

Ans : The preferred size of a component size that will allow the component to display normally.

46) Which method is method to set the layout of a container?

startLayout( )
initLayout( )
layoutContainer( )
setLayout( )
Ans : d.

47) Which method returns the preferred size of a component?

getPreferredSize( )
getPreferred( )
getRequiredSize( )
getLayout( )
Ans : a.

48) Which layout should you use to organize the components of a container in a tabular form?

CardLayout
BorederLayout
FlowLayout
GridLayout
Ans : d.

49) An application has a frame that uses a Border layout manager. Why is it probably not a good idea to put a vertical scroll bar at North in the frame?

The scroll bar’s height would be its preferred height, which is not likely to be enough.
The scroll bar’s width would be the entire width of the frame, which would be much wider than necessary.
Both a and b.
Neither a nor b. There is no problem with the layout as described.
Ans : c.

50) What is the default layouts for a applet, a frame and a panel?

Ans : For an applet and a panel, Flow layout is the default layout, whereas Border layout is default layout for a frame.

51) If a frame uses a Grid layout manager and does not contain any panels, then all the components within the frame are the same width and height.

True
False.
Ans : a.

52) If a frame uses its default layout manager and does not contain any panels, then all the components within the frame are the same width and height.

True
False.
Ans : b.

53) With a Border layout manager, the component at Center gets all the space that is left over, after the components at North and South have been considered.

True
False
Ans : b.

54) An Applet has its Layout Manager set to the default of FlowLayout. What code would be the correct to change to another Layout Manager?

setLayoutManager(new GridLayout());
setLayout(new GridLayout(2,2));
setGridLayout(2,2,))
setBorderLayout();
Ans : b.

55) How do you indicate where a component will be positioned using Flowlayout?

a) North, South,East,West
b) Assign a row/column grid reference
c) Pass a X/Y percentage parameter to the add method
d) Do nothing, the FlowLayout will position the component

Ans :d.

56) How do you change the current layout manager for a container?

a) Use the setLayout method
b) Once created you cannot change the current layout manager of a component
c) Use the setLayoutManager method
d) Use the updateLayout method

Ans :a.

57)When using the GridBagLayout manager, each new component requires a new instance of the GridBagConstraints class. Is this statement true or false?

a) true
b) false

Ans : b.

58) Which of the following statements are true?

a)The default layout manager for an Applet is FlowLayout
b) The default layout manager for an application is FlowLayout
c) A layout manager must be assigned to an Applet before the setSize method is called
d) The FlowLayout manager attempts to honor the preferred size of any components

Ans : a and d.

59) Which method does display the messages whenever there is an item selection or deselection of the CheckboxMenuItem menu?

Ans : itemStateChanged method.

60) Which is a dual state menu item?

Ans : CheckboxMenuItem.

61) Which method can be used to enable/diable a checkbox menu item?

Ans : setState(boolean).

62) Which of the following may a menu contain?

A separator
A check box
A menu
A button
A panel
Ans : a and c.

63) Which of the following may contain a menu bar?

A panel
A frame
An applet
A menu bar
A menu
Ans : b

64) What is the difference between a MenuItem and a CheckboxMenuItem?

Ans : The CheckboxMenuItem class extends the MenuItem class to support a menu item

that may be checked or unchecked.


65) Which of the following are true?

A Dialog can have a MenuBar.
MenuItem extends Menu.
A MenuItem can be added to a Menu.
A Menu can be added to a Menu.
Ans : c and d.

Top


--------------------------------------------------------------------------------

Utility Package
1) What is the Vector class?

ANSWER : The Vector class provides the capability to implement a growable array of objects.

2) What is the Set interface?

ANSWER : The Set interface provides methods for accessing the elements of a finite mathematical set.Sets do not allow duplicate elements.

3) What is Dictionary class?

ANSWER : The Dictionary class is the abstarct super class of Hashtable and Properties class.Dictionary provides the abstarct functions used to store and retrieve objects by key-value.This class allows any object to be used as a key or value.

4) What is the Hashtable class?

ANSWER : The Hashtable class implements a hash table data structure. A hash table indexes and stores objects in a dictionary using hash codes as the objects' keys. Hash codes are integer values that identify objects.

5) What is the Properties class?

Answer : The properties class is a subclass of Hashtable that can be read from or written to a stream.It also provides the capability to specify a set of default values to be used if a specified key is not found in the table. We have two methods load() and save().

6) What changes are needed to make the following prg to compile?

import java.util.*;

class Ques{

public static void main (String args[]) {

String s1 = "abc";

String s2 = "def";

Vector v = new Vector();

v.add(s1);

v.add(s2);

String s3 = v.elementAt(0) + v.elementAt(1);

System.out.println(s3);

}

}

A) Declare Ques as public

B) Cast v.elementAt(0) to a String

C) Cast v.elementAt(1) to an Object.

D) Import java.lang

ANSWER : B) Cast v.elementAt(0) to a String

7) What is the output of the prg.

import java.util.*;

class Ques{

public static void main (String args[]) {

String s1 = "abc";

String s2 = "def";

Stack stack = new Stack();

stack.push(s1);

stack.push(s2);

try{

String s3 = (String) stack.pop() + (String) stack.pop() ;

System.out.println(s3);

}catch (EmptyStackException ex){}

}

}

A) abcdef

B) defabc

C) abcabc

D) defdef

ANSWER : B) defabc

9) Which of the following may have duplicate elements?

A)Collection

B) List

C) Map

D) Set

ANSWER : A and B Neither a Map nor a Set may have duplicate elements.

10) Can null value be added to a List?

ANSWER : Yes.A Null value may be added to any List.

11) What is the output of the following prg.

import java.util.*;

class Ques{

public static void main (String args[]) {

HashSet set = new HashSet();

String s1 = "abc";

String s2 = "def";

String s3 = "";

set.add(s1);

set.add(s2);

set.add(s1);

set.add(s2);

Iterator i = set.iterator();

while(i.hasNext())

{

s3 += (String) i.next();

}

System.out.println(s3);

}

}

A) abcdefabcdef B) defabcdefabc C) fedcbafedcba D) defabc

ANSWER : D) defabc. Sets may not have duplicate elements.

12) Which of the following java.util classes support internationalization?

A) Locale B) ResourceBundle C) Country D) Language

ANSWER : A and B . Country and Language are not java.util classes.

13) What is the ResourceBundle?

The ResourceBundle class also supports internationalization.
ResourceBundle subclasses are used to store locale-specific resources that can be loaded by a program to tailor the program's appearence to the paticular locale in which it is being run. Resource Bundles provide the capability to isolate a program's locale-specific resources in a standard and modular manner.

14) How are Observer Interface and Observable class, in java.util package, used?

ANSWER : Objects that subclass the Observable class maintain a list of Observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

15) Which java.util classes and interfaces support event handling?

ANSWER : The EventObject class and the EventListener interface support event processing.

16) Does java provide standard iterator functions for inspecting a collection of objects?

ANSWER : The Enumeration interface in the java.util package provides a framework for stepping once through a collection of objects. We have two methods in that interface.

public interface Enumeration {

boolean hasMoreElements();

Object nextElement();

}

17) The Math.random method is too limited for my needs- How can I generate random numbers more flexibly?

ANSWER : The random method in Math class provide quick, convienient access to random numbers, but more power and flexibility use the Random class in the java.util package.

double doubleval = Math.random();

The Random class provide methods returning float, int, double, and long values.

nextFloat() // type float; 0.0 <= value < 1.0

nextDouble() // type double; 0.0 <= value < 1.0

nextInt() // type int; Integer.MIN_VALUE <= value <= Integer.MAX_VALUE

nextLong() // type long; Long.MIN_VALUE <= value <= Long.MAX_VALUE

nextGaussian() // type double; has Gaussian("normal") distribution with mean 0.0 and standard deviation 1.0)

Eg. Random r = new Random();

float floatval = r.nextFloat();

18) How can we get all public methods of an object dynamically?

ANSWER : By using getMethods(). It return an array of method objects corresponding to the public methods of this class.

getFields() returns an array of Filed objects corresponding to the public Fields(variables) of this class.

getConstructors() returns an array of constructor objects corresponding to the public constructors of this class.

Top


--------------------------------------------------------------------------------

JDBC
1) What are the steps involved in establishing a connection?

ANSWER : This involves two steps: (1) loading the driver and (2) making the connection.

2) How can you load the drivers?

ANSWER : Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:

Eg.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code:

Eg.

Class.forName("jdbc.DriverXYZ");

3) What Class.forName will do while loading drivers?

ANSWER : It is used to create an instance of a driver and register it with the DriverManager.

When you have loaded a driver, it is available for making a connection with a DBMS.

4) How can you make the connection?

ANSWER : In establishing a connection is to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea:

Eg.

String url = "jdbc:odbc:Fred";

Connection con = DriverManager.getConnection(url, "Fernanda", "J8");

5) How can you create JDBC statements?

ANSWER : A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate.

Eg.

It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object stmt :

Statement stmt = con.createStatement();

6) How can you retrieve data from the ResultSet?

ANSWER : Step 1.

JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.

Eg.

ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

Step2.

String s = rs.getString("COF_NAME");

The method getString is invoked on the ResultSet object rs , so getString will retrieve (get) the value stored in the column COF_NAME in the current row of rs

7) What are the different types of Statements?

ANSWER : 1.Statement (use createStatement method) 2. Prepared Statement (Use prepareStatement method) and 3. Callable Statement (Use prepareCall)

8) How can you use PreparedStatement?

ANSWER : This special type of statement is derived from the more general class, Statement.If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead.

The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first.

Eg.

PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");

9) What setAutoCommit does?

ANSWER : When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode

Eg.

con.setAutoCommit(false);

Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly.

Eg.

con.setAutoCommit(false);

PreparedStatement updateSales = con.prepareStatement(

"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");

updateSales.setInt(1, 50);

updateSales.setString(2, "Colombian");

updateSales.executeUpdate();

PreparedStatement updateTotal = con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");

updateTotal.setInt(1, 50);

updateTotal.setString(2, "Colombian");

updateTotal.executeUpdate();

con.commit();

con.setAutoCommit(true);

10) How to call a Strored Procedure from JDBC?

ANSWER : The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open Connection

object. A CallableStatement object contains a call to a stored procedure;

Eg.

CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");

ResultSet rs = cs.executeQuery();

11) How to Retrieve Warnings?

ANSWER : SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned.

A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object

Eg.

SQLWarning warning = stmt.getWarnings();

if (warning != null) {

System.out.println("\n---Warning---\n");

while (warning != null) {

System.out.println("Message: " + warning.getMessage());

System.out.println("SQLState: " + warning.getSQLState());

System.out.print("Vendor error code: ");

System.out.println(warning.getErrorCode());

System.out.println("");

warning = warning.getNextWarning();

}

}

12) How can you Move the Cursor in Scrollable Result Sets ?

ANSWER : One of the new features in the JDBC 2.0 API is the ability to move a result set's cursor backward as well as forward. There are also methods that let you move the cursor to a particular row and check the position of the cursor.

Eg.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_READ_ONLY);

ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE .

The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE . The point to remember here is that if you specify a type, you must also specify whether it is read-only or updatable. Also, you must specify the type first, and because both parameters are of type int , the compiler will not complain if you switch the order.

Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY

13) What’s the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE?

ANSWER : You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened

Eg.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

srs.afterLast();

while (srs.previous()) {

String name = srs.getString("COF_NAME");

float price = srs.getFloat("PRICE");

System.out.println(name + " " + price);

}

14) How to Make Updates to Updatable Result Sets?

ANSWER : Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.

Eg.

Connection con = DriverManager.getConnection("jdbc:mySubprotocol:mySubName");

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_UPDATABLE);

ResultSet uprs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

Top


--------------------------------------------------------------------------------

Networking Concepts
1) The API doesn't list any constructors for InetAddress- How do I create an InetAddress instance?

ANSWER : In case of InetAddress the three methods getLocalHost, getByName, getByAllName can be used to create instances.

E.g.

InetAddress add1;

InetAddress add2;

try{

add1 = InetAddress.getByName("java.sun.com");

add2 = InetAddress.getByName("199.22.22.22");

}catch(UnknownHostException e){}

2) Is it possible to get the Local host IP?

ANSWER : Yes. Use InetAddress's getLocalHost method.

3) What's the Factory Method?

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

4) What’s the difference between TCP and UDP?

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

5) What is the Proxy Server?

ANSWER : A proxy server speaks the client side of a protocol to another server. This is often required when clients have certain restrictions on which servers they can connect to. And when several users are hitting a popular web site, a proxy server can get the contents of the web server's popular pages once, saving expensive internetwork transfers while providing faster access to those pages to the clients.

Also, we can get multiple connections for a single server.

6) What are the seven layers of OSI model?

ANSWER : Application, Presentation, Session, Transport, Network, DataLink, Physical Layer.

7) What Transport Layer does?

ANSWER : It ensures that the mail gets to its destination. If a packet fails to get its destination, it handles the process of notifying the sender and requesting that another packet be sent.

8) What is DHCP?

ANSWER : Dynamic Host Configuration Protocol, a piece of the TCP/IP protocol suite that handles the automatic assignment of IP addresses to clients.

9) What is SMTP?

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

10) In OSI N/w architecture, the dialogue control and token management are responsibilities of...

a) Network b) Session c) Application d) DataLink

ANSWER : b) Session Layer.

11) In OSI N/W Architecture, the routing is performed by ______

a) Network b) Session c) Application d) DataLink

Answer : Network Layer.

Top


--------------------------------------------------------------------------------

Networking
1) What is the difference between URL instance and URLConnection instance?

ANSWER : A URL instance represents the location of a resource, and a URLConnection instance represents a link for accessing or communicating with the resource at the location.

2) How do I make a connection to URL?

ANSWER : You obtain a URL instance and then invoke openConnection on it.

URLConnection is an abstract class, which means you can't directly create instances of it using a constructor. We have to invoke openConnection method on a URL instance, to get the right kind of connection for your URL.

Eg. URL url;

URLConnection connection;

try{ url = new URL("...");

conection = url.openConnection();

}catch (MalFormedURLException e) { }

3) What Is a Socket?

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

4) What information is needed to create a TCP Socket?

ANSWER : The Local System’s IP Address and Port Number. And the Remote System's IPAddress and Port Number.

5) What are the two important TCP Socket classes?

ANSWER : Socket and ServerSocket.

ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets. getInputStream() and getOutputStream() are the two methods available in Socket class.

6) When MalformedURLException and UnknownHostException throws?

ANSWER : When the specified URL is not connected then the URL throw MalformedURLException and If InetAddress’ methods getByName and getLocalHost are unabletoresolve the host name they throwan UnknownHostException.

Top


--------------------------------------------------------------------------------

Servlets
1) What is the servlet?

ANSWER : Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database.

Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface.

2) Whats the advantages using servlets than using CGI?

ANSWER : Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension.

3) What are the uses of Servlets?

ANSWER : A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing.

Servlets can forward requests to other servers and servlets.Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries.

4) Which pakage provides interfaces and classes for writing servlets?

ANSWER : javax

5) Whats the Servlet Interfcae?

ANSWER : The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.

Servlets-->Generic Servlet-->HttpServlet-->MyServlet.

The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

6) When a servlet accepts a call from a client, it receives two objects- What are they?

ANSWER : ServeltRequest: Which encapsulates the communication from the client to the server. ServletResponse: Whcih encapsulates the communication from the servlet back to the client. ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

7) What information that the ServletRequest interface allows the servlet access to?

ANSWER : Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it.

The input stream, ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods.

8) What information that the ServletResponse interface gives the servlet methods for replying to the client?

ANSWER : It Allows the servlet to set the content length and MIME type of the reply.

Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

9) What is the servlet Lifecycle?

ANSWER : Each servlet has the same life cycle:

A server loads and initializes the servlet (init())

The servlet handles zero or more client requests (service())

The server removes the servlet (destroy())

(some servers do this step only when they shut down)

10) How HTTP Servlet handles client requests?

ANSWER : An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

importent java interview questions 64

Exploring Java.lang
1) java.lang package is automatically imported into all programs.

True
False
Ans : a

2) What are the interfaces defined by java.lang?

Ans : Cloneable, Comparable and Runnable.

3) What are the constants defined by both Flaot and Double classes?

Ans : MAX_VALUE,

MIN_VALUE,

NaN ,

POSITIVE_INFINITY,

NEGATIVE_INFINITY and

TYPE.

4) What are the constants defined by Byte, Short, Integer and Long?

Ans : MAX_VALUE,

MIN_VALUE and

TYPE.

5) What are the constants defined by both Float and Double classes?

Ans : MAX_RADIX,

MIN_RADIX,

MAX_VALUE,

MIN_VALUE and

TYPE.

6) What is the purpose of the Runtime class?

Ans : The purpose of the Runtime class is to provide access to the Java runtime system.

7) What is the purpose of the System class?

Ans : The purpose of the System class is to provide access to system resources.

8) Which class is extended by all other classes?

Ans : Object class is extended by all other classes.

9) Which class can be used to obtain design information about an object?

Ans : The Class class can be used to obtain information about an object’s design.

10) Which method is used to calculate the absolute value of a number?

Ans : abs( ) method.

11) What are E and PI?

Ans : E is the base of the natural logarithm and PI is the mathematical value pi.

12) Which of the following classes is used to perform basic console I/O?

System
SecurityManager
Math
Runtime
Ans : a.

13) Which of the following are true?

The Class class is the superclass of the Object class.
The Object class is final.
The Class class can be used to load other classes.
The ClassLoader class can be used to load other classes.
Ans : c and d.

14) Which of the following methods are methods of the Math class?

absolute( )
log( )
cosine( )
sine( )
Ans : b.

15) Which of the following are true about the Error and Exception classes?

Both classes extend Throwable.
The Error class is final and the Exception class is not.
The Exception class is final and the Error is not.
Both classes implement Throwable.
Ans : a.

16) Which of the following are true?

The Void class extends the Class class.
The Float class extends the Double class.
The System class extends the Runtime class.
The Integer class extends the Number class.
Ans : d.

17) Which of the following will output -4.0

System.out.println(Math.floor(-4.7));
System.out.println(Math.round(-4.7));
System.out.println(Math.ceil(-4.7));
System.out.println(Math.Min(-4.7));
Ans : c.

18) Which of the following are valid statements

a) public class MyCalc extends Math
b) Math.max(s);
c) Math.round(9.99,1);
d) Math.mod(4,10);

e) None of the above.

Ans : e.

19) What will happen if you attempt to compile and run the following code?

Integer ten=new Integer(10);

Long nine=new Long (9);

System.out.println(ten + nine);

int i=1;

System.out.println(i + ten);

19 followed by 20
19 followed by 11
Error: Can't convert java lang Integer
d) 10 followed by 1

Ans : c.

Top


--------------------------------------------------------------------------------

Input/Output: Exploring Java.io
1) What is meant by Stream and what are the types of Streams and classes of the Streams?

Ans : A Stream is an abstraction that either produces or consumes information.

There are two types of Streams. They are:

Byte Streams : Byte Streams provide a convenient means for handling input and output of bytes.

Character Streams : Character Streams provide a convenient means for handling input and output of characters.

Byte Stream classes : Byte Streams are defined by using two abstract classes. They are:InputStream and OutputStream.

Character Stream classes : Character Streams are defined by using two abstract classes. They are : Reader and Writer.

2) Which of the following statements are true?

UTF characters are all 8-bits.
UTF characters are all 16-bits.
UTF characters are all 24-bits.
Unicode characters are all 16-bits.
Bytecode characters are all 16-bits.
Ans : d.

3) Which of the following statements are true?

When you construct an instance of File, if you do not use the filenaming semantics of the local machine, the constructor will throw an IOException.
When you construct an instance of File, if the corresponding file does not exist on the local file system, one will be created.
When an instance of File is garbage collected, the corresponding file on the local file system is deleted.
None of the above.
Ans : a,b and c.

4) The File class contains a method that changes the current working directory.

True
False
Ans : b.

5) It is possible to use the File class to list the contents of the current working directory.

True
False
Ans : a.

6) Readers have methods that can read and return floats and doubles.

True
False
Ans : b.

7) You execute the code below in an empty directory. What is the result?

File f1 = new File("dirname");

File f2 = new File(f1, "filename");

A new directory called dirname is created in the current working directory.
A new directory called dirname is created in the current working directory. A new file called filename is created in directory dirname.
A new directory called dirname and a new file called filename are created, both in the current working directory.
A new file called filename is created in the current working directory.
No directory is created, and no file is created.
Ans : e.

8) What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

Ans : The Reader/Writer class hierarchy is character-oriented and the InputStream/OutputStream class hierarchy is byte-oriented.

9) What is an I/O filter?

Ans : An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

10) What is the purpose of the File class?

Ans : The File class is used to create objects that provide access to the files and directories of a local file system.

11) What interface must an object implement before it can be written to a stream as an object?

Ans : An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.

12) What is the difference between the File and RandomAccessFile classes?

Ans : The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.

13) What class allows you to read objects directly from a stream?

Ans : The ObjectInputStream class supports the reading of objects from input streams.

14) What value does read( ) return when it has reached the end of a file?

Ans : The read( ) method returns – 1 when it has reached the end of a file.

15) What value does readLine( ) return when it has reached the end of a file?

Ans : The readLine( ) method returns null when it has reached the end of a file.

16) How many bits are used to represent Unicode, ASCII, UTF-16 and UTF-8 characters?

Ans : Unicode requires 16-bits and ASCII requires 8-bits. Although the ASCII character set uses only 1-bits, it is usually represented as 8-bits. UTF-8 represents characters using 8, 16 and 18-bit patterns. UTF-16 uses 16-bit and larger bit patterns.

17) Which of the following are true?

The InputStream and OutputStream classes are byte-oriented.
The ObjectInputStream and ObjectOutputStream do not support serialized object input and output.
The Reader and Writer classes are character-oriented.
The Reader and Writer classes are the preferred solution to serialized object output.
Ans : a and c.

18) Which of the following are true about I/O filters?

Filters are supported on input, but not on output.
Filters are supported by the InputStream/OutputStream class hierarchy, but not by the Reader/Writer class hierarchy.
Filters read from one stream and write to another.
A filter may alter data that is read from one stream and written to another.
Ans : c and d.

19) Which of the following are true?

Any Unicode character is represented using 16-bits.
7-bits are needed to represent any ASCII character.
UTF-8 characters are represented using only 8-bits.
UTF-16 characters are represented using only 16-bits.
Ans : a and b.

20) Which of the following are true?

The Serializable interface is used to identify objects that may be written to an output stream.
The Externalizable interface is implemented by classes that control the way in which their objects are serialized.
The Serializable interface extends the Externalizable interface.
The Externalizable interface extends the Serializable interface.
Ans : a, b and d.

21) Which of the following are true about the File class?

A File object can be used to change the current working directory.
A File object can be used to access the files in the current directory.
When a File object is created, a corresponding directory or file is created in the local file system.
File objects are used to access files and directories on the local file system.
File objects can be garbage collected.
When a File object is garbage collected, the corresponding file or directory is deleted.
Ans : b, d and e.

22) How do you create a Reader object from an InputStream object?

Use the static createReader( ) method of InputStream class.
Use the static createReader( ) method of Reader class.
Create an InputStreamReader object, passing the InputStream object as an argument to the InputStreamReader constructor.
Create an OutputStreamReader object, passing the InputStream object as an argument to the OutputStreamReader constructor.
Ans : c.

23) Which of the following are true?

Writer classes can be used to write characters to output streams using different character encodings.
Writer classes can be used to write Unicode characters to output streams.
Writer classes have methods that support the writing of the values of any Java primitive type to output streams.
Writer classes have methods that support the writing of objects to output streams.
Ans : a and b.

24) The isFile( ) method returns a boolean value depending on whether the file object is a file or a directory.

True.
False.
Ans : a.

25) Reading or writing can be done even after closing the input/output source.

True.
False.
Ans : b.

26) The ________ method helps in clearing the buffer.

Ans : flush( ).

27) The System.err method is used to print error message.

True.
False.
Ans : a.

28) What is meant by StreamTokenizer?

Ans : StreamTokenizer breaks up InputStream into tokens that are delimited by sets of characters.

It has the constructor : StreamTokenizer(Reader inStream).

Here inStream must be some form of Reader.

29) What is Serialization and deserialization?

Ans : Serialization is the process of writing the state of an object to a byte stream.

Deserialization is the process of restoring these objects.

30) Which of the following can you perform using the File class?

a) Change the current directory
b) Return the name of the parent directory
c) Delete a file
d) Find if a file contains text or binary information

Ans : b and c.

31) How can you change the current working directory using an instance of the File class called FileName?

FileName.chdir("DirName").
FileName.cd("DirName").
FileName.cwd("DirName").
The File class does not support directly changing the current directory.
Ans : d.

Top


--------------------------------------------------------------------------------

Applets
1) What is an Applet? Should applets have constructors?

Ans : Applet is a dynamic and interactive program that runs inside a Web page displayed by a Java capable browser. We don’t have the concept of Constructors in Applets.

2) How do we read number information from my applet’s parameters, given that Applet’s getParameter() method returns a string?

Ans : Use the parseInt() method in the Integer Class, the Float(String) constructor in the Class Float, or the Double(String) constructor in the class Double.

3) How can I arrange for different applets on a web page to communicate with each other?

Ans : Name your applets inside the Applet tag and invoke AppletContext’s getApplet() method in your applet code to obtain references to the other applets on the page.

4) How do I select a URL from my Applet and send the browser to that page?

Ans : Ask the applet for its applet context and invoke showDocument() on that context object.

Eg. URL targetURL;

String URLString

AppletContext context = getAppletContext();

try{

targetUR L = new URL(URLString);

} catch (Malformed URLException e){

// Code for recover from the exception

}

context. showDocument (targetURL);

5) Can applets on different pages communicate with each other?

Ans : No. Not Directly. The applets will exchange the information at one meeting place

either on the local file system or at remote system.

6) How do Applets differ from Applications?

Ans : Appln: Stand Alone

Applet: Needs no explicit installation on local m/c.

Appln: Execution starts with main() method.

Applet: Execution starts with init() method.

Appln: May or may not be a GUI

Applet: Must run within a GUI (Using AWT)

7) How do I determine the width and height of my application?

Ans : Use the getSize() method, which the Applet class inherits from the Component

class in the Java.awt package. The getSize() method returns the size of the applet as

a Dimension object, from which you extract separate width, height fields.

Eg. Dimension dim = getSize ();

int appletwidth = dim.width ();

8) What is AppletStub Interface?

Ans : The applet stub interface provides the means by which an applet and the browser communicate. Your code will not typically implement this interface.

9) It is essential to have both the .java file and the .html file of an applet in the same directory.

True.
False.
Ans : 2.

10) The tag contains two attributes namely _________ and _______.

Ans : Name , value.

11) Passing values to parameters is done in the _________ file of an applet.

Ans : .html.

12) What tags are mandatory when creating HTML to display an applet

name, height, width
code, name
codebase, height, width
code, height, width
Ans : 4.

13) Applet’s getParameter( ) method can be used to get parameter values.

True.
False.
Ans : a.

14) What are the Applet’s Life Cycle methods? Explain them?

Ans : init( ) method - Can be called when an applet is first loaded.

start( ) method - Can be called each time an applet is started.

paint( ) method - Can be called when the applet is minimized or refreshed.

stop( ) method - Can be called when the browser moves off the applet’s page.

destroy( ) method - Can be called when the browser is finished with the applet.

15) What are the Applet’s information methods?

Ans : getAppletInfo( ) method : Returns a string describing the applet, its author ,copy

right information, etc.

getParameterInfo( ) method : Returns an array of string describing the applet’s parameters.

16) All Applets are subclasses of Applet.

True.
False.
Ans : a.

17) All Applets must import java.applet and java.awt.

True.
False.
Ans : a.

18) What are the steps involved in Applet development?

Ans : a) Edit a Java source file,

b) Compile your program and

c) Execute the appletviewer, specifying the name of your applet’s source file.

19) Applets are executed by the console based Java run-time interpreter.

True.
False.
Ans : b.

20) Which classes and interfaces does Applet class consist?

Ans : Applet class consists of a single class, the Applet class and three interfaces: AppletContext,

AppletStub and AudioClip.

21) What is the sequence for calling the methods by AWT for applets?

Ans : When an applet begins, the AWT calls the following methods, in this sequence.

init( )
start( )
paint( )
22) When an applet is terminated, the following sequence of method cals takes place :

stop( )
destroy( )
23) Which method is used to output a string to an applet?

Ans : drawString ( ) method.

24) Every color is created from an RGB value.

True.
False
Ans : a.

Top


--------------------------------------------------------------------------------

Event Handling
1) The event delegation model, introduced in release 1.1 of the JDK, is fully compatible with the event model.

True
False
Ans : b.

2) A component subclass that has executed enableEvents( ) to enable processing of a certain kind of event cannot also use an adapter as a listener for the same kind of event.

True
False
Ans : b.

3) What is the highest-level event class of the event-delegation model?

Ans : The java.util.eventObject class is the highest-level class in the event-delegation hierarchy.

4) What interface is extended by AWT event listeners?

Ans : All AWT event listeners extend the java.util.EventListener interface.

5) What class is the top of the AWT event hierarchy?

Ans : The java.awt.AWTEvent class is the highest-level class in the AWT event class hierarchy.

6) What event results from the clicking of a button?

Ans : The ActionEvent event is generated as the result of the clicking of a button.

7) What is the relationship between an event-listener interface and an event-adapter class?

Ans : An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface.

8) In which package are most of the AWT events that support the event-delegation model defined?

Ans : Most of the AWT–related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package.

9) What is the advantage of the event-delegation model over the earlier event-inheritance model?

Ans : The event-delegation has two advantages over the event-inheritance model. They are :

It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component’s design and its use.
It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.
10) What is the purpose of the enableEvents( ) method?

Ans :The enableEvents( ) method is used to enable an event for a particular object.

11) Which of the following are true?

The event-inheritance model has replaced the event-delegation model.
The event-inheritance model is more efficient than the event-delegation model.
The event-delegation model uses event listeners to define the methods of event-handling classes.
The event-delegation model uses the handleEvent( ) method to support event handling.
Ans : c.

12) Which of the following is the highest class in the event-delegation model?

java.util.EventListener
java.util.EventObject
java.awt.AWTEvent
java.awt.event.AWTEvent
Ans : b.

13) When two or more objects are added as listeners for the same event, which listener is first invoked to handle the event?

The first object that was added as listener.
The last object that was added as listener.
There is no way to determine which listener will be invoked first.
It is impossible to have more than one listener for a given event.
Ans : c.

14) Which of the following components generate action events?

Buttons
Labels
Check boxes
Windows
Ans : a.

15) Which of the following are true?

A TextField object may generate an ActionEvent.
A TextArea object may generate an ActionEvent.
A Button object may generate an ActionEvent.
A MenuItem object may generate an ActionEvent.
Ans : a,c and d.

16) Which of the following are true?

The MouseListener interface defines methods for handling mouse clicks.
The MouseMotionListener interface defines methods for handling mouse clicks.
The MouseClickListener interface defines methods for handling mouse clicks.
The ActionListener interface defines methods for handling the clicking of a button.
Ans : a and d.

17) Suppose that you want to have an object eh handle the TextEvent of a TextArea object t. How should you add eh as the event handler for t?

t.addTextListener(eh);
eh.addTextListener(t);
addTextListener(eh.t);
addTextListener(t,eh);
Ans : a.

18) What is the preferred way to handle an object’s events in Java 2?

Override the object’s handleEvent( ) method.
Add one or more event listeners to handle the events.
Have the object override its processEvent( ) methods.
Have the object override its dispatchEvent( ) methods.
Ans : b.

19) Which of the following are true?

A component may handle its own events by adding itself as an event listener.
A component may handle its own events by overriding its event-dispatching method.
A component may not handle oits own events.
A component may handle its own events only if it implements the handleEvent( ) method.
Ans : a and b.

20) How many types of events are provided by AWT? Explain them?

Ans : The AWT provides two types of events. They are :

21) Low-level event : A low-level event is the one that represents a low-level input or window-system occurrence on a visual component on the screen.

22) Semantic event : Semantic event is defined at a higher-level to encapsulate the semantics of a user interface component’s model.

23) A __________ is an object that originates or "fire" events.

Ans : source.

24) The event listener corresponding to handling keyboard events is the _________ .

Ans : KeyListener.

25) What are the types of mouse event listeners?

Ans : MouseListener and MouseMotionListener.

26) Which of the following are correct event handling methods

a) mousePressed(MouseEvent e){}
b) MousePressed(MouseClick e){}
c) functionKey(KeyPress k){}
d) componentAdded(ContainerEvent e){}

Ans : a and d.

27) Which of the following are true?

a) A component may have only one event listener attached at a time
b) An event listener may be removed from a component
c) The ActionListener interface has no corresponding Adapter class
d) The processing of an event listener requires a try/catch block

Ans : b and c.

Top


--------------------------------------------------------------------------------

AWT : windows, graphics and fonts
1) How would you set the color of a graphics context called g to cyan?

g.setColor(Color.cyan);
g.setCurrentColor(cyan);
g.setColor("Color.cyan");
g.setColor("cyan’);
g.setColor(new Color(cyan));
Ans : a.

2) The code below draws a line. What color is the line?

g.setColor(Color.red.green.yellow.red.cyan);

g.drawLine(0, 0, 100,100);

Red
Green
Yellow
Cyan
Black
Ans : d.

3) What does the following code draw?

g.setColor(Color.black);

g.drawLine(10, 10, 10, 50);

g.setColor(Color.RED);

g.drawRect(100, 100, 150, 150);

A red vertical line that is 40 pixels long and a red square with sides of 150 pixels
A black vertical line that is 40 pixels long and a red square with sides of 150 pixels
A black vertical line that is 50 pixels long and a red square with sides of 150 pixels
A red vertical line that is 50 pixels long and a red square with sides of 150 pixels
A black vertical line that is 40 pixels long and a red square with sides of 100 pixel
Ans : b.

4) Which of the statements below are true?

a) A polyline is always filled.

b) A polyline can not be filled.

c) A polygon is always filled.

d) A polygon is always closed

e) A polygon may be filled or not filled

Ans : b, d and e.

5) What code would you use to construct a 24-point bold serif font?

new Font(Font.SERIF, 24,Font.BOLD);
new Font("SERIF", 24, BOLD");
new Font("BOLD ", 24,Font.SERIF);
new Font("SERIF", Font.BOLD,24);
new Font(Font.SERIF, "BOLD", 24);
Ans : 4.

6) What does the following paint( ) method draw?

Public void paint(Graphics g) {

g.drawString("question #6",10,0);

}

The string "question #6", with its top-left corner at 10,0
A little squiggle coming down from the top of the component, a little way in from the left edge
Ans : 2.

7) What does the following paint( ) method draw?

Public void paint(Graphics g) {

g.drawString("question #6",10,0);

}

A circle at (100, 100) with radius of 44
A circle at (100, 44) with radius of 100
A circle at (100, 44) with radius of 44
The code does not compile
Ans : 4.

8) What is relationship between the Canvas class and the Graphics class?

Ans : A Canvas object provides access to a Graphics object via its paint( ) method.

9) What are the Component subclasses that support painting.

Ans : The Canvas, Frame, Panel and Applet classes support painting.

10) What is the difference between the paint( ) and repaint( ) method?

Ans : The paint( ) method supports painting via a Graphics object. The repaint( ) method is used to cause paint( ) to be invoked by the AWT painting method.

11) What is the difference between the Font and FontMetrics classes?

Ans : The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

12) Which of the following are passed as an argument to the paint( ) method?

A Canvas object
A Graphics object
An Image object
A paint object
Ans : b.

13) Which of the following methods are invoked by the AWT to support paint and repaint operations?

paint( )
repaint( )
draw( )
redraw( )
Ans : a.

14) Which of the following classes have a paint( ) method?

Canvas
Image
Frame
Graphics
Ans : a and c.

15) Which of the following are methods of the Graphics class?

drawRect( )
drawImage( )
drawPoint( )
drawString( )
Ans : a, b and d.

java importent studying questions

) A class is a template for multiple objects with similar features.

a)True

b)False

Ans: a.

4) What is mean by garbage collection?

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.

5) 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.

6) What is calling method?

Ans: Calling methods are similar to calling or referring to an instance variable. These methods are accessed using dot notation.

Ex: obj.methodname(param1,param2)

7) Which method is used to determine the class of an object?

Ans: getClass( ) method can be used to find out what class the belongs to. This class is defined in the object class and is available to all objects.

8) All the classes in java.lang package are automatically imported when a program is compiled.

a)True

b)False

Ans: a.

9) How can class be imported to a program?

Ans: To import a class, the import keyword should be used as shown.;

import classname;

10) How can class be imported from a package to a program?

Ans: import java . packagename . classname (or) import java.package name.*;

11) What is a constructor?

Ans: A constructor is a special kind of method that determines how an object is initialized when created.

12) Which keyword is used to create an instance of a class?

Ans: new.

13) Which method is used to garbage collect an object?

Ans: finalize ().

14) Constructors can be overloaded like regular methods.

a)True

b)False

Ans: a.

15) What is casting?

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

16) Casting between primitive types allows conversion of one primitive type to another.

a)True

b)False

Ans: a.

17) Casting occurs commonly between numeric types.

a)True

b)False

Ans: a.

18) Boolean values can be cast into any other primitive type.

a)True

b)False

Ans: b.

19) Casting does not affect the original object or value.

a)True

b)False

Ans: a.

20) Which cast must be used to convert a larger value into a smaller one?

Ans: Explicit cast.

21) Which cast must be used to cast an object to another class?

Ans: Specific cast.

22) Which of the following features are common to both Java & C++?

A.The class declaration

b.The access modifiers

c.The encapsulation of data & methods with in objects

d.The use of pointers

Ans: a,b,c.

23) Which of the following statements accurately describe the use of access modifiers within a class definition?

a.They can be applied to both data & methods

b.They must precede a class's data variables or methods

c.They can follow a class's data variables or methods

d.They can appear in any order

e.They must be applied to data variables first and then to methods

Ans: a,b,d.

24) Suppose a given instance variable has been declared private. Can this instance variable be manipulated by methods out side its class?

a.yes

b.no

Ans: b.

25) Which of the following statements can be used to describe a public method?

a.It is accessible to all other classes in the hierarchy