oops & thread

Upload: manish-madhopuria

Post on 11-Jul-2015

122 views

Category:

Documents


0 download

TRANSCRIPT

OOPSWhat is Class? Class is the blue print of an object. What is Object? An object is an instance of a class. What is OOPS (Object-Oriented Programming System) or Principles of OOPS? OOP means Object Oriented Programming. This is a technique used to create programs as the real world entities. There are different Principles of OOPS Abstraction, Polymorphism, Inheritance and Encapsulation. Notes:- In OOP, the number of classes is not considered a problem What is Abstraction? An abstraction process of hiding the details and exposing the only essential feature of the object. In other words, it deals with the outside view of an object (interface). What are the types of Abstraction? Abstraction is of two types 1. Data Abstraction 2. Control Abstraction. What is data Abstraction? Through Data abstraction you can hide the member variable & only accessible through public methods. What is control Abstraction? Through control Abstraction you can hide the implementation of a particular method. When ever we are declaring any abstract method (in interface or abstract class) that is an example of control abstraction. Note:- if in an abstract class no method is abstract than also you can hide the member variables which is called data abstraction. Interfaces and abstract classes are example of Abstraction? Yes, it contains the abstract method whose implementation is not there. So it is hiding the implementation. So these are an example of Abstraction. Is declaring of private or other access specifiers in method is also a way of abstraction? Yes, because access specifiers limits the access of method or member variable. So its an example of abstraction or hiding. What is Polymorphism? Polymorphism is briefly described as "one method, many implementations". Polymorphism is implemented in Java in the form of multiple methods having the same name. There are two types of Polymorphism in java overloading and overriding (through inheritance & Java interface). What are the types of polymorphism? 1. Compile time polymorphism (Overloading) 2. Run time polymorphism (Overriding) What is overloading? Multiple methods have the same name, same or different return type and different formal parameters list in a class is call Overloading. Note: - same or different visibility, types and order of the argument are different. What is overriding? Multiple methods have the same name, same return type, and same formal argument list in supper and sub class is called Overriding. Note: - same or higher visibility and can throws same or subclass of exception with subclass. What is Inheritance?

Inheriting a part or all of the properties and behavior of an entity to another entity is called inheritance. You can also replace or modify inherited behavior. If you are implementing an interface it is also an example of inheritance. What are the benefits of inheritance? 1. Reusability 2. Extensibility What is Encapsulation? Encapsulation is a process of binding the data and member functions into a single unit. Data abstraction is a useful consequence (result) of the encapsulation principle. Encapsulation is not information hiding. What are the benefits and example of Encapsulate? Bu using encapsulation we can create out own custom types by reusing the existing or primitive types. Creating a class is an example of Encapsulate. What is the difference between abstraction and encapsulation? Abstraction is implemented with the help of encapsulation. Abstraction solves the problem in the design side while encapsulation is the implementation. What is Aggregation? It provides a 'has-a' relationship and the lifetime of the part is not managed by the whole. What is Composition? It provides a 'part-of' relationship and the lifetime of the part is managed by the whole. With the end of the whole that will be the end. What is the difference between inheritance, aggregation and composition? If inheritance gives us 'is-a' and composition gives us 'part-of', we could argue that aggregation gives us a 'has-a' relationship. What is the difference between aggregation and composition? Aggregation and composition are special kinds of associations. Aggregation is used to represent ownership or a whole/part relationship, and composition is used to represent an even stronger form of ownership.What is a constructor? A method in a class having the same name as class name and no return type. Note: - A constructor is executed when an object is instantiated from a class.

Modifiers other than an accessibility modifier are not permitted in the constructor header. It is possible to take initial parameters.What is a Default Constructor?

A default constructor is a constructor without any parameters.What is the difference between argument and parameter? Functions are declared with parameters where functions are called with arguments.

ThreadsWhat is a thread? A thread is an independent sequential path of execution within a program. Threads in a program exist in a common memory space and can therefore, share both data and code. What is difference between thread and process? Program in execution is called a process. A Process may contain more than one thread. A thread is a single sequence stream within the process. Threads share the address space of the process that created it; processes have their own address. Threads can directly communicate with other threads of its process; processes must use interpose communication to communicate with sibling processes. Thread is also called light weight process as its creation is easier than a process.What is a ThreadGroup? A ThreadGroup is used to represent a group of Threads. A tree structure can be formed from Threads Groups containing other ThreadGroups. Threads can only access the ThreadGroup to which they belong. This means that access to a ThreadGroups parent or other ThreadGroup is not permitted.

What is thread pool? A thread pool is a collection of threads, which you keep "alive" and use/reuse to process incoming "tasks". When a new task arrives you try to find a thread from the collection, which is idle, and handle the task to it. If no such thread exists you either wait for one to become available or add a new thread to the pool. After the thread has finished processing the task, it is not terminated, only marked as idle and ready to be reused for another task. Advantages 1) By reusing threads you save the thread creation/destruction overhead. 2) You have control over the maximum number of tasks that are being processed in parallel. How to create a thread pool? Create an object of java.util.concurrent.ThreadPoolExecutor, assign the task by calling execute method and finishes with shutdown method. How does the race condition occur? It occurs when two or more processes are reading or writing some shared data and the final result depends on who runs precisely when. What is multiprogramming? Multiprogramming is the technique of running several processes at a time using timesharing. What is multitasking? Multitasking is the logical extension of multiprogramming, where multiple tasks can be run simultaneously. What is multithreading? Run multiple threads (similar type of task) at the same time. What is a multithread application? A multithreaded application has the power to run many threads concurrently within a single program. What is context switching? Switching from one process/Thread to another is called context switch.What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. What's the difference between Thread and Runnable types?

-

-

Thread is a class and Runnable is an interface. Thread class also implements the runnable interface. Extending a thread class you are extending all the methods of thread class which may lead to accidental overriding where as implementing the Runnable interface will only give you option of implementing run method. Extending the Thread class will make your class unable to extend other classes. You can pass a single object of runnable to multiple threads. This is not possible by extending Thread class. In Object oriented aspect we extend a class when we want to make it different from its super class but we are not doing this here.

What is Synchronization? If several threads try to modifying the shared resources simultaneously it may be corrupted. To avoid this condition synchronize key word is used. method: - the lock is obtained on the object on which the method was invoked. blocks: - the lock is obtained on any arbitrary object (non-null reference value) which is specified as argument. Static synchronized method: - the lock is obtained on the Class not on instance. Static synchronized blocks: - the lock is obtained on the Class which is specified as argument. // How can you synchronize a static and non static method? By using synchronize blocks. In that you have to create a static object because it can be accessible in a static method. Take a lock on that object in both static and non static block. Or you can do it by declaring a synchronized block with class lock in the non static method.Synchronized Synchronized What are the different states of a Thread? NEW A Fresh thread that has not yet started to execute. RUNNABLE A thread that is executing in the Java virtual machine. BLOCKED A thread that is blocked waiting for a monitor lock. WAITING A thread that is waiting to be notified by another thread. TIMED_WAITING A thread that is waiting to be notified by another thread for a specific amount of time. TERMINATED A thread whos run method has ended.

What is Thread Priorities? Every thread has its own priority. The minimum priority is 1 and maximum is 10 and the default priority assigned is 5. Higher priority thread executes first. The priority of the thread can set any time by calling setPriority method.

How to stop a thread safely? the best way to stop a request is to end the run method.

What the sleep method does? The static Thread.Sleep(long) method maintains control of thread execution but delays the next action until the sleep time expires. What the yield method does?

This method will cause the current thread in the Running state to transit to the Ready-to-run state, thus relies the CPU. Its a static method. What the activeCount () method does? Returns the number of active threads in the current thread's thread group. Its a static method.What the jion method does?

A thread waits for the other thread to complete its execution before continuing. When a thread terminate?

As soon as the run method returns returns. What is deadlock? A deadlock is a situation where a thread is waiting for an object lock that another thread holds, and this second thread is waiting for an object lock that the first thread holds. Since each thread is waiting for the other thread to relinquish a lock, they both remain waiting forever in the Blocked-for-lock-acquisition state. The threads are said to be deadlocked.What the currentThread method does? This method returns a reference to the thread object of the currently executing thread.

Its a

static method.

What the Run method does? Thread execution starts from run method. What the start method does?

This method spawns the thread from dormant state to ready to run state.Can I implement my own start() method? The Thread start () method is not marked final, but should not be overridden. Do I need to use synchronized on setValue(int)? It depends whether multiple threads are working on single object then yes. If working on distinct objects then no. How threads work? We start a thread by calling start method. It start execution from run() method and ends with the end of run() method. What the wait methods does? The wait method of an object can be called when the thread is holding the lock on that object otherwise; the call will result in an IllegalMonitorStateException. When wait ()

method is called on the object the lock will be released and it leaves the Running state and transits to the Waiting-for-notification state. Its a final method.What the notify method does? Invoking the notify() method on an

object wakes up a single thread that is waiting on the lock of this object. On being notified, a waiting thread first transits to the Blocked-for-lockacquisition state to acquire the lock on the object, and not directly to the Ready-to-run state. Its a final method.What the Interrupt method does? If the thread is blocked for any reason and the thread Interrupts then InterruptedException is thrown and Interrupt flag is set to true. Else only the interrupt flag is set to true.

interrupted and is isInterrupted method? Interrupted is a static method where as isInterrupted is an instance method. If the Interrupt flag is set to true the call of interrupted method return true as isInterrupted method and reset the flag to false which is not done by isInterrupted. What the isAlive method does? Tests if this thread is alive or active. A thread is alive if it has been started and has not yet died.Difference between How inter Thread communication is achieved in java? inter Thread communication is declared in java.lang.Object Class. Each object is associated with monitor. The method are used are wait, notify and notifyAll. Where wait(), notify() and notifyall() methods defined? In the Object class. Why are wait(), notify() and notifyall() methods defined in the Object class? As they are implemented in thread programming but for all subclasses of Objects. What is the different between notify() and notifyall()? The notify() method wakes up a single thread that is waiting on this object's monitor and The notifyall() method wakes up all threads that are waiting on this object's monitor Garbage collector thread belongs to which priority?

Those are low priority threads or demon threads. What is daemon thread? When JVM finds no user threads it stops and all daemon thread terminate instantly. It is created by calling setDaemon (Boolean on) on thread before the thread stated.

Which method in the object class is a overloaded method? Wait(). Which method in the Thread class is a overloaded method? Join(). How to avid dead lock? when evere you are calling syncronise methods interdependingly than thare is a chance of dead lock if there is two entry point for two methods to enter into these method. So you should avoid this situation to avoid the deadlock.

SocketsName the seven layers of the OSI Model and describe them briefly? Physical Layer - covers the physical interface between devices and the rules by which bits are passed from one to another. Data Link Layer - attempts to make the physical link reliable and provides the means to activate, maintain, and deactivate the link. Network Layer - provides for the transfer of information between end systems across some sort communications network. Transport Layer - provides a mechanism for the exchange of data between end system. Session Layer - provides the mechanism for controlling the dialogue between applications in end systems. Presentation Layer - defines the format of the data to be exchanged between applications and offers application programs a set of data transformation services. Application Layer - provides a means for application programs to access the OSI environment. (pyare dost naveen teri sadi par ayenge) Name the fore layers of the tcp / ip Model and describe them briefly? Application- Defines TCP/IP application protocols and how host programs interface with transport layer services to use the network. Ex. DNS, FTP, HTTP, IMAP, POP3, SMTP, SNMP, SSH, TELNETTransport- Provides communication session management between host computers. Defines the level of service and status of the connection used when transporting data. Ex. TCP, UDP.

Internet- Packages data into IP data grams, which contain source and destination address information that is used to forward the data grams between hosts and across networks. Performs routing of IP data grams. Ex. IP (IPv4, IPv6), ARP and RARP. Network Interface -Specifies details of how data is physically sent through the network, including how bits are electrically signaled by hardware devices that interface directly with a network medium, such as coaxial cable, optical fiber, or twisted-pair copper wire. Ex. Ethernet. What is arp (address resolution protocol)? ARP is primarily used to translate IP addresses to Ethernet MAC addresses. What is rarp (Reverse Address Resolution Protocol)? Rarp is used to obtain an IP address for a given hardware address. What is gateway? A gateway is a network point that acts as an entrance to another network. What is hub/Switch? A hub is used in a wired network to connect Ethernet cables from a number of devices together. What is NAT (Network Address Translation)? An Internet standard that enables a local-area network (LAN) to use one set of IP addresses for internal traffic and a second set of addresses for external traffic. A NAT box located where the LAN meets the Internet makes all necessary IP address translations. What is SSH (Secure Shell)? Secure Shell is a program to log into another computer over a network, to execute commands in a remote machine, and to move files from one machine to another. It provides strong authentication and secure communications over insecure channels. Some SSH client are SSHSecureShellClient, Putty. What is SNMP? Simple Network Management Protocol (SNMP) is a popular protocol for network management to communicate with network elements. What is TELNET?

The Telnet program runs on your computer and connects your PC to a server on the network with tcp/ip protocal. What is SMTP(Simple Mail Transfer Protocol)? SMTP a protocol for sending e-mail messages between servers. What is POP3 (Post Office Protocol) and IMAP4 (Internet Message Access Protocol)? E-mail client use these protocols to retrieve e-mail from a mail server. What is DNS? The domain name system (DNS) resolves the domain name to IP addresses. What are the types of record in DNS? A:- returns a 32-bit IPv4 address, used for web. MX:- mail exchange record. SPF:- Specified as part of the SPF protocol, as an alternative to storing SPF data in TXT records. TXT:- originally intended to carry arbitrary human-readable text in a DNS record. Since the early 1990s, however, this record is more often used to carry machine-readable data such as specified by SPF. PTR:- host name to IP. Reverse DNS lookups. What is the difference between TCP and UDP? TCP and UDP are both transport-level protocols. TCP is designed to provide reliable communication across a variety of reliable and unreliable networks and internets. It the connection oriented protocol. UDP provides a connectionless service for application-level procedures. Thus, UDP is basically an unreliable service; delivery and duplicate protection are not guaranteed. Its the connectionless protocol. What is an IP address? Your IP address is your computer's unique address on the Internet; it consists of four numeric segments separated by periods (e.g., 64.236.16.116). (System address) What is the difference between TCP/IP and IP protocol? The difference is that TCP is responsible for the data delivery of a packet and IP is responsible for the logical addressing. In other words, IP obtains the address and TCP guarantees delivery of data to that address. What is mac address? Short for Media Access Control address, a hardware address that uniquely identifies each node of a network. (machine address) Note:- multiple ip address is possible for one mac address. What is a port? A port is a way for computers to communicate over a network. A IP is having total 65536 ports. What does a socket consists of? The combination of an IP address and a port number is called a socket. What are some advantages and disadvantages of Java Sockets? Advantages of Java Sockets: Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information. Disadvantages of Java Sockets: Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network

Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way. Since the data formats and protocols remain application specific, the re-use of socket based implementations is limited. What is the difference between a NULL pointer and a void pointer? A NULL pointer is a pointer of any type whose value is zero. A void pointer is a pointer to an object of an unknown type, and is guaranteed to have enough bits to hold a pointer to any object. A void pointer is not guaranteed to have enough bits to point to a function (though in general practice it does). What is encapsulation technique? Hiding data within the class and making it available only through the methods. This technique is used to protect your class against accidental changes to fields, which might leave the class in an inconsistent state. How to create a tcp socket? We can create socket by creating the instance of socket class Ex. CurrentSocket = new Socket("10.11.13.87",25); Socket(String host, int port, InetAddress localAddr, int localPort) How to get local address and port of socket? getLocalAddress()//Gets the local address to which the socket is bound. getLocalPort()//Returns the local port to which this socket is bound. How to get the local host and port of ServerSocket object? getInetAddress()//Returns the local address of this server socket. getLocalPort()//Returns the port on which this socket is listening. How to get remote address and port of socket? getInetAddress()//Returns the address to which the socket is connected. getPort()//Returns the remote port to which this socket is connected. How to get channels from the socket? getInputStream()//Returns an input stream for this socket. getOutputStream()Returns an output stream for this socket. How to close Input and OutPut Stream? shutdownInput()//shutdown the input stream. If you read from a socket input stream after invoking shutdownInput() on the socket, the stream will return EOF. shutdownOutput()// shutdown the output Stream. If you write to a socket output stream after invoking shutdownOutput() on the socket, the stream will throw an IOException. What is InetAddress? This class represents an Internet Protocol (IP) address. getHostAddress()//Returns the IP address string in textual presentation. getAddress()//Returns the raw IP address of this InetAddress object return byte[]. getHostName()//Gets the host name for this IP address. How to get the localhost? getLocalHost() // Static method return InetAddress. How to close the socket? close()//Closing this socket will also close the socket's InputStream and OutputStream. What are the socket verifying function? isClosed()//Returns the closed state of the socket. isInputShutdown()//Returns whether the read-half of the socket connection is closed. isOutputShutdown()//Returns whether the write-half of the socket connection is closed. How to create a UDP socket? We can create udp socket by creating the instance of DatagramSocket class

Ex. ds = new DatagramSocket(); ds.connect(host, port); What is DatagramPacket class used? Datagram packets are used to implement a connectionless packet delivery service. Each message is routed from one machine to based solely on information contained within that packet How to send from the UDP socket? DatagramPacket outgoing = new DatagramPacket(new byte[1], length, host, port); send(outgoing) // Sends a datagram packet from this socket. How to receive from the UDP socket? DatagramPacket incoming = new DatagramPacket(new byte[bufferSize], bufferSize); receive(incoming) //Receives a datagram packet from this socket. Sytem.out.println(incoming.getData()); What is a ServerSocket class does? This class implements server sockets. A server socket waits for requests to come in over the network. As the request comes it returns a socket with the established connection. How to create a ServerSocket object? Ss = new ServerSocket(int port, int Que, InetAddress bindAddr) How to create an object of InetAddress? InetAddress duke = InetAddress.getByName("128.238.2.92"); How to start listening for request by ServerSocket object? ss. accept()//Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made. How to close the ServerSocket? ss.close(). Name some classes of java.net package? Inet4Address Inet6Address InetAddress ServerSocket Socket URI URL DatagramPacket DatagramSocket What is a URL class? Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine. Ex. URL url = new URL("http://hostname:80/index.html"); url.openStream()// getting inputStream. How to set parameater in URL? URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); Difference between Unicast & Multicast model? A unicast packet is the complete opposite: one machine is talking to only one other machine. While multicast packet is from one machine to one or more.

What is a proxy server? A server that sits between a client application, such as a Web browser, and a real server. It intercepts all requests to the real server to see if it can fulfill the requests itself. If not, it forwards the request to the real server. Write the range of multicast socket IP address? This reserved range consists of addresses from 224.0.0.0 to 239.255.255.255. However, the multicast addresses from 224.0.0.0 to 224.0.0.255 are reserved for multicast routing information; Application programs should use multicast addresses outside this range.

Package interface & abstract classWhat is the default modifier of an interface? The default modifier for method is abstract, public and for variable it is public, static and final. What are Abstract methods? What are packages? A package in Java is an encapsulation mechanism that can be used to group related classes, interfaces, and sub packages. If you omit the package, the classes are put into the default package. What is a default package? Java.lang package is imported by default even without a package declaration How to define an Interface? Answer: In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.What is abstract class?

Abstract classes are classes that contain zero or more abstract methods. An abstract method is a method that is declared, but not implementation. Abstract classes cannot be instantiated and sometimes we do not want the class to be instantiated than also we declare a concrete class as

abstract.What is similarities/difference between an Abstract class and Interface? Answer: Differences are as follows: Interfaces provide a form of multiple inheritance. A class can extend only one other class. Interfaces are limited to public members and constants with no implementation of method. Abstract classes can have a partial implementation, all visibility type of member, static methods, etc. A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class. Interfaces enable you to provide your very own functionality for each and every method accordingly. Where as an abstract class is a class which has certain non-implemented methods apart from some implemented methods. Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. Abstract classes are fast. Similarities: Neither Abstract classes or Interface can be instantiated. What is Abstract modifier? Abstract Class: Can not to be instantiated, but extended by other classes. Abstract Method: A method does not have an implementation Which is better to use interface or abstract class? This is implementation dependent. After that abstract class has some what one step ahead. But if multiple inheritance is required then either both interface or abstract class will solve the propose or only interface. But interface has its own disadvantages we cant declare instance variables nor can we provide the default implementation. Also Interfaces are slow as it requires extra indirection so Abstract classes are faster.

Exception HandlingWhat is an exception? An exception in Java is a signal that indicates the occurrence of some important or unexpected condition during execution. What is a Throwable class? It is the top label class of Exception Inheritance Hierarchy. It has two main subclasses Exception and Error. What is Exception class? The class Exception represents exceptions that a program would want to be made aware of during execution. What is Error class? These are invariably never explicitly caught and are usually irrecoverable. What is RuntimeException exception? As these runtime exceptions are usually caused by program bugs that should not occur in the first place, it is more appropriate to treat them as faults in the program design, rather than merely catching t during program exehemcution. What is checked exceptions? Except for RuntimeException, Error, and their subclasses, all exceptions are called checked exceptions. What is an unchecked exception? Exceptions defined by Error and RuntimeException classes and their subclasses are known as unchecked exceptions, meaning that a method is not obliged to deal with these kinds of exceptions. What is the Exception Handling mechanism in java? The mechanism for handling execeptions is embedded in the try-catch-finally construct. What is try block? The try block is a context that which is handled for encountering an exception. What is catch block? If try block raises an exception then only the control is transfer to catch block. The catch block that is having the appropriate parameter that catches the exception. The code of the first such catch block is executed and all other catch blocks are ignored. What is the arrangement structure of catch block? The catch block is arranged in terms of there exception argument. Lower exceptions in higher position. What is finally block? If the try block is executed, then the finally block is guaranteed to be executed, regardless of exception has risen or not. it can be used to specify any clean-up code. What is the need finally block as garbage collector is doing the clean up? The garbage collector is cleaning up the java resources. But the program may also holding the non java resources such as, files, net connections. The finally block is used to clean up that code. What are the different exception types? Exceptions are of two type checked and unchecked exceptions. What is user defined exception? We can also be able to create our own exception class. Inherit the exception class whose sub class you want to create. What will happen to the Exception object after exception handling? Exception object will be garbage collected. What are chained exceptions?

If you catch an exception, then decide to rethrow a new one to be caught at a higher level, the information in the lower level exeception is lost unless you print it out right there. Instead, starting with Java 1.4 you can pass the old exception as a parameter to the constructor of the new exception, thus combining the information from both the old and new exeception. What happen if the catch block throws an exaction and the next catch block is declared with that type of exception? That exception will raise not handled as the catch block only handles the exception generated in try block. What are the ways you can handle exception? Using try--catchfinally or by using throws. Can any exception raised from finally block? Yes, but if any exception is thrown from try and finally block then the try block exception is suppressed. What happen if finally block has a control transfer statement like a return or labeledbreak?

If any exception is thrown from try block then it is suppressed and execution continues. What is the use of throw exception? When the exception has not generated automatically but we want to generate an exception then we use the throw key word to generate it or it can also be used to re thrown an exception. What is the use of throws exception? If the exception is raised in a method but we do not want to handle it than we throws that exception so that it can propagate to the caller method. Can we throw multiple exceptions in Throws claws? Yes, by separating with commas. The statements following the throw keyword in a program are not executed. True / False? True. How does finally block differ from finalize() method? Finally block will be executed whether or not an exception is thrown. So it is used to free resources. finalize() is a protected method in the Object class which is called by the JVM just an object is garbage collected before. What are the constraints imposed by overriding on exception handling? An overriding method in a subclass May only throw exceptions declared in the parent class or children of the exceptions declared in the parent class. What will happen to the finally block if exit() is called in the try block? Finally block will not execute. exit() transfers the control to OS.

ReferenceWhy java.lang.ref is used? Provides reference-object classes, which support a limited degree of interaction with the garbage collector. What is Strong Reference? An ordinary reference. Keeps objects alive as long as they are referenced. It a normal reference. It is garbage collected when no reference is pointed to the object. What is Soft Reference? Keeps objects alive provided theres enough memory. It is used to keep objects alive even after clients have removed their references, in case clients start asking for them again by key. It is good for creating memory-sensitive caches. It is garbage collected when JVM decides it still needs to reclaim more space. The class that implements it is java.lang.ref.SoftReference. Owner of the object would like to keep target object in memory, but is system is lacking free memory owner will be able to deal with a loos of target What is Weak Reference? Keeps objects alive only while theyre in use (reachable) by clients. It is garbage collected in the next GC cycle. Containers that automatically delete objects no longer in use. implementing classes are java.lang.ref.WeakReference, java.util.WeakHashMap. automatically delete objects no longer in use. Why Weak Reference is used? Don't own target, need access so long as target exists .I am not owner of the target (don't contain or control it) but so long as target exists I need to access it. Also can be used for very short term caching. What is Phantom Reference? Lets you clean up after finalization but before the space is reclaimed (replaces or augments the use of finalize()). Its used in Special clean up processing. Class that implements java.lang.ref.PhantomReference. The get method in this reference always returns null. So that you cannot be able to get the object back. If Phantom Reference holds the object that is the GC called the finalize method but cannot be able to clean the object so the memory is occupied not going back to free memory. Here you can do any other clean up that you want. than call clean method to let the GC to collect occupied memory to free memory pool. Need to do stuff when target is destroyed .When target is destroyed I need to perform some processing, such as cleanup external resources (OS handles). Phantom reference must contain additional attributes associated with the target (such as OS handles). How can you make GC to an object which is reference by a Phantom Reference? You must call its clear() method or allow the PhantomReference object itself to be garbagecollected What is the difference between using finalize() method or Phantom Reference in cleanup process? When the finalize() method is called, that means the object is in the process of being garbage collected. So if it contains references to other objects, that is imminently going to be irrelevant. Setting those references to null is pointless. I'd recommend using a PhantomReference instead.

It's more controllable. You control what thread it's cleaned up on, you can pass references in a way that's dangerous in a finalize and you can discard it if (as should happen) the program explicitly closes its connection with the resource. What they get method of Soft, Weak and Phantom Reference will returned? The get method in Soft, Weak Reference will return the object if it is not GC else it will return null. But in case of Phantom Reference if it is GC or not it will return null only. What is a WeakHashMap? What is its use and when should you use it? A WeakHashMap is a special Map implementation where the keys of the map are stored in a java.lang.ref.WeakReference. By storing the keys in a weak reference, key-value pairs can dynamically be dropped from the map when the only reference to the key is from the weak reference. This makes the WeakHashMap an excellent implementation for a weakly referenced list, where entries that aren't used elsewhere may be dropped with no side effects. Also, just because a key may be dropped, doesn't mean it will immediately be dropped. If the system has sufficient resources, the weak key reference that isn't externally referenced could stay around for a long time. In WeakHashMap only the key is Weak Reference but the value is a Strong Referenced.

Garbage collectionExplain Garbage collection in Java? Garbage Collection is automatic process of freeing the memory by removes the unreferenced objects. What is the priority of GC thread? Garbage Collector Thread runs as a low priority daemon thread. When does the Garbage Collection happen? When there is not enough memory or when the daemon GC thread gets a chance to run. When is an Object eligible for Garbage collection? An Object is eligible for GC, when there are no references to the object. What are two steps in Garbage Collection? 1. Detection of garbage collectible objects and marking them for garbage collection. 2. Freeing the memory of objects marked for GC. What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform any non java resource cleanup before the object is garbage collected. Can GC be forced in Java? No. GC can't be forced. What does System.gc() and Runtime.gc() methods do? These methods inform the JVM to run GC but this is only a request to the JVM but it is up to the JVM to run GC immediately or run it when it gets time. When is the finalize() called? finalize() method is called by the GC just before releasing the object's memory. It is normally advised to release resources held by the object in finalize() method. Can an object be resurrected after it is marked for garbage collection? Yes. It can be done in finalize() method of the object but it is not advisable to do so. Will the finalize() method run on the resurrected object? No. finalize() method will run only once for an object. The resurrected object's will not be cleared till the JVM cease to exist. GC is single threaded or multi threaded? Garbage Collection is multi threaded from JDK1.3 onwards. What are the good programming practices for better memory management? a. We shouldn't declare unwanted variables and objects. b. We should avoid declaring variables or instantiating objects inside loops. c. When an object is not required, its reference should be nullified. d. We should minimize the usage of String object and SOP's. When is the Exception object in the Exception block eligible for GC? Immediately after Exception block is executed. When are the local variables eligible for GC? Immediately after method's execution is completed. If an object reference is set to null, Will GC immediately free the memory held by that object? No. It will be garbage collected only in the next GC cycle. What happen is finalize() method raises exception? The finalization method stops execution and ignore the exception.

StringWhat is the difference between StringBuilder and StringBuffer class? The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. What is the ensureCapacity method of StringBuilder and StringBuffer class do? Ensures that the capacity is at least equal to the specified minimum. If the current capacity is less than the argument, then a new internal array is allocated with greater capacity. The new capacity is the larger of: The minimumCapacity argument and Twice the old capacity, plus 2. Are String object Immutable, Can you explain the concept? JVM internally maintains the "String Pool". To achive the memory efficiency, JVM will refer the String object from pool. It will not create the new String objects. So, whenevr you create a new string literal, JVM will check in the pool whether it already exists or not. If already present in the pool, just give the reference to the same object or create the new object in the pool. There will be many references point to the same String objects, if someone changes the value, it will affect all the references. So, sun decided to make it immutable. What is the difference String and new String()? String literal will first check in String pool, that is any String exists with the value "Hello", if so then its directly points to same object, if not, then only it will create new object, but in case of new String() It always creates new object, and assign it to value "Hello". What the intern() method in String class return? It returns a canonical representation for the string object from String constant pool. Can you extend the String, StringBuffer or StringBuilder class? No. It cannot be extended. The classes are final. What is the importance of == and equals() method with respect to String object? == is used to check whether the references are of the same object. equals() is used to check whether the contents of the objects are the same. Is String a Wrapper Class or not? No. String is not a Wrapper class. How will you find length of a String object? Using length() method of String class. What will trim() method of String class do? trim() eliminate spaces from both the ends of a string. What is the possible runtime exception thrown by substring() method? StringIndexOutOfBoundsException. What is the difference between String and Stringbuffer? Object's of String class is immutable and object's of Stringbuffer class is mutable moreover stringbuffer is faster in concatenation. How can you find the length and capacity of a StringBuffer? For the length length() method and for capacity capacity() method is used. String index position start with 1 or 0? String index starts with 0. How the substring(int, int) method of String class Works? Its creates a new String from existing string. Note:- The first index of from the String is included and the second index is excluded. How the indexOf(String) method of String class Works? Returns the index within this string of the first occurrence of the specified substring. What are the interfaces are defined in java.lang class? Appendable, Cloneable, Comparable, Iterable, Runnable. How can you compare String and StringBuffer? By contentEquals (StringBuffer) method of String.

String tokenizer 1. 2. 3.StringTokenizer st1 = new StringTokenizer("Java|StringTokenizer| Example 1", "|");

st1.hasMoreTokens() st1.nextToken();

MathWhat is the use of Math class? Math class provide methods for mathametical functions. Can you instantiate Math class? No. It cannot be instantiated. The class is final and its constructor is private. But all the methods are static, so we can use them without instantiating the Math class. What will Math.abs() do? It simply returns the absolute value of the value supplied to the method, i.e. gives you the same value. If you supply negative value it simply removes the sign. What will Math.ceil() do? This method returns always double. It returns next available whole number. What will Math.floor() do? This method returns always double, It returns the smallest next available whole number. What will Math.max() do? The max() method returns greater value out of the supplied values. What will Math.min() do? The min() method returns smaller value out of the supplied values. What will Math.random() do? The random() method returns random number between 0.0 and 1.0. It always returns double. What will Math.round () do? If positive value is than less than 0.5 comes to 0.0 else 1.0. If negative value is than less than equal to -0.5 comes to -0.0 else -1.0. int Value 127 it return true in == condition

Java FundamentalsWhat is primitive datatype? Primitive data values are not objects. Each primitive data type defines the range of values in the data type. What is the most important feature of Java? Java is a platform independent language. What do you mean by platform independence? Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc). What is JVM (Java Virtual Machine)? JVM (Java Virtual Machine): A Java runtime environment, required for the running of Java class files, which includes a Java interpreter. A different JVM is required for each unique operating system (Linux, OS/2, Windows 98, etc.), but any JVM can run the same version of a Java class file. Is JVMs platform independent? JVM's are not platform independent. JVM's are platform specific run time implementation provided by the vendor. What is the difference between a JDK and a JVM? JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM. What is JIT (Just-in-Time) Compilation? In the Java programming language and environment, a just-in-time (JIT) compiler is a program that turns Java bytecode (a program that contains instructions that must be interpreted) into instructions that can be sent directly to the processor. Using the Java just-in-time compiler (really a second compiler) at the particular system platform compiles the bytecode into the particular system code (as though the program had been compiled initially on that platform). What is a pointer and does Java support pointers? Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn't support the usage of pointers. Difference between path and class path? PATH is nothing but setting up an environment for operating system. Operating System will look in this PATH for executables. Classpath is nothing but setting up the environment for Java. Java will use to find compiled classes (i.e. .class files). What is JAVA doc utility? The javadoc utility lets you put your comments right next to your code, inside your ".java" source files. When you're satisfied with your code and comments, you simply run the javadoc command, and your HTML-style documentation is automatically created for you. Name some java doc tags? @author, @deprecated, @exception, @param, @return, @see, @throws, @version What are JAVA doc doclets? Doclets are programs written in the JavaTM programming language that use the doclet API to specify the content and format of the output of the Javadoc tool. By default, the Javadoc tool uses the "standard" doclet provided by SunTM to generate API documentation in HTML form. However, you can supply your own doclets to customize the output of Javadoc as you like. You can write the doclets from scratch using the doclet API, or you can start with the standard doclet and modify it to suit your needs. What is jconsole utility? The jconsoletool is a JMX-compliant graphical tool for monitoring a Java virtual machine. The jconsoletool can monitor both local and remote JVMs.

The jconsoletool can monitor and manage an application. What is native2ascii utility? You can use the native2ascii tool to convert files with native encoded characters to a file with Unicode encoded characters. what is javap utility? The javap command displays information about the methods, variables, and parameters present in a class file. The output of the javap tool depends on the options used. If you do not specify any options while using the jap tool, the javap tool prints the package, protected, and public fields and methods of the classes passed to the tool. What is marker interface and its example? Interfaces with empty bodies are often used as markers to tag classes as having a certain property or behavior are called marker interface. Examples of such marker interfaces: java.lang.Cloneable, java.io.Serializable, java.util.EventListener. What are pass by reference and passby value?Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 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. What is Reflection API in Java? Provides classes and interfaces for obtaining reflective information about classes and objects. Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes. Classes in this package, along with java.lang.Class class accommodate the task. Does Java support multiple inheritance? Java use multiple inheritance help of interface without interface java does not support multiple inheritance. Is Java a pure object oriented language? Java uses primitive data types and Static modifier. Hence is not a pure object oriented language. Are arrays primitive data types? In Java, Arrays are objects. How to declare an Array? int myArray = new int[100]; Can a main method be overloaded? Yes. You can have any number of main methods with different method signature and implementation in the class. Can we override static method? We can not override static method. Can a main method be declared final? Yes. Any inheriting class will not be able to have it's own default main method. Which object system.in and system.out system.err are? system.out :- PrintStream system.err :- PrintStream system.in :- Inputstream What else you can use for printing in console? you can use java.io.Console console.writer :- PrintStream console.reader :- Reader

What is the benefit of Console class? Which non-Unicode letter characters may be used as the first character of an identifier? The non-Unicode letter characters $ and _ may appear as the first character of an identifier What is Downcasting ? Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy What are order of precedence and associativity, and how are they used? Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left What are the legal operands of the instanceof operator? The left operand is an object reference or null value and the right operand is a class, interface, or array type. What is numeric promotion? Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required To what value is a variable of the boolean type automatically initialized? The default value of the boolean type is false What is the difference between an if statement and a switch statement? The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed. What are the practical benefits, if any, of importing a specific class rather than an entire package (e.g. import java.net.* versus import java.net.Socket)? It makes no difference in the generated class files since only the classes that are actually used are referenced by the generated class file. There is another practical benefit to importing single classes, and this arises when two (or more) packages have classes with the same name. Take java.util.Timer and javax.swing.Timer, for example. If I import java.util.* and javax.swing.* and then try to use "Timer", I get an error while compiling (the class name is ambiguous between both packages). Let's say what you really wanted was the javax.swing.Timer class, and the only classes you plan on using in java.util are Collection and HashMap. In this case, some people will prefer to import java.util.Collection and import java.util.HashMap instead of importing java.util.*. This will now allow them to use Timer, Collection, HashMap, and other javax.swing classes without using fully qualified class names in. How many static init can you have ? As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope. What is constructor chaining and how is it achieved in Java ? A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In Java it is done via an implicit call to the no-args constructor as the first statement. Which Java operator is right associative? The = operator is right associative. 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 is the difference between the >> and >>> operators? The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out. What is static modifier? Static :- Static members belong to the class in which they are declared, and are not part of any instance of the class. What is static variable? Static Variable: All instances share the same copy of the variable. A static variable can be accessed directly with the class or with a instance. Static variables are initialized to their default values if no explicit initialization expression is specified What is static Method? Static Method: We do not need to create an object to call our static method. Simply using the class name will suffice. It can directly access other static members in the class but cannot access instance members of the class. What is static Block? Static Block: Static block is executed position wise in the program and can access only the static members. What is final Class? That class cannot be inherited. What is final Method? Final Method: That method cannot be overridden by a subclass. What is final Variable? Final Variable: Its value cannot be changed once it has been initialized. This applies to instance, static and local variables, including parameters that are declared final. A final variable need not be initialized at its declaration, but it must be initialized once before it is used. A final variable of a primitive data type cannot change its value once it has been initialized. A final variable of a reference type cannot change its reference value once it has been initialized, but the state of the object it denotes can still be changed. What is the Native modifier used? Native methods are also called foreign methods. Their implementation is not defined in Java but in another programming language. The method prototype is prefixed with the keyword native. It can also specify checked exceptions in a throws clause, which cannot be checked by the compiler since the method is not implemented in Java. class Native { static { System.loadLibrary("NativeMethodLib"); // (1) Load native library. } native void nativeMethod(); // (2) Native method prototype. } What is the Volatile modifier used? During execution, compiled code might cache the values of fields for efficiency reasons. Since multiple threads can access the same field, it is vital that caching is not allowed to cause inconsistencies when reading and writing the value in the field. The volatile modifier can be used to inform the compiler that it should not attempt to perform optimizations on the field, which could cause unpredictable results when the field is accessed by multiple threads.

If you are working with the multi-threaded programming, the volatile keyword will be more useful. When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it's updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn't know anything about the values changed by the another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory. So, other threads can access the updated value.

What is Serialization? Serialization is the process of converting an object to a stream of bytes in such a manner that the original object can be rebuilt. An object can be serialized only if it implements the Serializable or Externalizable interface; it's superclass must have a no-arg default constructor or be Serializable itself. A classes serializable fields are all of its; this applies to all public, protected, package and private fields. the serialized fields are written out using ObjectOutputStream.writeObject() and read back using ObjectOutputStream.readObject().if a field contains an object that is not serializable, a NotSerializableException is thrown. At the time of Serialization what happen to static variables? no static or transient fields undergo default serialization How can you serialize the extended class? extendable classes should be declared Serialize to serialize the extended class object other wise it should have default constructer for instantiation at the time of de serialization. What is Transient key word? Transient fields values has not saved when object is written to persistent storage. All non Serializable objects and other fields whom we do not want to store are declared as transient. Why the Externalizable interface used? Externalizable interface provide custom Serialization. It has two methods writeExternal(ObjectOutput) and readExternal(ObjectInput). These methods are automatically called with writeObject and readObject automatically. The writeExternal and readExternal uses writeXxx and readXxx method to write or read from the stream. Reading should be done in the same order as writing. How are Observer and Observable used? Objects that subclass the Observable class maintain a list of observers by adding the observer with addObserver method. When an Observable object is updated its state it calls setChanged and notifyObservers method. With the call of the notifyObservers method of Observable object it invokes the update(Observable, Object) method of each of its observer object. Why does Java not support operator overloading? The language itself does overload the plus sign for string concatenation, but that is it. The designers of Java must have decided that operator overloading was more of a problem than it was worth.What is a Labeled Statements?

The labeled statement can be a block of statement or single statement but the single statement can not be the declaration statement. The break and continue can be called from the scope of the labeled statement. What is Labeled break used?

A labeled break statement can be used to terminate any labeled statement that contains the break statement. Control is then transferred to the statement following the enclosing labeled statement. What is Labeled continue is used? A labeled continue statement must occur within a labeled loop that has the same label. Executions of the labeled continue statement then transfers control to the end of that enclosing labeled loop. Which are the Illegal character for Identifiers? - And @ can not be used in an Identifier.What are the number of keywords in java? 49 form that 2 are reserved keywords. Those are const and goto. What are the No Reserved literals in java and what are those? null, true, false. What are the number of primitive data type? 8, Integral types( int, long, short, byte) and unsigned Integral types (char), fluting point type (float, double), Boolean type(Boolean), what is hexadecimal and Octal representation in java? Hexadecimal number is represented in 0x at starting and octal with starting with 0.

What is an array? An array is a data structure that defines an indexed collection of a fixed number of homogeneous data elements. In Java, arrays are objects. When the memory is allocated to an array the values is initialized with the default value. That may be a member of class or local. What is a Switch statement?The switch condition will be either int type or enum type and case type will only int type. The default case can be placed at any position and processed only if no case is matched.

Arrange the Accessibility Modifiers from top to bottom? Public, protected, default, private What is the scope of Accessibility Modifiers? Modifierspublic protected

Members Accessible everywhere. Accessible by any class in the same package as its class, and accessible only by subclasses of its class in other packages. Only accessible by classes, including subclasses, in the same package as its class (package accessibility). Only accessible in its own class and not anywhere else.

default (no modifier)private

Which is the common symbol used for logical and bit wise operator?

The XOR operator ^. What's the difference between the ">>" and ">>>" operators? ">>" is a signed right shift, while ">>>" is an unsigned right shift. What this means is that if you use a signed shift on a negative number, the result will still be negative. Signed right shifting by one is equivalent to dividing by two, even if the number is negative. What the > n

Shift all bits in a right n times, filling with the sign bit all bits in a right n times, filling with

from the leftWhat the >>(Right shift) operator does? + and values calculation value/2n. a >>> n Shift Shift

0 from the left.What is Assertion? An assertion is a statement enables us to test our assumptions about the program. Each assertion contains a boolean expression that our believe will be true when the assertion executes. If it is not true, the system will throw an AssertionError. How to enable and disable assertion at run time? Java ea or enableassertions enables assertion and da or -disableassertions disable assertion. What is the syntax of assert Statement? The following two forms of the assert statement can be used to specify assertions: assert ; // if expression is false throw new AssertionError(); assert : ; // if expression is false throw new AssertionError(message expression); What is singleton class & its implementation? With the Singleton design pattern you can ensure that only one instance of a class is created Provide a global point of access to the object Allow multiple instances in the future without affecting a singleton class's clients //Sample Code public class SingleInstance { private static SingleInstance ourInstance = new SingleInstance(); public static SingleInstance getInstance() { if(null==ourInstance){ ourInstance= new SingleInstance();} return ourInstance; } private SingleInstance() { } }

What is the purpose of run-time class and system class. The purpose of the Runtime class is to provide access to the Java runtime system. And the purpose of the System class is to provide access to system resources Which method is used to find that the object is exited or not? we can check the null status of the object for it is exits or not. //j == null What is the difference between Class. newInstance() and new operator? Creates a new instance of the class represented by this Class object by calling no argument constructor. With new operator you can call parameterized constructor. What is a Phantom references? Phantom references point to objects that are already dead and have been finalised. Why we get error - Unsupported major.minor version 50.0? You have compiled the classes with a newer javac version than the java version. For example compiling the classes with Java 1.6 and executing them with an older version may result this error. Can you through an exception from consractior? yes, there is no problem at all. If the abstract method(in interface or abstract class) is throwing some exception than it is mandatory that the overriding method should throw some exception? No. // How much memory JVM Can access?

Its depends. Under Windows 32 bits (or a 32 bit JRE on Windows 64) only 2 GB can be addressed by a single program (minus a small window of I believe 2 MB for OS addressing/message exchange). Since java requires contiguous (virtual) memory addressing, this is further reduced. In my experience you can usually assign somewhere between 1500MB and 1800MB depending on other programs loaded. I am not exactly sure how this works on other 32 bit operating systems. It's a limitation of 32 bit OS and VM. You can allocate much more memory if you are using 64-bit.

Inner Classes & anonymous classWhat is the difference between inner class and nested class? Nested classes come in two flavors, static nested classes and inner classes. Nested classes : embedded top-level classes (static) and inner classes. Inner classes : embedded non-static classes, local classes, anonymous classes. What modifiers may be used with an inner class that is a member of an outer class? A (non-local) inner class may be declared as public, protected, private, static, final, or abstract. What modifiers can be used with a local inner class? A local inner class may be final or abstract. What modifiers may be used with a top-level class? A top-level class may be public, abstract, or final. What is nested class? Class that is declared within another class or interface, is called a nested class. What are the types of nested classes? There are fore types of nested classes. These are 1. static member classes and interfaces 2. non-static member classes 3. local classes 4. anonymous classes What is inner class? An instance of an inner class may be associated with an instance of the enclosing class. What is anonymous class? Anonymous classes combine the process of definition and instantiation into a single step. Anonymous classes are defined at the location they are instantiated, using additional syntax with the new operator. Anonymous classes can access final variables only in the enclosing context. How to instantiate an anonymous class? An anonymous class can be instantiated in both static and non static block. Class can be created by extending an Existing Class or by implementing an Interface. How can you create an anonymous class with extending an existing class? The syntax is new () { }; You can extend only one supper class. Only non-static members and final static fields can be declared in the class body. How can you create an anonymous class with implementing an existing Interface? The syntax is new () { }; An anonymous class provides a single interface implementation, and no arguments are passed. Only non-static members and final static fields can be declared in the class body. can an anonymous class have constructor? no anonymous class can not have constructor. If you want to pass some data to the parrent class constructor than at the time of creation you can pass.

example

Thread t = new Thread(r){ @Override public void run() { // TODO Auto-generated method stub super.run(); } };

can an anonymous class have field? yes non-static and final static fields only.

can we declare a class in an interface? yes by default it is static public only.Table 7.1. Overview of Classes and Interfaces

Entity

Declaration Context Package

Accessibility Enclosing Modifiers Instancepublic

Direct Access to Enclosing Context N/A

Declarations in Entity Body All that are valid in a class (or interface) body

Top-level Class (or Interface)

or

No

default All No

Static Member As static Class (or member of Interface) enclosing class or interface Non-static As non-static Member Class member of enclosing class or interface Local Class In block with non-static context

Static members in All that are valid enclosing context in a class (or interface) body

All

Yes

All members in enclosing context

Only non-static declarations + final static fields Only non-static declarations + final static fields

None

Yes

All members in enclosing context + final local variables

Table 7.1. Overview of Classes and Interfaces

Entity

Declaration Context In block with static context

Accessibility Enclosing Modifiers Instance None No

Direct Access to Enclosing Context Static members in enclosing context + final local variables All members in enclosing context + final local variables Static members in enclosing context + final local variables

Declarations in Entity Body Only non-static declarations + final static fields Only non-static declarations + final static fields Only non-static declarations + final static fields

As expression None in non-static context Anonymous Class As expression None in static context

Yes

No

UtilsWhat is Collection API? The Collection API is a set of classes and interfaces that support operation on collections of objects. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap. Example of interfaces: Collection, Set, List and Map. What is the GregorianCalendar class? The GregorianCalendar is a concrete subclass of Calendar and provides support for traditional Western calendars. What is the SimpleTimeZone class? SimpleTimeZone is a concrete subclass of TimeZone that represents a time zone for use with a Gregorian calendar. What is the Locale class? The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. What is the use of 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. What value does read() return when it has reached the end of a file? The read() method returns -1 when it has reached the end of a file. Which concrete implementation in util package implements Cloneable and Serializable interface? All concrete class in util package. What is Iterator Interface. An Iterator is similar to the Enumeration interface.With the Iterator interface methods, you can traverse a collection from start to end and safely remove elements from the underlying Collection. The iterator() method generally used in query operations. Basic methods: iterator.remove(); iterator.hasNext(); iterator.next(); Explain Enumeration Interface? The Enumeration interface allows you to iterate through all the elements of a collection. Iterating through an Enumeration is similar to iterating through an Iterator. However, there is no removal support with Enumeration. It supports two methods. boolean hasMoreElements(); Object nextElement(); What is the difference between Enumeration and Iterator interface? The Enumeration interface allows you to iterate through all the elements of a collection. Iterating through an Enumeration is similar to iterating through an Iterator. However, there is no removal support with Enumeration. Enumeration is introduced in 1.1 and Iterator(also ListIterator) in 1.2. What is the difference b/w Iterator & ListIterator? Through Iterator you can only traverse forward but with ListIterator you can traverse both side forward and backward. By using the function hasPrevious() ,previous(),PreviousIndex(). In ListIterator you can also add(o) (for inserting) set(o) (for replacing) items. Which interface the ListIterator supports? It implements Iterator interface but not list interface. What the remove method of Iterator or ListIterator does? Removes from the list the last element that was returned by next or ( previous) method. This call can only be made once per call to next or previous.

What the add method of ListIterator does? Inserts the specified element into the list (optional operation). The element is inserted immediately before the next element that would be returned by next. Which class implements serializeable and cleanable interface? All concrete class implements them. What the hashcode used for? Hash code is usefull for searching perposes. What the hashCode method returns? HashCode method returns a hashcode of that object. if the hashcode method is not ovetridden than the JVM will give different hash code for every object. You can change the behaviour by ovetridding the hascode method. Sample Hashcode that fits into a specific rang of objects? hashcode & MAX_LENGTH hashcode % MAX_LENGTH Explain Set Interface. In mathematical concept, a set is just a group of unique items, in the sense that the group contains no duplicates. It compares two elements with .equals function. The Set interface extends the Collection interface. Set does not allow duplicates in the collection. In Set implementations null is valid entry, but allowed only once. What are the two types of Set implementations available in the Collections Framework? HashSet and TreeSet are the two Set implementations available in the Collections Framework. What is the difference between HashSet and TreeSet? HashSet Class implements java.util.Set interface to eliminate the duplicate entries and uses hashing for storage. Hashing is nothing but mapping between a key value and a data item, this provides efficient searching. The TreeSet Class implements java.util.Set interface provides an ordered set, eliminates duplicate entries and uses tree for storage. HashSet allow one null value where as TreeSet not. What is the difference between HashSet and LinkedHashSet? LinkedHashSet extends HashSet. HashSet stores elements are not in any order but LinkedHashSet stores element in insertion order. Both allow one null value. What is the Difference b/w hashset and treeset? you will use a HashSet for storing your duplicate-free collection. The TreeSet implementations useful when you need to extract elements from a collection in a sorted manner. To optimize HashSet space usage , you can tune initial capacity and load factor. TreeSet has no tuning options. What is a List? List is a ordered and duplicated collection of objects. The List interface extends the Collection interface. What are the List implementations available in the Collections Framework? ArrayList, LinkedList and Vector are the three List implementations available in the Collections Framework. What is the difference between ArrayList and LinkedList? The ArrayList Class implements java.util.List interface and uses array for storage. An array storage's are generally faster to store and access rendomly but insert and delete entries in middle of the list needs a lot of data transfer which takes time. To achieve this kind of addition and deletion requires a new array constructed. The LinkedList Class implements java.util.List interface and uses linked list for storage. A linked list allow elements to be added, removed from the collection at any location in the container by ordering the elements. With this implementation you can only access the elements in sequentially.

Both allow multiple null values. What collection will you use to implement a queue and why? LinkedList , it impliments the queue interface. Which class is having the ability to add,get and remove from the head and tail without specifying the index? LinkedList. What the following code does? list.indexof(obj)!=list.lastindexof(obj) It simply check whether their are duplicates for this obj. What is RandomAccess interface? Its a marker interface. It has no methods. Its concrete implementations are ArrayList and Vector. What does the following statement convey? Vector vt = new Vector(3, 10); vt is an instance of Vector class with an initial capacity of 3 and grows in increment of 10 in each relocation What the vector. element() returns? Enumeration. What are the methods of enumeration? Enumeration has two methods hasMoreElemnts(), nextElements(). What is the difference between Vector and ArrayList? Vector and ArrayList are very similar. Both of them represent a growable array. The main difference is that Vector is synchronized while ArrayList is not. Arraylist has no default size while vector has a default size of 10. Arraylist don't define any increment size while vector does. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. What the capacity() function of Vector does? Returns the current capacity of this vector. It is not possible to find the capacity of an arrayList. What the elements() function of Vector returns? Enumeration. Explain Map Interface? A map is a special kind of set with no duplicates key. The key values are used to lookup, or index the stored data. The Map interface is not an extension of Collection interface. In Map implementations null is valid entry, but allowed only once as key and multiple as values. What are the types of Map implementations available in the Collections Framework? HashMap, TreeMap, LinkedHashMap and Hashtable are the type of Map implementations available in the Collections Framework. What is the difference between HashMap and LinkedHashMap? LinkedHashMap extends HashMap. HashMap stores elements are not in any order but LinkedHashMap stores element in Key insertion order. Both allow one null key and multiple null values. What is the difference between HashMap and TreeMap? The HashMap does not store the keys in any order But The TreeMap Class provides Sort in key order. HashMap allow one null key and multiple null values where as TreeMap allow no null as key but only multiple null values. To optimize HashMap space usage , you can tune initial capacity and load factor. TreeMap has no tuning options. What is the between Hashtable and HashMap? Both provide key-value access to data. The key differences are : Hashtable is synchronised but HasMap is not synchronised. HashMap permits null values but Hashtable doent allow null values. HashMap permits null keys but Hashtable does not allow null keys.

Which map implementation is providing LRU options? LinkedHashMap. What is UnsupportedOperationException? if the method is not supported by this collection than it throws this exception. What method in the System class allows you to copy eleemnts from one array to another? System. arraycopy() Which is faster, synchronizing a HashMap or using a Hashtable for thread-safe access? Because a synchronized HashMap requires an extra method call, a Hashtable is faster for synchronized access. How hashing is implemented in HashMap? Every object is having its own hasCode. whenever any object is inserted in HashMap than the hashcode is retrived and maped to the index. Than that index is searched which contain a linkedlist of objects those are hashed with the same index and the new object is added in that same linkedlist. When HashMap thinks to increase the size of array? As it is an implementation of both array and linkedlist you can acomodate as many as objects that you want. with the array if you know the index you can directly reach to the location but in linklist its a siquential flow. if you have a short index of array and long linkedlist the searching will be shlower. so array need to be resize. The decision of resizing will be taken when size > threshold. and threshold is calculated by threshold = (int)(capacity * loadFactor);. size is increased by 1 whenever any element is added. For hashMap what is the increament? its doibling the capacity every time it requers to be increased. the formula used is capacity