Core Java Interview Questions

Core Java Interview Questions……

  1. What is the difference between procedural and object-oriented programs?– a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code. b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.
  2. What are Encapsulation, Inheritance and Polymorphism?– Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions.
  3. What is the difference between Assignment and Initialization?– Assignment can be done as many times as desired whereas initialization can be done only once.
  4. What is OOPs?– Object oriented programming organizes a program around its data, i. e. , objects and a set of well defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.
  5. What are Class, Constructor and Primitive data types?– Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform. Constructor is a special kind of method that determines how an object is initialized when created. Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean, char.
  6. What is an Object and how do you allocate memory to it?– Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using new operator, memory is allocated to it.
  7. What is the difference between constructor and method?– Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.
  8. What are methods and how are they defined?– Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes. Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method’s signature is a combination of the first three parts mentioned above.
  9. What is the use of bin and lib in JDK?– Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.
  10. What is casting?– Casting is used to convert the value of one type to another.
  11. How many ways can an argument be passed to a subroutine and explain them?– An argument can be passed in two ways. They are passing by value and passing by reference. Passing by value: This method copies the value of an argument into the formal parameter of the subroutine. Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.
  12. What is the difference between an argument and a parameter?– While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.
  13. What are different types of access modifiers?– public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private can’t be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package.
  14. What is final, finalize() and finally?– final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can’t be overridden. A final variable can’t change from its initialized value. finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection. finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.
  15. What is UNICODE?– Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.
  16. What is Garbage Collection and how to call it explicitly?– When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.
  17. What is finalize() method?– finalize () method is used just before an object is destroyed and can be called just prior to garbage collection.
  18. What are Transient and Volatile Modifiers?– Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.
  19. What is method overloading and method overriding?– Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.
  20. What is difference between overloading and overriding?– a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method. b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass. d) Overloading must have different method signatures whereas overriding must have same signature.
  21. What is meant by Inheritance and what are its advantages?– Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.
  22. What is the difference between this() and super()?– this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.
  23. What is the difference between superclass and subclass?– A super class is a class that is inherited whereas sub class is a class that does the inheriting.
  24. What modifiers may be used with top-level class?– public, abstract and final can be used for top-level class.
  25. What are inner class and anonymous class?– Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.
  26. What is a package?– A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.
  27. What is a reflection package?– java. lang. reflect package has the ability to analyze itself in runtime.
  28. What is interface and its use?– Interface is similar to a class which may contain method’s signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for: a)Declaring methods that one or more classes are expected to implement b)Capturing similarities between unrelated classes without forcing a class relationship. c)Determining an object’s programming interface without revealing the actual body of the class.
  29. What is an abstract class?– An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.
  30. What is the difference between Integer and int?– a) Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other. b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.
  31. What is a cloneable interface and how many methods does it contain?– It is not having any method because it is a TAGGED or MARKER interface.
  32. What is the difference between abstract class and interface?– a) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be concrete or abstract. b) In abstract class, key word abstract must be used for the methods whereas interface we need not use that keyword for the methods. c) Abstract class must have subclasses whereas interface can’t have subclasses.
  33. Can you have an inner class inside a method and what variables can you access?– Yes, we can have an inner class inside a method and final variables can be accessed.
  34. What is the difference between String and String Buffer?– a) String objects are constants and immutable whereas StringBuffer objects are not. b) String class supports constant strings whereas StringBuffer class supports growable and modifiable strings.
  35. What is the difference between Array and vector?– Array is a set of related data type and static whereas vector is a growable array of objects and dynamic.
  36. What is the difference between exception and error?– The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file, which does not exist, the network connection is disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested in loading is missing. The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.
  37. What is the difference between process and thread?– Process is a program in execution whereas thread is a separate path of execution in a program.
  38. What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?– Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.
  39. What is the class and interface in java to create thread and which is the most advantageous method?– Thread class and Runnable interface can be used to create threads and using Runnable interface is the most advantageous method to create threads because we need not extend thread class here.
  40. What are the states associated in the thread?– Thread contains ready, running, waiting and dead states.
  41. What is synchronization?– Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time.
  42. When you will synchronize a piece of your code?– When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.
  43. What is deadlock?– When two threads are waiting each other and can’t precede the program is said to be deadlock.
  44. What is daemon thread and which method is used to create the daemon thread?– Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.
  45. Are there any global variables in Java, which can be accessed by other part of your program?– No, it is not the main method in which you define variables. Global variables is not possible because concept of encapsulation is eliminated here.
  46. What is an applet?– Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser.
  47. What is the difference between applications and applets?– a)Application must be run on local machine whereas applet needs no explicit installation on local machine. b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser. d)Application starts execution with its main method whereas applet starts execution with its init method. e)Application can run with or without graphical user interface whereas applet must run within a graphical user interface.
  48. How does applet recognize the height and width?– Using getParameters() method.
  49. When do you use codebase in applet?– When the applet class file is not in the same directory, codebase is used.
  50. What is the lifecycle of an applet?– init() method – Can be called when an applet is first loaded start() method – Can be called each time an applet is started. paint() method – Can be called when the applet is minimized or maximized. stop() method – Can be used when the browser moves off the applet’s page. destroy() method – Can be called when the browser is finished with the applet.
  51. How do you set security in applets?– using setSecurityManager() method
  52. What is an event and what are the models available for event handling?– An event is an event object that describes a state of change in a source. In other words, event occurs when an action is generated, like pressing button, clicking mouse, selecting a list, etc. There are two types of models for handling events and they are: a) event-inheritance model and b) event-delegation model
  53. What are the advantages of the model over the event-inheritance model?– The event-delegation model has two advantages over the event-inheritance model. They are: a)It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component’s design and its use. b)It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to be repeatedly process unhandled events as is the case of the event-inheritance.
  54. What is source and listener?– source : A source is an object that generates an event. This occurs when the internal state of that object changes in some way. listener : A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.
  55. What is adapter class?– An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act listener by extending one of the adapter classes and implementing only those events in which you are interested. For example, the MouseMotionAdapter class has two methods, mouseDragged()and mouseMoved(). The signatures of these empty are exactly as defined in the MouseMotionListener interface. If you are interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mouseDragged() .
  56. What is meant by controls and what are different types of controls in AWT?– Controls are components that allow a user to interact with your application and the AWT supports the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.
  57. What is the difference between choice and list?– A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices and only one item may be selected from a choice. A List may be displayed in such a way that several list items are visible and it supports the selection of one or more list items.
  58. What is the difference between scrollbar and scrollpane?– A Scrollbar is a Component, but not a Container whereas Scrollpane is a Conatiner and handles its own events and perform its own scrolling.
  59. What is a layout manager and what are different types of layout managers available in java AWT?– A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout.
  60. How are the elements of different layouts organized?– FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion. BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container. CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards. GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid. GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements are of different size and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.
  61. Which containers use a Border layout as their default layout?– Window, Frame and Dialog classes use a BorderLayout as their layout.
  62. Which containers use a Flow layout as their default layout?– Panel and Applet classes use the FlowLayout as their default layout.
  63. What are wrapper classes?– Wrapper classes are classes that allow primitive types to be accessed as objects.
  64. What are Vector, Hashtable, LinkedList and Enumeration?– Vector : The Vector class provides the capability to implement a growable array of objects. Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable indexes and stores objects in a dictionary using hash codes as the object’s keys. Hash codes are integer values that identify objects. LinkedList: Removing or inserting elements in the middle of an array can be done using LinkedList. A LinkedList stores each object in a separate link whereas an array stores object references in consecutive locations. Enumeration: An object that implements the Enumeration interface generates a series of elements, one at a time. It has two methods, namely hasMoreElements() and nextElement(). HasMoreElemnts() tests if this enumeration has more elements and nextElement method returns successive elements of the series.
  65. What is the difference between set and list?– Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements.
  66. What is a stream and what are the types of Streams and classes of the Streams?– A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are: Byte Streams: Provide a convenient means for handling input and output of bytes. Character Streams: Provide a convenient means for handling input & output of characters. Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream. Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer.
  67. What is the difference between Reader/Writer and InputStream/Output Stream?– The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented.
  68. What is an I/O filter?– 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.
  69. What is serialization and deserialization?– Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.
  70. What is JDBC?– JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications.
  71. What are drivers available?– a) JDBC-ODBC Bridge driver b) Native API Partly-Java driver c) JDBC-Net Pure Java driver d) Native-Protocol Pure Java driver
  72. What is the difference between JDBC and ODBC?– a) OBDC is for Microsoft and JDBC is for Java applications. b) ODBC can’t be directly used with Java because it uses a C interface. c) ODBC makes use of pointers which have been removed totally from Java. d) ODBC mixes simple and advanced features together and has complex options for simple queries. But JDBC is designed to keep things simple while allowing advanced capabilities when required. e) ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and portable on all platforms. f) JDBC API is a natural Java interface and is built on ODBC. JDBC retains some of the basic features of ODBC.
  73. What are the types of JDBC Driver Models and explain them?– There are two types of JDBC Driver Models and they are: a) Two tier model and b) Three tier model Two tier model: In this model, Java applications interact directly with the database. A JDBC driver is required to communicate with the particular database management system that is being accessed. SQL statements are sent to the database and the results are given to user. This model is referred to as client/server configuration where user is the client and the machine that has the database is called as the server. Three tier model: A middle tier is introduced in this model. The functions of this model are: a) Collection of SQL statements from the client and handing it over to the database, b) Receiving results from database to the client and c) Maintaining control over accessing and updating of the above.
  74. What are the steps involved for making a connection with a database or how do you connect to a database?a) Loading the driver : To load the driver, Class. forName() method is used. Class. forName(”sun. jdbc. odbc. JdbcOdbcDriver”); When the driver is loaded, it registers itself with the java. sql. DriverManager class as an available database driver. b) Making a connection with database: To open a connection to a given database, DriverManager. getConnection() method is used. Connection con = DriverManager. getConnection (”jdbc:odbc:somedb”, “user”, “password”); c) Executing SQL statements : To execute a SQL query, java. sql. statements class is used. createStatement() method of Connection to obtain a new Statement object. Statement stmt = con. createStatement(); A query that returns data can be executed using the executeQuery() method of Statement. This method executes the statement and returns a java. sql. ResultSet that encapsulates the retrieved data: ResultSet rs = stmt. executeQuery(”SELECT * FROM some table”); d) Process the results : ResultSet returns one row at a time. Next() method of ResultSet object can be called to move to the next row. The getString() and getObject() methods are used for retrieving column values: while(rs. next()) { String event = rs. getString(”event”); Object count = (Integer) rs. getObject(”count”);
  75. What type of driver did you use in project?– JDBC-ODBC Bridge driver (is a driver that uses native(C language) libraries and makes calls to an existing ODBC driver to access a database engine).
  76. What are the types of statements in JDBC?– Statement: to be used createStatement() method for executing single SQL statement PreparedStatement — To be used preparedStatement() method for executing same SQL statement over and over. CallableStatement — To be used prepareCall() method for multiple SQL statements over and over.
  77. What is stored procedure?– Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.
  78. How to create and call stored procedures?– To create stored procedures: Create procedure procedurename (specify in, out and in out parameters) BEGIN Any multiple SQL statement; END; To call stored procedures: CallableStatement csmt = con. prepareCall(”{call procedure name(?,?)}”); csmt. registerOutParameter(column no. , data type); csmt. setInt(column no. , column name) csmt. execute();
  79. What is servlet?– 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.
  80. What are the classes and interfaces for servlets?– There are two packages in servlets and they are javax. servlet and
  81. What is the difference between an applet and a servlet?– a) Servlets are to servers what applets are to browsers. b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.
  82. What is the difference between doPost and doGet methods?– a) doGet() method is used to get information, while doPost() method is used for posting information. b) doGet() requests can’t send large amount of information and is limited to 240-255 characters. However, doPost()requests passes all of its data, of unlimited length. c) A doGet() request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.
  83. What is the life cycle of a servlet?– Each Servlet has the same life cycle: a) A server loads and initializes the servlet by init () method. b) The servlet handles zero or more client’s requests through service() method. c) The server removes the servlet through destroy() method.
  84. Who is loading the init() method of servlet?– Web server
  85. What are the different servers available for developing and deploying Servlets?– a) Java Web Server b) JRun g) Apache Server h) Netscape Information Server i) Web Logic
  86. How many ways can we track client and what are they?– The servlet API provides two ways to track client state and they are: a) Using Session tracking and b) Using Cookies.
  87. What is session tracking and how do you track a user session in servlets?– Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are: a) User Authentication – occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password. b) Hidden form fields – fields are added to an HTML form that are not displayed in the client’s browser. When the form containing the fields is submitted, the fields are sent back to the server. c) URL rewriting – every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change. d) Cookies – a bit of information that is sent by a web server to a browser and which can later be read back from that browser. e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session. maxresidents property.
  88. What is Server-Side Includes (SSI)?– Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with an . shtml extension.
  89. What are cookies and how will you use them?– Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user. a) Create a cookie with the Cookie constructor: public Cookie(String name, String value) b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse: public void HttpServletResponse. addCookie(Cookie cookie) c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest: public Cookie[ ] HttpServletRequest. getCookie().
  90. Is it possible to communicate from an applet to servlet and how many ways and how?– Yes, there are three ways to communicate from an applet to servlet and they are: a) HTTP Communication(Text-based and object-based) b) Socket Communication c) RMI Communication
  91. What is connection pooling?– With servlets, opening a database connection is a major bottleneck because we are creating and tearing down a new connection for every page request and the time taken to create connection will be more. Creating a connection pool is an ideal approach for a complicated servlet. With a connection pool, we can duplicate only the resources we need to duplicate rather than the entire servlet. A connection pool can also intelligently manage the size of the pool and make sure each connection remains valid. A number of connection pool packages are currently available. Some like DbConnectionBroker are freely available from Java Exchange Works by creating an object that dispenses connections and connection Ids on request. The ConnectionPool class maintains a Hastable, using Connection objects as keys and Boolean values as stored values. The Boolean value indicates whether a connection is in use or not. A program calls getConnection() method of the ConnectionPool for getting Connection object it can use; it calls returnConnection() to give the connection back to the pool.
  92. Why should we go for interservlet communication?– Servlets running together in the same server communicate with each other in several ways. The three major reasons to use interservlet communication are: a) Direct servlet manipulation – allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object) b) Servlet reuse – allows the servlet to reuse the public methods of another servlet. c) Servlet collaboration – requires to communicate with each other by sharing specific information (through method invocation)
  93. Is it possible to call servlet with parameters in the URL?– Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).
  94. What is Servlet chaining?– Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request. In servlet chaining, one servlet’s output is piped to the next servlet’s input. This process continues until the last servlet is reached. Its output is then sent back to the client.
  95. How do servlets handle multiple simultaneous requests?– The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost() and service()) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.
  96. What is the difference between TCP/IP and UDP?– TCP/IP is a two-way communication between the client and the server and it is a reliable and there is a confirmation regarding reaching the message to the destination. It is like a phone call. UDP is a one-way communication only between the client and the server and it is not a reliable and there is no confirmation regarding reaching the message to the destination. It is like a postal mail.
  97. What is Inet address?– Every computer connected to a network has an IP address. An IP address is a number that uniquely identifies each computer on the Net. An IP address is a 32-bit number.
  98. What is Domain Naming Service(DNS)?– It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters. For example, www. mascom. com implies com is the domain name reserved for US commercial sites, moscom is the name of the company and www is the name of the specific computer, which is mascom’s server.
  99. What is URL?– URL stands for Uniform Resource Locator and it points to resource files on the Internet. URL has four components: http://www. address. com:80/index.html, where http – protocol name, address – IP address or host name, 80 – port number and index.html – file path.
  100. What is RMI and steps involved in developing an RMI object?– Remote Method Invocation (RMI) allows java object that executes on one machine and to invoke the method of a Java object to execute on another machine. The steps involved in developing an RMI object are: a) Define the interfaces b) Implementing these interfaces c) Compile the interfaces and their implementations with the java compiler d) Compile the server implementation with RMI compiler e) Run the RMI registry f) Run the application
  101. What is RMI architecture?– RMI architecture consists of four layers and each layer performs specific functions: a) Application layer – contains the actual object definition. b) Proxy layer – consists of stub and skeleton. c) Remote Reference layer – gets the stream of bytes from the transport layer and sends it to the proxy layer. d) Transportation layer – responsible for handling the actual machine-to-machine communication.
  102. what is UnicastRemoteObject?– All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make objects available from remote machines.
  103. Explain the methods, rebind() and lookup() in Naming class?– rebind() of the Naming class(found in java. rmi) is used to update the RMI registry on the server machine. Naming. rebind(”AddSever”, AddServerImpl); lookup() of the Naming class accepts one argument, the rmi URL and returns a reference to an object of type AddServerImpl.
  104. What is a Java Bean?– A Java Bean is a software component that has been designed to be reusable in a variety of different environments.
  105. What is a Jar file?– Jar file allows to efficiently deploying a set of classes and their associated resources. The elements in a jar file are compressed, which makes downloading a Jar file much faster than separately downloading several uncompressed files. The package java. util. zip contains classes that read and write jar files.
  106. What is BDK?– BDK, Bean Development Kit is a tool that enables to create, configure and connect a set of set of Beans and it can be used to test Beans without writing a code.
  107. What is JSP?– JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to be embedded into a web file (HTML/XML, etc). The suffix traditionally ends with .jsp to indicate to the web server that the file is a JSP files. JSP is a server side technology – you can’t do any client side validation with it. The advantages are: a) The JSP assists in making the HTML more functional. Servlets on the other hand allow outputting of HTML but it is a tedious process. b) It is easy to make a change and then let the JSP capability of the web server you are using deal with compiling it into a servlet and running it.
  108. What are JSP scripting elements?– JSP scripting elements lets to insert Java code into the servlet that will be generated from the current JSP page. There are three forms: a) Expressions of the form <%= expression %> that are evaluated and inserted into the output, b) Scriptlets of the form<% code %>that are inserted into the servlet’s service method, and c) Declarations of the form <%! Code %>that are inserted into the body of the servlet class, outside of any existing methods.
  109. What are JSP Directives?– A JSP directive affects the overall structure of the servlet class. It usually has the following form:<%@ directive attribute=”value” %> However, you can also combine multiple attribute settings for a single directive, as follows:<%@ directive attribute1=”value1″ attribute 2=”value2″ . . . attributeN =”valueN” %> There are two main types of directive: page, which lets to do things like import classes, customize the servlet superclass, and the like; and include, which lets to insert a file into the servlet class at the time the JSP file is translated into a servlet
  110. What are Predefined variables or implicit objects?– To simplify code in JSP expressions and scriptlets, we can use eight automatically defined variables, sometimes called implicit objects. They are request, response, out, session, application, config, pageContext, and page.
  111. What are JSP ACTIONS?– JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include: jsp:include – Include a file at the time the page is requested. jsp:useBean – Find or instantiate a JavaBean. jsp:setProperty – Set the property of a JavaBean. jsp:getProperty – Insert the property of a JavaBean into the output. jsp:forward – Forward the requester to a newpage. Jsp: plugin – Generate browser-specific code that makes an OBJECT or EMBED
  112. How do you pass data (including JavaBeans) to a JSP from a servlet?– (1) Request Lifetime: Using this technique to pass beans, a request dispatcher (using either “include” or forward”) can be called. This bean will disappear after processing this request has been completed. Servlet: request. setAttribute(”theBean”, myBean); RequestDispatcher rd = getServletContext(). getRequestDispatcher(”thepage. jsp”); rd. forward(request, response); JSP PAGE:<jsp: useBean id=”theBean” scope=”request” class=”. . . . . ” />(2) Session Lifetime: Using this technique to pass beans that are relevant to a particular session (such as in individual user login) over a number of requests. This bean will disappear when the session is invalidated or it times out, or when you remove it. Servlet: HttpSession session = request. getSession(true); session. putValue(”theBean”, myBean); /* You can do a request dispatcher here, or just let the bean be visible on the next request */ JSP Page:<jsp:useBean id=”theBean” scope=”session” class=”. . . ” /> 3) Application Lifetime: Using this technique to pass beans that are relevant to all servlets and JSP pages in a particular app, for all users. For example, I use this to make a JDBC connection pool object available to the various servlets and JSP pages in my apps. This bean will disappear when the servlet engine is shut down, or when you remove it. Servlet: GetServletContext(). setAttribute(”theBean”, myBean); JSP PAGE:<jsp:useBean id=”theBean” scope=”application” class=”. . . ” />
  113. How can I set a cookie in JSP?– response. setHeader(”Set-Cookie”, “cookie string”); To give the response-object to a bean, write a method setResponse (HttpServletResponse response) – to the bean, and in jsp-file:<% bean. setResponse (response); %>
  114. How can I delete a cookie with JSP?– Say that I have a cookie called “foo, ” that I set a while ago & I want it to go away. I simply: <% Cookie killCookie = new Cookie(”foo”, null); KillCookie. setPath(”/”); killCookie. setMaxAge(0); response. addCookie(killCookie); %>
  115. How are Servlets and JSP Pages related?– JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.
  1. What is a Marker Interface? – An interface with no methods. Example: Serializable, Remote, Cloneable
  2. What interface do you implement to do the sorting? – Comparable
  3. What is the eligibility for a object to get cloned? – It must implement the Cloneable interface
  4. What is the purpose of abstract class? – It is not an instantiable class. It provides the concrete implementation for some/all the methods. So that they can reuse the concrete functionality by inheriting the abstract class.
  5. What is the difference between interface and abstract class? – Abstract class defined with methods. Interface will declare only the methods. Abstract classes are very much useful when there is a some functionality across various classes. Interfaces are well suited for the classes which varies in functionality but with the same method signatures.
  6. What do you mean by RMI and how it is useful? – RMI is a remote method invocation. Using RMI, you can work with remote object. The function calls are as though you are invoking a local variable. So it gives you a impression that you are working really with a object that resides within your own JVM though it is somewhere.
  7. What is the protocol used by RMI? – RMI-IIOP
  8. What is a hashCode? – hash code value for this object which is unique for every object.
  9. What is a thread? – Thread is a block of code which can execute concurrently with other threads in the JVM.
  10. What is the algorithm used in Thread scheduling? – Fixed priority scheduling.
  11. What is hash-collision in Hashtable and how it is handled in Java? – Two different keys with the same hash value. Two different entries will be kept in a single hash bucket to avoid the collision.
  12. What are the different driver types available in JDBC? – 1. A JDBC-ODBC bridge 2. A native-API partly Java technology-enabled driver 3. A net-protocol fully Java technology-enabled driver 4. A native-protocol fully Java technology-enabled driver For more information: Driver Description
  13. Is JDBC-ODBC bridge multi-threaded? – No
  14. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? – No
  15. What is the use of serializable? – To persist the state of an object into any perminant storage device.
  16. What is the use of transient? – It is an indicator to the JVM that those variables should not be persisted. It is the users responsibility to initialize the value when read back from the storage.
  17. What are the different level lockings using the synchronization keyword? – Class level lock Object level lock Method level lock Block level lock
  18. What is the use of preparedstatement? – Preparedstatements are precompiled statements. It is mainly used to speed up the process of inserting/updating/deleting especially when there is a bulk processing.
  19. What is callable statement? Tell me the way to get the callable statement? – Callablestatements are used to invoke the stored procedures. You can obtain the callablestatement from Connection using the following methods prepareCall(String sql) prepareCall(String sql, int resultSetType, int resultSetConcurrency)
  20. In a statement, I am executing a batch. What is the result of the execution? – It returns the int array. The array contains the affected row count in the corresponding index of the SQL.
  21. Can a abstract method have the static qualifier? – No
  22. What are the different types of qualifier and what is the default qualifier? – public, protected, private, package (default)
  23. What is the super class of Hashtable? – Dictionary
  24. What is a lightweight component? – Lightweight components are the one which doesn’t go with the native call to obtain the graphical units. They share their parent component graphical units to render them. Example, Swing components
  25. What is a heavyweight component? – For every paint call, there will be a native call to get the graphical units. Example, AWT.
  26. What is an applet? – Applet is a program which can get downloaded into a client environment and start executing there.
  27. What do you mean by a Classloader? – Classloader is the one which loads the classes into the JVM.
  28. What are the implicit packages that need not get imported into a class file? – java.lang
  29. What is the difference between lightweight and heavyweight component? – Lightweight components reuses its parents graphical units. Heavyweight components goes with the native graphical unit for every component. Lightweight components are faster than the heavyweight components.
  30. What are the ways in which you can instantiate a thread? – Using Thread class By implementing the Runnable interface and giving that handle to the Thread class.
  31. What are the states of a thread? – 1. New 2. Runnable 3. Not Runnable 4. Dead
  32. What is a socket? – A socket is an endpoint for communication between two machines.
  33. How will you establish the connection between the servlet and an applet? – Using the URL, I will create the connection URL. Then by openConnection method of the URL, I will establish the connection, through which I can be able to exchange data.
  34. What are the threads will start, when you start the java program? – Finalizer, Main, Reference Handler, Signal Dispatcher
  1. What is garbage collection? What is the process that is responsible for doing that in java? – Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process
  2. What kind of thread is the Garbage collector thread? – It is a daemon thread.
  3. What is a daemon thread? – These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly.
  4. How will you invoke any external process in Java? – Runtime.getRuntime().exec(….)
  5. What is the finalize method do? – Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected.
  6. What is mutable object and immutable object? – If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …)
  7. What is the basic difference between string and stringbuffer object? – String is an immutable object. StringBuffer is a mutable object.
  8. What is the purpose of Void class? – The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.
  9. What is reflection? – Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.
  10. What is the base class for Error and Exception? – Throwable
  11. What is the byte range? -128 to 127
  12. What is the implementation of destroy method in java.. is it native or java code? – This method is not implemented.
  13. What is a package? – To group set of classes into a single unit is known as packaging. Packages provides wide namespace ability.
  14. What are the approaches that you will follow for making a program very efficient? – By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more.
  15. What is a DatabaseMetaData? – Comprehensive information about the database as a whole.
  16. What is Locale? – A Locale object represents a specific geographical, political, or cultural region
  17. How will you load a specific locale? – Using ResourceBundle.getBundle(…);
  18. What is JIT and its use? – Really, just a very fast compiler… In this incarnation, pretty much a one-pass compiler — no offline computations. So you can’t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, it’s an on-line problem.
  19. Is JVM a compiler or an interpreter? – Interpreter
  20. When you think about optimization, what is the best way to findout the time/memory consuming process? – Using profiler
  21. What is the purpose of assert keyword used in JDK1.4.x? – In order to validate certain expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing.
  22. How will you get the platform dependent values like line separator, path separator, etc., ? – Using Sytem.getProperty(…) (line.separator, path.separator, …)
  23. What is skeleton and stub? what is the purpose of those? – Stub is a client side representation of the server, which takes care of communicating with the remote server. Skeleton is the server side representation. But that is no more in use… it is deprecated long before in JDK.
  24. What is the final keyword denotes? – final keyword denotes that it is the final implementation for that method or variable or class. You can’t override that method/variable/class any more.
  25. What is the significance of ListIterator? – You can iterate back and forth.
  26. What is the major difference between LinkedList and ArrayList? – LinkedList are meant for sequential accessing. ArrayList are meant for random accessing.
  27. What is nested class? – If all the methods of a inner class is static then it is a nested class.
  28. What is inner class? – If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.
  29. What is composition? – Holding the reference of the other class within some other class is known as composition.
  30. What is aggregation? – It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation.
  31. What are the methods in Object? – clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString
  32. Can you instantiate the Math class? – You can’t instantiate the math class. All the methods in this class are static. And the constructor is not public.
  33. What is singleton? – It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods … }
  34. What is DriverManager? – The basic service to manage set of JDBC drivers.
  35. What is Class.forName() does and how it is useful? – It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( “class-instance”.newInstance() ).
  36. Inq adds a question: Expain the reason for each keyword of

public static void main(String args[])

  1. Can there be an abstract class with no abstract methods in it? – Yes
  2. Can an Interface be final? – No
  3. Can an Interface have an inner class? – Yes.
4.                   public interface abc
5.                   {
6.                          static int i=0; void dd();
7.                          class a1
8.                          {
9.                                  a1()
10.                              {
11.                                      int j;
12.                                      System.out.println("inside");
13.                              };
14.                              public static void main(String a1[])
15.                              {
16.                                      System.out.println("in interfia");
17.                              }
18.                      }
19.               }
  1. Can we define private and protected modifiers for variables in interfaces? – No
  2. What is Externalizable? – Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)
  3. What modifiers are allowed for methods in an Interface? – Only public and abstract modifiers are allowed for methods in interfaces.
  4. What is a local, member and a class variable? – Variables declared within a method are “local” variables. Variables declared within the class i.e not within any methods are “member” variables (global variables). Variables declared within the class i.e not within any methods and are defined as “static” are class variables
  5. What are the different identifier states of a Thread? – The different identifiers of a Thread are: R – Running or runnable thread, S – Suspended thread, CW – Thread waiting on a condition variable, MW – Thread waiting on a monitor lock, MS – Thread suspended waiting on a monitor lock
  6. What are some alternatives to inheritance? – Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).
  7. Why isn’t there operator overloading? – Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().
  8. What does it mean that a method or field is “static”? – Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println() work. out is a static field in the java.lang.System class.
  9. How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?
29.               String hostname = InetAddress.getByName("192.18.97.39").getHostName();
  1. Difference between JRE/JVM/JDK?
  2. Why do threads block on I/O? – Threads block on i/o (that is enters the waiting state) so that other threads may execute while the I/O operation is performed.
  3. What is synchronization and why is it important? – With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.
  4. Is null a keyword? – The null value is not a keyword.
  5. Which characters may be used as the second character of an identifier,but not as the first character of an identifier? – The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.
  6. 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.
  7. 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.
  8. What are wrapped classes? – Wrapped classes are classes that allow primitive types to be accessed as objects.
  9. What restrictions are placed on the location of a package statement within a source code file? – A package statement must appear as the first line in a source code file (excluding blank lines and comments).
  10. 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.
  11. What is a native method? – A native method is a method that is implemented in a language other than Java.
  12. 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
  13. What is the catch or declare rule for method declarations? – If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.
  14. Can an anonymous class be declared as implementing an interface and extending a class? – An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
  15. What is the range of the char type? – The range of the char type is 0 to 2^16 – 1.
  16. What is the purpose of finalization? – The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
  17. What is the difference between the Boolean & operator and the && operator? – If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. 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. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
  18. How many times may an object’s finalize() method be invoked by the garbage collector? – An object’s finalize() method may only be invoked once by the garbage collector.
  19. 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.
  20. What is the argument type of a program’s main() method? – A program’s main() method takes an argument of the String[] type.
  21. Which Java operator is right associative? – The = operator is right associative.
  22. Can a double value be cast to a byte? – Yes, a double value can be cast to a byte.
  23. What is the difference between a break statement and a continue statement? – A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.
  24. What must a class do to implement an interface? – It must provide all of the methods in the interface and identify the interface in its implements clause.
  25. What is the advantage of the event-delegation model over the earlier event-inheritance model? – The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component’s design and its use. The other advantage of the event-delegation model is that 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.
  26. How are commas used in the intialization and iteration parts of a for statement? – Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.
  27. What is an abstract method? – An abstract method is a method whose implementation is deferred to a subclass.
  28. 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.
  29. Can a Byte object be cast to a double value? – No, an object cannot be cast to a primitive value.
  30. What is the difference between a static and a non-static inner class? – A non-static inner class may have object instances that are associated with instances of the class’s outer class. A static inner class does not have any object instances.
  31. If a variable is declared as private, where may the variable be accessed? – A private variable may only be accessed within the class in which it is declared.
  32. What is an object’s lock and which object’s have locks? – An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is acquired on the class’s Class object.
  33. What is the % operator? – It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.
  34. When can an object reference be cast to an interface reference? – An object reference be cast to an interface reference when the object implements the referenced interface.
  35. Which class is extended by all other classes? – The Object class is extended by all other classes.
  36. Can an object be garbage collected while it is still reachable? – A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.
  37. Is the ternary operator written x : y ? z or x ? y : z ? – It is written x ? y : z.
  38. How is rounding performed under integer division? – The fractional part of the result is truncated. This is known as rounding toward zero.
  39. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy? – The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.
  40. 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.
  41. If a class is declared without any access modifiers, where may the class be accessed? – A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
  42. Does a class inherit the constructors of its superclass? – A class does not inherit constructors from any of its superclasses.
  43. What is the purpose of the System class? – The purpose of the System class is to provide access to system resources.
  44. Name the eight primitive Java types. – The eight primitive types are byte, char, short, int, long, float, double, and boolean.
  45. Which class should you use to obtain design information about an object? – The Class class is used to obtain information about an object’s design.
  1. Is “abc” a primitive value? – The String literal “abc” is not a primitive value. It is a String object.
  2. What restrictions are placed on the values of each case of a switch statement? – During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.
  3. What modifiers may be used with an interface declaration? – An interface may be declared as public or abstract.
  4. Is a class a subclass of itself? – A class is a subclass of itself.
  5. What is the difference between a while statement and a do statement? – 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.
  6. What modifiers can be used with a local inner class? – A local inner class may be final or abstract.
  7. What is the purpose of the File class? – The File class is used to create objects that provide access to the files and directories of a local file system.
  8. Can an exception be rethrown? – Yes, an exception can be rethrown.
  9. When does the compiler supply a default constructor for a class? – The compiler supplies a default constructor for a class if no other constructors are provided.
  10. If a method is declared as protected, where may the method be accessed? – A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.
  11. 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
  12. What restrictions are placed on method overloading? – Two methods may not have the same name and argument list but different return types.
  13. What is casting? – There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
  14. What is the return type of a program’s main() method? – A program’s main() method has a void return type.
  15. What class of exceptions are generated by the Java run-time system? – The Java runtime system generates RuntimeException and Error exceptions.
  16. What class allows you to read objects directly from a stream? – The ObjectInputStream class supports the reading of objects from input streams.
  17. What is the difference between a field variable and a local variable? – A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.
  18. How are this() and super() used with constructors? – this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
  19. What is the relationship between a method’s throws clause and the exceptions that can be thrown during the method’s execution? – A method’s throws clause must declare any checked exceptions that are not caught within the body of the method.
  20. Why are the methods of the Math class static? – So they can be invoked as if they are a mathematical code library.
  21. 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.
  22. What an I/O filter? – 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.
  23. If an object is garbage collected, can it become reachable again? – Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.
  24. What are E and PI? – E is the base of the natural logarithm and PI is mathematical value pi.
  25. Are true and false keywords? – The values true and false are not keywords.
  26. What is the difference between the File and RandomAccessFile classes? – 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.
  27. What happens when you add a double value to a String? – The result is a String object.
  28. What is your platform’s default character encoding? – If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.
  29. Which package is always imported by default? – The java.lang package is always imported by default.
  30. What interface must an object implement before it can be written to a stream as an object? – An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.
  31. How can my application get to know when a HttpSession is removed? – Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method. Create an instance of that class and put that instance in HttpSession.
  32. Whats the difference between notify() and notifyAll()? – notify() is used to unblock one waiting thread; notifyAll() is used to unblock all of them. Using notify() is preferable (for efficiency) when only one blocked thread can benefit from the change (for example, when freeing a buffer back into a pool). notifyAll() is necessary (for correctness) if multiple threads should resume (for example, when releasing a “writer” lock on a file might permit all “readers” to resume).
  33. Why can’t I say just abs() or sin() instead of Math.abs() and Math.sin()? – The import statement does not bring methods into your local name space. It lets you abbreviate class names, but not get rid of them altogether. That’s just the way it works, you’ll get used to it. It’s really a lot safer this way.
    However, there is actually a little trick you can use in some cases that gets you what you want. If your top-level class doesn’t need to inherit from anything else, make it inherit from java.lang.Math. That *does* bring all the methods into your local name space. But you can’t use this trick in an applet, because you have to inherit from java.awt.Applet. And actually, you can’t use it on java.lang.Math at all, because Math is a “final” class which means it can’t be extended.
  34. Why are there no global variables in Java? – Global variables are considered bad form for a variety of reasons: Adding state variables breaks referential transparency (you no longer can understand a statement or expression on its own: you need to understand it in the context of the settings of the global variables), State variables lessen the cohesion of a program: you need to know more to understand how something works. A major point of Object-Oriented programming is to break up global state into more easily understood collections of local state, When you add one variable, you limit the use of your program to one instance. What you thought was global, someone else might think of as local: they may want to run two copies of your program at once. For these reasons, Java decided to ban global variables.
  35. What does it mean that a class or member is final? – A final class can no longer be subclassed. Mostly 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. Methods may be declared final as well. This means they may not be overridden in a subclass. Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be changed after it’s initialized, and it must include an initializer statement where it’s declared. For example, public final double c = 2.998; It’s also possible to make a static field final to get the effect of C++’s const statement or some uses of C’s #define, e.g. public static final double c = 2.998;
  36. What does it mean that a method or class is abstract? – An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is abstract with the abstract keyword like this:
111.           public abstract class Container extends Component {

Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in the current class. It exists only to be overridden in subclasses. It has no body. For example,

  public abstract float price();

Abstract methods may only be included in abstract classes. However, an abstract class is not required to have any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared abstract.

  1. What is a transient variable? – transient variable is a variable that may not be serialized.
  2. How are Observer and Observable used? – 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.
  3. Can a lock be acquired on a class? – Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.
  4. What state does a thread enter when it terminates its processing? – When a thread terminates its processing, it enters the dead state.
  5. 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.
  6. 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.
  7. Is sizeof a keyword? – The sizeof operator is not a keyword.
  8. Does garbage collection guarantee that a program will not run out of memory? – Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
  9. Can an object’s finalize() method be invoked while it is reachable? – An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects.
  10. What value does readLine() return when it has reached the end of a file? – The readLine() method returns null when it has reached the end of a file.
  11. Can a for statement loop indefinitely? – Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;
  12. To what value is a variable of the String type automatically initialized? – The default value of an String type is null.
  13. What is a task’s priority and how is it used in scheduling? – A task’s priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.
  14. What is the range of the short type? – The range of the short type is -(2^15) to 2^15 – 1.
  15. What is the purpose of garbage collection? – 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.
  16. What do you understand by private, protected and public? – These are accessibility modifiers. Private is the most restrictive, while public is the least restrictive. There is no real difference between protected and the default type (also known as package protected) within the context of the same package, however the protected keyword allows visibility to a derived class in a different package.
  17. What is Downcasting ? – Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy
  18. Can a method be overloaded based on different return type but same argument type ? – No, because the methods can be called without using their return type in which case there is ambiquity for the compiler
  19. What happens to a static var that is defined within a method of a class ? – Can’t do it. You’ll get a compilation error
  20. 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.
  21. What is the difference amongst JVM Spec, JVM Implementation, JVM Runtime ? – The JVM spec is the blueprint for the JVM generated and owned by Sun. The JVM implementation is the actual implementation of the spec by a vendor and the JVM runtime is the actual running instance of a JVM implementation
  22. Describe what happens when an object is created in Java? – Several things happen in a particular order to ensure the object is constructed properly: Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data. The instance variables of the objects are initialized to their default values. The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.
  23. What does the “final” keyword mean in front of a variable? A method? A class? – FINAL for a variable: value is constant. FINAL for a method: cannot be overridden. FINAL for a class: cannot be derived
  24. What is the difference between instanceof and isInstance? – instanceof is used to check to see if an object can be cast into a specified type without throwing a cast class exception. isInstance() Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.
  25. Why does it take so much time to access an Applet having Swing Components the first time? – Because behind every swing component are many Java objects and resources. This takes time to create them in memory. JDK 1.3 from Sun has some improvements which may lead to faster execution of Swing applications.
  26. How could Java classes direct program messages to the system console, but error messages, say to a file?

The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:

Stream st =
 new Stream (new
  FileOutputStream ("techinterviews_com.txt"));
System.setErr(st);
System.setOut(st);
  1. What’s the difference between an interface and an abstract class?

An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

  1. Why would you use a synchronized block vs. synchronized method?

Synchronized blocks place locks for shorter periods than synchronized methods.

  1. Explain the usage of the keyword transient?

This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

  1. How can you force garbage collection?

You can’t force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

  1. How do you know if an explicit object casting is needed?

If you assign a superclass object to a variable of a subclass’s data type, you need to do explicit casting. For example:

Object a;Customer b; b = (Customer) a;

When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.

  1. What’s the difference between the methods sleep() and wait()

The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

  1. Can you write a Java class that could be used both as an applet as well as an application?

Yes. Add a main() method to the applet.

  1. What’s the difference between constructors and other methods?

Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

  1. Can you call one constructor from another if a class has multiple constructors

Yes. Use this() syntax.

  1. Explain the usage of Java packages.

This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

  1. If a class is located in a package, what do you need to change in the OS environment to be able to use it?

You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let’s say a class Employee belongs to a package com.xyz.hr; and is located in the file c:/dev/com.xyz.hr.Employee.java. In this case, you’d need to add c:/dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee

  1. What’s the difference between J2SDK 1.5 and J2SDK 5.0?

There’s no difference, Sun Microsystems just re-branded this version.

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

I’d use the method equals() to compare the values of the Strings and the = = to check if two variables point at the same instance of a String object.

  1. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

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

  1. Can an inner class declared inside of a method access local variables of this method?

It’s possible if these variables are final.

  1. What can go wrong if you replace && with & in the following code:
154.   String a=null;
155.   if (a!=null && a.length()>10)
{...}

A single ampersand here would lead to a NullPointerException.

  1. What’s the main difference between a Vector and an ArrayList

Java Vector class is internally synchronized and ArrayList is not.

  1. When should the method invokeLater()be used?

This method is used to ensure that Swing components are updated through the event-dispatching thread.

  1. How can a subclass call a method or a constructor defined in a superclass?

Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass’s constructor.

  1. What’s the difference between a queue and a stack?

Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule.

  1. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?

Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.

  1. What comes to mind when you hear about a young generation in Java?

Garbage collection.

  1. What comes to mind when someone mentions a shallow copy in Java?

Object cloning.

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

hashCode()

  1. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use: ArrayList or LinkedList?

ArrayList

  1. How would you make a copy of an entire Java object with its state?

Have this class implement Cloneable interface and call its method clone().

  1. How can you minimize the need of garbage collection and make the memory use more effective?

Use object pooling and weak object references.

  1. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?

If these classes are threads I’d consider notify() or notifyAll(). For regular classes you can use the Observer interface.

  1. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?

You do not need to specify any access level, and Java will use a default package access level.

About Sanju
I am Software Programmer. I am working in JAVA/J2EE Technologies.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: