Showing posts with label core java interview questions. Show all posts
Showing posts with label core java interview questions. Show all posts

Tuesday, April 19, 2011

Core Java Interview Questions - Part 2

In the Previous part on Core Java Interview Questions, I had posted 50 questions. Since the post was getting too big, I left out some questions which are posted in this one.

Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) that cover these topics, which you might find useful. You can use them to revise/review your understanding of these topics.

They are:

Static Fields & Methods
Loops & Iterators
Using Dates & Calendars
If & Switch Statements
File Navigation & I/O
Polymorphism - Method Overloading and Method Overriding
Encapsulation
Inheritance
Arithmetic Operators
Logical Operators

Questions:

51. Are true and false keywords?

The values true and false are not keywords.

52. What is a void return type?

A void return type indicates that a method does not return a value after its execution.

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

54. Which package is always imported by default?

The java.lang package is always imported by default in all Java Classes.

55. What restrictions are placed on method overriding?

Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides but it can expand it. The overriding method may not throw any exceptions that are not thrown by the overridden method.

56. Which arithmetic operations can result in the throwing of an ArithmeticException?

Integer / and % can result in the throwing of an ArithmeticException.

57. What is the ResourceBundle class?

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

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

59. To what value is a variable of the boolean type automatically initialized?

The default value of the boolean type is false.

60. What is the difference between the prefix and postfix forms of the ++ operator?

The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value to the expression and then performs the increment operation on that value.

61. What is the purpose of a statement block?

A statement block is used to organize a sequence of statements as a single statement group.

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

A Switch statement with 5 Case blocks can be compared to an if statement with 5 else-if blocks.

63. What do you mean by object oreiented programming

In object oreinted programming the emphasis is more on data than on the procedure and the program is divided into objects. Some concepts in OO Programming are:

* The data fields are hidden and they cant be accessed by external functions.
* The design approach is bottom up.
* The Methods operate on data that is tied together in data structure

64. What are 4 pillars of object oreinted programming

1. Abstraction - It means hiding the details and only exposing the essentioal parts

2. Polymorphism - Polymorphism means having many forms. In java you can see polymorphism when you have multiple methods with the same name

3. Inheritance - Inheritance means the child class inherits the non private properties of the parent class

4. Encapsulation - It means data hiding. In java with encapsulate the data by making it private and even we want some other class to work on that data then the setter and getter methods are provided

65. Difference between procedural and object oreinted language

In procedural programming the instructions are executed one after another and the data is exposed to the whole program
In Object Oriented programming the unit of program is an object which is nothing but combination of data and code and the data is not exposed outside the object

66. What is the difference between parameters and arguments

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

67. What is reflection in java

Reflection allows Java code to discover information about the fields, methods and constructors of loaded classes and to dynamically invoke them. The Java Reflection API covers the Reflection features.

68. What is a cloneable interface and how many methods does it contain

The cloneable interface is used to identify objects that can be cloned using the Object.clone() method. IT is a Tagged or a Marker Interface and hence it does not have any methods.

69. What is the difference between Java Bean and Java Class

Basically a Bean is a java class but it has getter and setter method and it does not have any logic in it, it is used for holding data.

On the other hand the Java class can have what a java bean has and also has some logic inside it

70. What are null or Marker interfaces in Java

The null interfaces or marker interfaces or Tagged Interfaces, do not have method declarations in them. They are empty interfaces, this is to convey the compiler that they have to be treated differently

71. Does java Support multiple inheritance

Java does not support multiple inheritance directly like C++, because then it is prone to ambiguity, example if a class extends 2 other classes and these 2 parent classes have same method names then there is ambiguity. Hence in Partial Java Multiple inheritance is supported using Interfaces

72. What are virtual function

In OOP when a derived class inherits from a base class, an object of the derived class may be referred to (or cast) as either being the base class type or the derived class type. If there are base class functions overridden by the derived class, a problem then arises when a derived object has been cast as the base class type. When a derived object is referred to as being of the base's type, the desired function call behavior is ambiguous.

The distinction between virtual and not virtual is provided to solve this issue. If the function in question is designated "virtual" then the derived class's function would be called (if it exists). If it is not virtual, the base class's function would be called.

73. Does java support virtual functions

No java does not support virtual functions direclty like in C++, but it supports using Abstract class and interfaces

74. What is JVM

When we install a java package. It contains 2 things
* The Java Runtime Environment (JRE)
* The Java Development Kit (JDK)

The JRE provides runtime support for Java applications. The JDK provides the Java compiler and other development tools. The JDK includes the JRE.

Both the JRE and the JDK include a Java Virtual Machine (JVM). This is the application that executes a Java program. A Java program requires a JVM to run on a particular platform

75. What is the difference between Authentication and Authorization

Authentication is a process for verifying that an individual is who they say they are. Authorization is an additional level of security, and it means that a particular user (usually authenticated), may have access to a particular resource say record, file, directory or script.

76. What types of values does boolean variables take

It only takes values true and false.

77. Which primitive datatypes are signed.

All primitive datatypes are signed except char and Boolean

78. Is char type signed or unsigned

char type is integral but unsigned. It range is 0 to 2^7-1

79. What forms an integral literal can be

decimal, octal and hexadecimal, hence example it can be 28, 034 and 0x1c respectively

80. Why is the main method static

So that it can be invoked without creating an instance of that class

81. What is the difference between class variable, member variable and automatic(local) variable

class variable is a static variable and does not belong to instance of class but rather shared across all the instances of the Class.

member variable belongs to a particular instance of class and can be called from any method of the class

automatic or local variable is created on entry to a method and is alive only when the method is executed

82. When are static and non static variables of the class initialized

The static variables are initialized when the class is loaded

Non static variables are initialized just before the constructor is called

83. How is an argument passed in java, is it by copy or by reference?

If the variable is primitive datatype then it is passed by copy.
If the variable is an object then it is passed by reference

84. How does bitwise (~) operator work

It converts all the 1 bits in a binary value to 0s and all the 0 bits to 1s, e.g 11110000 gets coverted to 00001111

85. Can shift operators be applied to float types.

No, shift operators can be applied only to integer or long types (whole numbers)

86. What happens to the bits that fall off after shifting

They are discarded (ignored)

87. What are the rules for overriding

The rules for Overriding are:

Private method can be overridden by private, protected or public methods
Friendly method can be overridden by protected or public methods
Protected method can be overridden by protected or public methods
Public method can be overridden by public method

88. Explain the final Modifier

Final can be applied to classes, methods and variables and the features cannot be changed. Final class cannot be subclassed, methods cannot be overridden

89. Can you change the reference of the final object

No the reference cannot be changed, but the data in that object can be changed

90. Can abstract modifier be applied to a variable

No it can be applied only to class and methods

91. Where can static modifiers be used

They can be applied to variables, methods and even a block of code, static methods and variables are not associated with any instance of class

92. When are the static variables loaded into the memory

During the class load time

93. When are the non static variables loaded into the memory

They are loaded just before the constructor is called

94. How can you reference static variables

You can refer to static variables directly using the class name and you dont need any object instance for it.

Ex: ClassTest.execMethod(); can be used to access the execMethod() method of the class ClassTest

95. Can static method use non static features of there class

No they are not allowed to use non static features of the class, they can only call static methods and can use static data

96. What is static initializer code

A class can have a block of initializer code that is simply surrounded by curly braces and labeled as static e.g.

public class Test{
static int =10;
static{
System.out.println("Hiiiiiii");
}
}

And this code is executed exactly once at the time of class load

97. Where is native modifier used?

It can refer only to methods and it indicates that the body of the method is to be found else where and it is usually written in language other than Java.

98. When do you use continue and when do you use break statements

When continue statement is applied it prematurely completes the iteration of a loop.
When break statement is applied it causes the entire loop to be abandoned.

99. What do you understand by late binding or virtual method Invocation.

When a compiler for a non object oriented language comes across a method invocation, it determines exactly what target code should be called and build machine language to represent that call. In an object oriented language, this is not possible since the proper code to invoke is determined based upon the class if the object being used to make the call, not the type of the variable. Instead code is generated that will allow the decision to be made at run time. This delayed decision making is called as late binding

100. Can Overridden methods have different return types

No they cannot have different return types

101. If the method to be overridden has access type protected, can subclass have the access type as private

No, it must have access type as protected or public, since an overriding method must not be less accessible than the method it overrides


102. What are the Final fields & Final Methods ?

Fields and methods can also be declared final. A final method cannot be overridden in a subclass. A final field is like a constant: once it has been given a value, it cannot be assigned again.

If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on Other Java Topics that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.

Previous Set of Core Java Interview Questions - Part 1

Other Java & J2EE Interview Questions

Core Java Interview Questions - Part 1

As part of the Java Interview Questions series, we have covered many large topics like Exception Handling, Threads, Garbage Collection etc. There are other topics of interest from an interview perpsective that are not large enough to warrant a seperate page. All those questions are collected here.

Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) that cover these topics, which you might find useful. You can use them to revise/review your understanding of these topics.

They are:

Static Fields & Methods
Loops & Iterators
Using Dates & Calendars
If & Switch Statements
File Navigation & I/O
Polymorphism - Method Overloading and Method Overriding
Encapsulation
Inheritance
Arithmetic Operators
Logical Operators

Questions:

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

Yes. Just, add a main() method to the applet.

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

3. 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. Once the class is available in the CLASSPATH, any other Java program can use it.

4. What's the difference between J2SDK 1.5 and J2SDK 5.0?

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

5. What are the static fields & static Methods ?

If a field or method defined as a static, there is only one copy for entire class, rather than one copy for each instance of class. static method cannot accecss non-static field or call non-static methods

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

7. Is null a keyword?

No, the null value is not a keyword.

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

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

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

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

12. Is sizeof a keyword?

No, the sizeof operator is not a keyword.

13. 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). It cannot appear anywhere else in a source code file.

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

15. What is a native method?

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

16. Can a for statement loop indefinitely?

Yes, a for statement can loop indefinitely.
Ex:
for(;;) ;

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

18. What is the range of the short type?

The range of the short data type is -(2^15) to 2^15 - 1.

19. What is the range of the char type?

The range of the char type is 0 to 2^16 - 1.

20. What is the difference between the Boolean & operator and the && operator?

&& is a short-circuit AND operator - i.e., The second condition will be evaluated only if the first condition is true. If the first condition is true, the system does not waste its time executing the second condition because, the overall output is going to be false because of the one failed condition.

& operator is a regular AND operator - i.e., Both conditions will be evaluated always.

21. What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars.

22. What is the purpose of the Runtime class?

The purpose of the Runtime class is to provide access to the Java runtime system.

23. What is the argument type of a program's main() method?

A program's main() method takes an argument of the String[] type. (A String Array)

24. Which Java operator is right associative?

The = operator is right associative.

25. What is the Locale class?

This class is used in conjunction with DateFormat and NumberFormat to format dates, numbers and currency for specific locales. With the help of the Locale class you’ll be able to convert a date like “10/10/2005” to “Segunda-feira, 10 de Outubro de 2005” in no time. If you want to manipulate dates without producing formatted output, you can use the Locale class directly with the Calendar class

26. Can a double value be cast to a byte?

Yes, a double value can be cast to a byte. But, it will result in loss of precision.

27. 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 beginning of the loop.

28. How are commas used in the intialization and iterationparts of a for statement?

Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.

29. How are Java source code files named?

A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file can take on a name that is different than its classes and interfaces. Source code files use the .java extension.

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

31. Can a Byte object be cast to a double value?

No, an object cannot be cast to a primitive value.

32. What is the Dictionary class?

The Dictionary class provides the capability to store key-value pairs. It is the predecessor to the current day HashMap and Hashtable.

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. What is the difference between the Font and FontMetrics classes?

The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

35. How is rounding performed under integer division?

The fractional part of the result is truncated. This is known as rounding toward zero.

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

37. What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar. You can use it to manipulate dates & times.

38. For which statements does it make sense to use a label?

The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement.

39. What is the purpose of the System class?

The purpose of the System class is to provide access to system resources.

40. Is &&= a valid Java operator?

No, it is not a valid operator.

41. Name the eight primitive Java data types.

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

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

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

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

A static variable is associated with the class as a whole rather than with specific instances or objects of a class. Non-static variables take on unique values with each object instance.

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

46. Which Math method is used to calculate the absolute value of a number?

The abs() method is used to calculate absolute values.

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

48. What restrictions are placed on method overloading?

Two methods may not have the same name and argument list but different return types.

49. What is the return type of a program's main() method?

A program's main() method has a void return type. i.e., the main method does not return anything.

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


Continued as Part 2...

Other Java & J2EE Interview Questions

Java AWT Interview Questions

The following are some questions you might encounter with respect to the AWT components in any Interview. AWT stands for Abstract Window Toolkit and is used for creating UI components using Java. Though AWT is outdated and its successor Java Swings is more widely used, AWT is still being used by many projects.

Questions:

1. Which containers use a border Layout as their default layout?

The window, Frame and Dialog classes use a border layout as their default layout.

2. What is the preferred size of a component?

The preferred size of a component is the minimum component size that is required for the component to display normally.

3. What method is used to specify a container's layout?

The setLayout() method is used to specify a container's layout.

4. Which containers use a FlowLayout as their default layout?

The Panel and Applet classes use the FlowLayout as their default layout.

5. Which method of the Component class is used to set the position and size of a component?

The setBounds() method

6. Which java.util classes and interfaces support event handling?

The EventObject class and the EventListener interface support event processing.

7. What is the purpose of using Event Handlers?

Any UI based application would have to respond to user actions. For ex: If you click on the Save button in a web page, you would expect the system to save the values you entered in the screen. Similarly there might be numerous actions that might need to be captured and handled by the system. Event handlers help us with that. Capturing user button clicks, opening of new pages etc.

8. What is the immediate superclass of the Applet class?

Panel

9. Name few Component subclasses that support painting.

The Canvas, Frame, Panel, and Applet classes support painting.

10. What is the immediate superclass of the Dialog class?

Window

11. What is clipping?

Clipping is the process of confining paint operations to a limited area or shape.

12. What is the difference between a MenuItem and a CheckboxMenuItem?

The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.

13. What class is the top of the AWT event hierarchy?

The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.

14. In which package are most of the AWT events that support the event-delegation model defined?

Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package.

15. What is the immediate superclass of Menu?

MenuItem

16. Which class is the immediate superclass of the MenuComponent class.

Object

17. Name three subclasses of the Component class.

Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, TextComponent etc are all subclasses of the Component class.

18. Which Container method is used to cause a container to be laid out and redisplayed?

validate()

19. Name two subclasses of the TextComponent class.

TextField and TextArea

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

21. Which containers may have a MenuBar?

Frame

22. What is the relationship between the Canvas class and the Graphics class?

A Canvas object provides access to a Graphics object via its paint() method.

23. How are the elements of a BorderLayout organized?

The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container. Usually the Center is the largest and occupies the most space in the layout.

24. What is the difference between a Window and a Frame?

The Frame class extends Window to define a main application window that can have a menu bar.

25. Which TextComponent method is used to set a TextComponent to the read-only state?

setEditable(). By setting setEditable(false) you can ensure that no one can edit that particular text component.

26. How are the elements of a CardLayout organized?

The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.

27. What is the relationship between clipping and repainting?

When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.


28. What is the relationship between an event-listener interface and an event-adapter class?

An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface.


29. What event results from the clicking of a button?

The ActionEvent event is generated as the result of the clicking of a button.

30. How can a GUI component handle its own events?

A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.

31. How are the elements of a GridBagLayout organized?

The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

32. What advantage do Java's layout managers provide over traditional windowing systems?

Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems. Also, when you resize a window, the usage of layout manager helps to adjust the components to fit the window size in a graceful manner while the use of no layout manager may result in the screen components displayed in a chaotic fashion.


33. What is the difference between the paint() and repaint() methods?

The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.


34. Which class is the immediate superclass of the Container class?

Component


35. How can the Checkbox class be used to create a radio button?

By associating Checkbox objects with a CheckboxGroup.


36. What is the purpose of the enableEvents() method?

The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.


37. What interface is extended by AWT event listeners?

All AWT event listeners extend the java.util.EventListener interface.

38. What is a layout manager?

A layout manager is an object that is used to organize components in a container.


39. What is the difference between a Scrollbar and a ScrollPane?

A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.


40. What methods are used to get and set the text label displayed by a Button object?

getLabel() and setLabel()

41. Which Component subclass is used for drawing and painting?

Canvas

42. What are the problems faced by Java programmers who don't use layout managers?

Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system. When you resize a window, the usage of layout manager helps to adjust the components to fit the window size in a graceful manner while the use of no layout manager may result in the screen components displayed in a chaotic fashion.


If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on AWT that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.

More Java & J2EE Interview Questions with Answers - Click Here

Java Classes & Interfaces Interview Questions

The following are some questions you might encounter with respect to Java Classes & Interfaces in any Java Interview. Classes and Interfaces are the building blocks of the Java Programming language and any experienced Java programmer needs to know the basics of Classes and Interfaces.

Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Classes & Interfaces that you might find useful. You can use them to revise/review your understanding of the topic.

They are:

Declaring Classes & Interfaces
Inner Classes
Method-Local Inner Classes
Anonymous Inner Classes
Static Nested Classes
Access Specifiers
Implementing an Interface
Reference Variable Casting
Constructors & Object Instantiation
The instanceOf Operator

Questions:

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.

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

Yes, it is possible if the variables are declared as final.

3. 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 because Java does not support multiple inheritance.

4. 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. A class with default access will be accessible only to other classes that are declared in the same directory/package.

5. When you declare a method as abstract method ?

We declare a method as abstract, When we want child class to implement the behavior of the method.

6. Can I call a abstract method from a non abstract method ?

Yes, We can call a abstract method from a Non abstract method in a Java abstract class

7. What is the difference between an Abstract class and Interface in Java ? or can you explain when you use Abstract classes ?

Abstract classes let you define some behavior while forcing your subclasses to provide the rest. These abstract classes will provide the basic funcationality of your application, child class which inherit this class will provide the funtionality of the abstract methods in abstract class.

Whereas, An Interface can only declare constants and instance methods, but cannot implement any default behavior.

If you want your class to extend some other class but at the same time re-use some features outlined in a parent class/interface - Interfaces are your only option because Java does not allow multiple inheritance and once you extend an abstract class, you cannot extend any other class. But, if you implement an interface, you are free to extend any other concrete class as per your wish.

Also, Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. Abstract classes are fast.

8. What are different types of inner classes ?

Inner classes nest within other classes. A normal class is a direct member of a package. Inner classes are of four types

1. Static member classes
2. Member classes
3. Local classes
4. Anonymous classes

9. What are the field/method access levels (specifiers) and class access levels ?

Each field and method has an access level corresponding to it:

private: accessible only in this class
package: accessible only in this package
protected: accessible only in this package and in all subclasses of this class
public: accessible everywhere this class is available

Similarly, each class has one of two possible access levels:

package: class objects can only be declared and manipulated by code in this package
public: class objects can be declared and manipulated by code in any package

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

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

12. What must a class do to implement an interface?

It must provide implementation to all of the methods in the interface and identify the interface in its implements clause in the class declaration line of code.

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

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

15. 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 default or package level access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.

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

17. What modifiers may be used with an interface declaration?

An interface may be declared as public or abstract.

18. Is a class a subclass of itself?

Yes, a class is a subclass of itself.

19. What modifiers can be used with a local inner class?

A local inner class may be final or abstract.

20. Can an abstract class be final?

An abstract class may not be declared as final. Abstract and Final are two keywords that carry totally opposite meanings and they cannot be used together.

21. What is the difference between a public and a non-public class?

A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package.

22. What modifiers may be used with a top-level class?

A top-level class may be public, abstract, or final.

23. What are the Object and Class classes used for?

The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.

24. Can you make an instance of abstract class

No you cannot create an instance of abstract class. If you use new keyword to instantiate an abstract class, you will get a compilation error.

25. Describe what happens when an object is created in Java

Several things happen in a particular order to ensure the object is created properly:

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

2. The instance variables of the objects are initialized to their default values.

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

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

26. What is the purpose of System Class

The purpose of the system class is to provide the access to the System reources

27. What is instanceOf operator used for

It is used to check if an object can be cast into a specific type without throwing Class cast exception

28. Why we should not have instance variable in an interface?

Since all data fields and methods in an Interface are public by default, when we implement that interface in our class, we have public members in our class and this class will expose these data members and this is violation of encapsulation as now the data is not secure

29. What is a singleton class

A singleton is an object that cannot be instantiated more than once. The restriction on the singleton is that there can be only one instance of a singleton created by the Java Virtual Machine (JVM) - by prevent direct instantiation we can ensure that developers don't create a second copy. We accomplish this by declaring the constructor private and having a public static instance variable of the class's type that can be accessed using a getInstance() method in the class.

30. Can an abstract class have final method

Yes, you can have a final method in an Abstract class.

31. Can a final class have an abstract method

No, a Final class cannot have an Abstract method.

32. When does the compiler insist that the class must be abstract

The compiler insists that your class be made abstract under the following circumstances:

1. If one or more methods of the class are abstract.
2. If class inherits one or more abstract methods from the parent abstract class and no implementation is provided for that method
3. If class implements an interface and provides no implementation for some methods

33. How is abstract class different from final class

Abstract class must be subclassed and an implementation has to be provided by the child class whereas final class cannot be subclassed

34. What is an inner class

An inner class is same as any other class, just that, is declared inside some other class

35. How will you reference the inner class

To reference an inner class you will have to use the following syntax: OuterClass$InnerClass

36. Can objects that are instances of inner class access the members of the outer class

Yes they can access the members of the outer class

37. Can inner classes be static

Yes inner classes can be static, but they cannot access the non static data of the outer classes, though they can access the static data

38. Can an inner class be defined inside a method

Yes it can be defined inside a method and it can access data of the enclosing methods or a formal parameter if it is final

39. What is an anonymous class

Some classes defined inside a method do not need a name, such classes are called anonymous classes

40. What are access modifiers

These public, protected and private, these can be applied to class, variables, constructors and methods. But if you don't specify an access modifier then it is considered as Friendly. They determine the accessibility or visibility of the entities to which they are applied.

41. Can protected or friendly features be accessed from different packages

No when features are friendly or protected they can be accessed from all the classes in that package but not from classes in another package

42. How can you access protected features from another package

You can access protected features from other classes by subclassing the that class in another package, but this cannot be done for friendly features


If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on Classes & Interfaces that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.

More Java & J2EE Interview Questions with Answers - Click Here

Java Threads & Multi-threading Interview Questions

The following are some questions you might encounter with respect to Java Multi-threading in any Interview. Multi-threading is a powerful and rather a complicated feature of Java. Expertise in multithreading is an added advantage to any and every core java programmer.

Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Java Multi-threading that you might find useful. You can use them to revise/review your understanding of Servlets.

They are:

Introduction to Threads and Multithreading
Thread States and Transitions
Preventing Thread Execution
Thread Priorities
Thread Synchronization
Thread Interactions

Questions:

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

Synchronized blocks place locks for shorter periods than synchronized methods.

2. What's the difference between the methods sleep() and wait()

The code sleep(1000); puts thread to sleep (Or prevent the thread from executing) 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.

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

4. What is Runnable interface ? Are there any other ways to make a multithreaded java program?

There are two ways to create new threads:

- Define a new class that extends the Thread class
- Define a new class that implements the Runnable interface, and pass an object of that class to a Thread's constructor.

The advantage of the second approach is that the new class can be a subclass of any class, not just of the Thread class.


5. How can I tell what state a thread is in ?

Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive() returned false the thread was either new or terminated but there was simply no way to differentiate between the two.

Starting with the release of Java Tiger (Java 5) you can now get what state a thread is in by using the getState() method which returns an Enum of Thread.States. A thread can only be in one of the following states at a given point in time.

New, Runnable, Blocked, Waiting, Timed_waiting and Terminated


6. What is the difference between notify and notify All methods ?

A call to notify causes at most one thread waiting on the same object to be notified (i.e., the object that calls notify must be the same as the object that called wait). A call to notifyAll causes all threads waiting on the same object to be notified. If more than one thread is waiting on that object, there is no way to control which of them is notified by a call to notifyAll

so, sometimes it is better to use notify than notifyAll.

7. What is synchronized keyword? In what situations you will Use it?

Synchronization is the act of serializing access to critical sections of code. We will use this keyword when we expect multiple threads to access/modify the same data. It helps prevent dirty read/write and helps keep thread execution clean and seperate. For more details on why we need Synchronization and how to use it, you can visit the article on Thread Synchronization as it is a large topic to be covered as an answer to a single question.

8. Why do threads block on I/O?

Threads block on i/o (i.e., Thread enters the waiting state) so that other threads may execute while the i/o Operation is performed. This is done to ensure that one thread does not hold on to resources while it is waiting for some user input - like entering a password.

9. 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. For more details on why we need Synchronization and how to use it, you can visit the article on Thread Synchronization as it is a large topic to be covered as an answer to a single question.

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

11. What's new with the stop(), suspend() and resume() methods in JDK 1.2?

Actually there is nothing new about these methods. The stop(), suspend() and resume() methods have been deprecated as of JDK 1.2.

12. What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state.

13. How do you make threads to wait for one another to complete execution as a group?

We can use the join() method to make threads wait for one another

14. What is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.

15. 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 many other factors. You can refer to articles on Operating Systems and processor scheduling for more details on the same.

16. When a thread blocks on I/O, what state does it enter?

A thread enters the waiting state when it blocks on I/O.

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

18. When a thread is created and started, what is its initial state?

A thread is in the ready state after it has been created and started.

19. What invokes a thread's run() method?

After a thread is started, via its start() method, the JVM invokes the thread's run() method when the thread needs to be executed.

20. What method is invoked to cause an object to begin executing as a separate thread?

The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.

21. What is the purpose of the wait(), notify(), and notifyAll() methods?

The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.

22. What are the high-level thread states?

The high-level thread states are ready, running, waiting, and dead.

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

24. What happens when a thread cannot acquire a lock on an object?

If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.

25. How does multithreading take place on a computer with a single CPU?

The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.

26. What happens when you invoke a thread's interrupt method while it is sleeping or waiting?

When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.

27. How can a dead thread be restarted?

A dead thread cannot be restarted. Once a thread is dead, it stays dead and there is no way to revive it.

28. What are three ways in which a thread can enter the waiting state?

A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.

29. What method must be implemented by all threads?

All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface. Without a run() method, a thread cannot execute.

30. What are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

A synchronized statement can be inside a regular method and vice versa.

31. What are volatile variables

It indicates that these variables can be modified asynchronously. i.e., there is no need for synchronzing these variables in a multi-threaded environment.

32. Where does java thread support reside

It resides in three distinct places

The java.lang.Thread class (Most of the support resides here)
The java.lang.Object class
The java language and virtual machine

33. What is the difference between Thread and a Process

Threads run inside process and they share data.

One process can have multiple threads, if the process is killed all the threads inside it are killed

34. What happens when you call the start() method of the thread

This registers the thread with a piece of system code called thread scheduler. The schedulers is the entity that determines which thread is actually running. When the start() method is invoked, the thread becomes ready for running and will be executed when the processor allots CPU time to execute it.

35. Does calling start () method of the thread causes it to run

No it just makes the thread eligible to run. The thread still has to wait for the CPU time along with the other threads, then at some time in future, the scheduler will permit the thread to run

36. When the thread gets to execute, what does it execute

It executes all the code that is placed inside the run() method.

37. How many methods are declared in the interface runnable

The runnable method declares only one method : public void run();

38. Which way would you prefer to implement threading - by extending Thread class or implementing Runnable interface

The preferred way will be to use Interface Runnable, because by subclassing the Thread class you have single inheritance i.e you wont be able to extend any other class in Java.

39. What happens when the run() method returns

When the run() method returns, the thread has finished its task and is considered dead. You can't restart a dead thread.

40. What are the different states of the thread

The different states of Threads are:

New: Just created Thraed
Running: The state that all threads want to be
Various waiting states : Waiting, Sleeping, Suspended and Blocked
Ready : Waiting only for the CPU
Dead : Story Over

41. What is Thread priority

Every thread has a priority, the higher priority thread gets preference over the lower priority thread by the thread scheduler

42. What is the range of priority integer that can be set for Threads?

It is from 1 to 10. 10 beings the highest priority and 1 being the lowest

43. What is the default priority of the thread

The default priority is 5. It is also called the Normal Priority.

44. What happens when you call Thread.yield()

It causes the currently executing thread to move to the ready state if the scheduler is willing to run any other thread in place of the yielding thread. Yield is a static method of class Thread

45. What is the advantage of yielding

It allows a time consuming thread to permit other threads to execute

46. What happens when you call Thread.sleep()

It causes the thread to while away time without doing anything and without using the CPU. A call to sleep method requests the currently executing thread to cease executing for a specified amount of time as mentioned in the argument to the sleep method.

47. Does the thread method start executing as soon as the sleep time is over

No, after the specified time is over the thread enters into ready state and will only execute when the scheduler allows it to do so. There is no guarantee that the thread will start running as soon as its sleep time is over.

48. What do you mean by thread blocking

If a method needs to wait an indeterminable amount of time until some I/O occurrence takes place, then a thread executing that method should graciously step out of the Running state. All java I/O methods behave this way. A thread that has graciously stepped out in this way is said to be blocked.

49. What threading related methods are there in object class

wait(), notify() and notifyAll() are all part of Object class and they have to be called from synchronized code only

50. What is preemptive scheduling

Preemptive scheduing is a scheduling mechanism wherein, the scheduler puts a lower priority thread on hold when a higher priority thread comes into the waiting queue. The arrival of a higher priority thread always preempts the execution of the lower priority threads. The problem with this system is - a low priority thread might remain waiting for ever.

51. What is non-preemptive or Time sliced or round robin scheduling

With time slicing the thread is allowd to execute for a limited amount of time. It is then moved to ready state, where it must wait along with all the other ready threads. This method ensures that all threads get some CPU time to execute.

52. What are the two ways of synchronizing the code

Synchronizing an entire method by putting the synchronized modifier in the methods declaration. To execute the method, a thread must acquire the lock of the object that owns the method.

Synchronize a subset of a method by surrounding the desired lines of code with curly brackets and inserting the synchronized expression before the opening curly. This allows you to synchronize the block on the lock of any object at all, not necessarily the object that owns the code

53. What happens when the wait() method is called

The following things happen:

The calling thread gives up CPU
The calling thread gives up the lock
The calling thread goes into the monitor's waiting pool

54. What happens when the notify() method is called

One thread gets moved out of monitors waiting pool and into the ready state and The thread that was notified must reacquire the monitors lock before it can proceed execution

55. Using notify () method how you can specify which thread should be notified

You cannot specify which thread is to be notified, hence it is always better to call notifyAll() method

Questions Contributed by our Blog Readers:

Contributed by Sweta Pawar:


Which statement at line 17 will ensure that j=10 at line 18

1 class A implements runaible (
2 int i;
3 public void run () (
4 try (
5 thread.sleep(5000);
6 i= 10;
7 ) catch(InterruptedException e) {}
8 )
9 )
10
11 public class Test {
12 public static void main (string args[]) (
13 try (
14 A a = new A ();
15 Thread t = new Thread (a);
16 t.start();
17 ** HERE**
18 int j= a.i;
19
20 ) catch (Exception e) {}
21 )
22 )


Answer: t.join();



If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on Threads & Multithreading that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.

More Java & J2EE Interview Questions with Answers - Click Here

Java Garbage Collection Interview Questions

The following are some questions you might encounter with respect to Java Garbage collection in any Java Interview. Garbage Collection is a very important concept in the Java Programming Technology that helps clear out unused memory objects and keep the system running without any memory issues. Hence, a good knowledge of the Garbage collection processes is a mandatory skill for any core java developer.

Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Garbage collection that you might find useful. You can use them to revise/review your understanding of Garbage Collection.

They are:

Stacks & Heap
Java Garbage Collection

Questions:

1. How can you force garbage collection?

You cannot force Garbage Collection, but could request it by calling System.gc(). Though you manually call this command from your program, the JVM does not guarantee that GC will be started immediately.

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

Use object pooling and weak object references. We need to ensure that all objects that are no longer required in the program are cleared off using finalize() blocks in your code.

3. Explain garbage collection ?

Garbage collection is an important part of Java's security strategy. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects from the memory. The name "garbage collection" implies that objects that are no longer needed or used by the program are "garbage" and can be thrown away to create free space for the programs that are currently running. A more accurate and up-to-date term might be "memory recycling." When an object is no longer referenced by the program, the heap space it occupies must be recycled so that the space is available for subsequent new objects. The garbage collector must determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. This way, unused memory space is reclaimed and made available for the program to use.

4. 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 as well. Hence, the Garbage Collection mechanism is a "On Best Effort Basis" system where the GC tries to clean up memory as much as possible to ensure that the system does not run out of memory but it does not guarantee the same.

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

6. 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. We usually nullify the object references of large objects like collections, maps etc in the finalize block.


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


8. 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. The system will not do it and you cannot force it either.

9. If an object is garbage collected, can it become reachable again?

Once an object is garbage collected, it ceases to exist. i.e., it is dead or deleted. It can no longer become reachable again.


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


11. Can an unreachable object become reachable again?

An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

12. When is an object subject to garbage collection?

An object is subject to garbage collection when it becomes unreachable to the program in which it is used. i.e., no other object or code in the system is going to access this current object

13. Does System.gc() and Runtime.gc() guarantee garbage collection

No.

14. Do we need memory management code in our application?

No. Memory Management is a complicated activity and that is exactly why the creators of the Java language did it themselves so that programmers like us do not have to go through the pain of handling memory management.

15. What is OutOfMemoryError in java? How to deal with java.lang.OutOfMemeryError error?

This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. Note: Its an Error (extends java.lang.Error) not Exception.

Two important types of OutOfMemoryError are often encountered
1. java.lang.OutOfMemoryError: Java heap space - The quick solution is to add these flags to JVM command line when Java runtime is started as follows:
-Xms1024m -Xmx1024m
2. java.lang.OutOfMemoryError: PermGen space - The solution is to add these flags to JVM command line when Java runtime is started as follows:

-XX:+CMSClassUnloadingEnabled-XX:+CMSPermGenSweepingEnabled

Increasing the Start/Max Heap size or changing Garbage Collection options may not always be a long term solution for your Out Of Memory Error problem. Best approach is to understand the memory needs of your program and ensure it uses memory wisely and does not have leaks.




If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on Garbage collection that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.

More Java & J2EE Interview Questions with Answers - Click Here

Java Strings Interview Questions

The following are some questions you might encounter with respect to Strings in any Java Interview. Strings are very powerful and frankly speaking, there can be no Java based application that does not use Strings.

Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Strings that you might find useful. You can use them to revise/review your understanding of Strings.

They are:

Java String Class
StringBuffer & StringBuilder


Questions:

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

I would personally prefer/use the equals() method to compare two Strings if I want to check the value of the Strings and the == operator if I want to check if the two variables point to the same instance of the String object.

2. For concatenation of strings, which method is good, StringBuffer or String ?

StringBuffer is faster than String for concatenation. Also, it is less memory/resource intensive when compared to Strings.

3. As a continuation to the previous question - Why would you say StringBuffers are less resource intensive than Strings during Concatenation?

As you might already know, Strings are immutable. So, when you concatenate some value to a String, you are actually creating a fresh String object that is going to hold some more data. This way you have created a new object while the old String object is still alive. As you keep concatenating values to the String, newer objects are going to get created which are going to use up the virtual memory. Whereas, if you use a StringBuffer, you are just editing the objects value rather than creating new objects.

4. To what value is a variable of the String type automatically initialized?

The default value of String variable is null.

5. What is the difference between the String and StringBuffer classes?

String objects are constants or in other words immutable while StringBuffer objects are not.

6. What happens when you add a double value to a String?

The result is a String object. For that matter, if you add anything to a String, you will end up with a String.

7. What will be the result if you compare StringBuffer with String if both have same values?

It will return false as you cannot compare String with StringBuffer directly. If you really want to compare the contents of the String & the StringBuffer you would have to invoke the equals method with the String and the toString() output of the StringBuffer.

8. What is difference between String, StringBuffer and StringBuilder? When to use them?

For all practical understanding purposes, all these 3 classes are used to handle/manipulate Strings. The main difference between these 3 classes is:

* Strings are immutable while StringBuffer & StringBuilder objects are mutable (can be modified)
* StringBuffer is synchronized (thread safe) while StringBuilder is not. 

9. When to use Strings or StringBuffer or StringBuilder? What will drive this decision? 

The type of objects you need to create and how they will be used will drive this decision. So, 

* If the object value is not going to change, use the String class
* If the object value will be changed frequently we must choose either the StringBuffer or the StringBuilder. 
* Here, if your object will be accessed only by a single thread use StringBuilder because it is faster 
* If your object may be accessed my multiple threads use the StringBuffer because it is thread safe 

Note: Thread safety is not free and comes at the expense of performance. So, if your system is not multi-threaded then use the StringBuilder which will be much faster than the StringBuffer. 

10. Why String class is final or immutable?

The reason "Why" the string class is final is because - The developers of the Java language did not want programmers to mess with the basic functionality of the String Class. Almost all the basic or core functionality related classes in Java are final for the same reason. 

If String were not final, you could create a subclass and have two strings that look alike when you see the value in the string, but that are actually different. 

Ex: See the two string objects below, MyString and YourString are two classes that are sub-classes of the "String" class and contain the same value but their equality check might fail which does not look right. Doesnt it? 

MyString str1 = "Rocky";
YourString str2 = "Rocky";

This is why String class is final. 


If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on Strings that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.

More Java & J2EE Interview Questions with Answers - Click Here

Java Collections Interview Questions - Part 1

The following are some questions you might encounter with respect to Java Collections in any Interview. Collections are an integral part of any Java application and it would be surprising if you did not get a few of the collection questions in an interview.

Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Collections that you might find useful. You can use them to revise/review your understanding of Java collections.

They are:

Introduction to Collections
ArrayList Basics
Sorting Collections
Searching Collections
Collections Summary

Questions:

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

Java Vector class is internally synchronized and ArrayList is not. Hence, Vectors are thread-safe while ArrayLists are not. On the Contrary, ArrayLists are faster and Vectors are not. ArrayList has no default size while vector has a default size of 10.

2. What's the difference between a queue and a stack?

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

3. what is a collection?

Collection is a group of objects.

There are two fundamental types of collections they are Collection and Map.

Collections just hold a bunch of objects one after the other while Maps hold values in a key-value pair.

Collections Ex: ArrayList, Vector etc.
Map Ex: HashMap, Hashtable etc

4. What is the Collections API?

The Collections API is a set of classes and interfaces that support operation on collections of objects. The API contains Interfaces, Implementations & Algorithm to help java programmer in everyday programming using the collections.

The purpose of the Collection API is to:

o Reduces programming efforts. - Increases program speed and quality.
o Allows interoperability among unrelated APIs.
o Reduces effort to learn and to use new APIs.
o Reduces effort to design new APIs.
o Encourages & Fosters software reuse.

Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

5. What is the List interface?

The List interface provides support for ordered collections of objects. Ex: ArrayList

6. What is the Vector class?

The Vector class provides the capability to implement a growable array of objects that is synchronzied and thread-safe.

7. What is an Iterator interface?

The Iterator interface is used to step through the elements of a Collection one by one. It is an easier way to loop through the contents of a collection when you do not know, how many objects are present in it. Also, it is a cleaner way to access the contents of a collection when compared to using a for loop and accessing entries using get(index) method.

Remember that, when using Iterators they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

8. What is the Map interface?

A map is an object that stores associations between keys and values (key/value pairs). Given a key, you can find its value. Both keys and values are objects. The keys must be unique, but the values may be duplicated. Some maps can accept a null key and null values, others cannot.


9. What is the Collection interface?

The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.

10. What is the Set interface?

• The Set interface provides methods for accessing the elements of a finite mathematical set
• Sets do not allow duplicate elements
• Contains no methods other than those inherited from Collection
• It adds the restriction that duplicate elements are prohibited
• Two Set objects are equal if they contain the same elements


11. What are different types of collections?

* A regular collection has no special order and does not reject duplicates
* A list is ordered and does not reject duplicates
* A set has no special order but rejects duplicates
* A map supports storing data as key-value pairs

12. Difference between Hashtable and HashMap?

* Hashtable does not store null value, while HashMap does
* Hashtable is synchronized, while HashMap is not
* Hashtables are slower because of the synchronization overhead while HashMaps are faster

13.What are the main Implementations of the Set interface ?
The main implementations of the List interface are as follows:
HashSet
TreeSet
LinkedHashSet
EnumSet

14.What is a HashSet ?
A HashSet is an unsorted, unordered Set. It uses the hashcode of the object being inserted to access the object. So, the more efficient your hashcode() implementation the better access performance you’ll get. Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it.
62.What is a TreeSet ?
TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time.

15.What is an EnumSet ?
An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created.

16.Difference between HashSet and TreeSet ?

HashSet does not store data in any Order while the TreeSet stores data in order. Also, you can elements of any type to the hash set while you can only add similar types of elements into a tree set.


17.What are the main Implementations of the Map interface ?
The main implementations of the List interface are as follows:
HashMap
HashTable
TreeMap
EnumMap

18.What is a TreeMap ?
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.

19.How do you decide when to use HashMap and when to use TreeMap ?
For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.

20. Can I store multiple keys or values that are null in a HashMap?

You can store only one key that has a value null. But, as long as your keys are unique, you can store as many nulls as you want in an HashMap

If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on Collections that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.

More Java & J2EE Interview Questions with Answers - Click Here

Java Collections Interview Questions - Part 2

Monday, April 18, 2011

Core Java Interview Questions - Objects

The following are some questions you might encounter with respect to Java Objects in any Java Interview. Everything in Java is an Object and the term Objects includes a lot of concepts. The questions below can be used to test a programmers understanding of the basic Object concepts in Java.

Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Objects that you might find useful. You can use them to revise/review your understanding of Servlets.

They are:

Type-Casting
Constructors
Wrapper Classes


Questions:


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. Whereas, When you assign a subclass to a variable having a supeclass type, the casting happens automatically.

2. What's the difference between constructors and other methods?

Constructors must have the same name as the class and cannot return a value, whereas methods can have any name and can return any value.

Also, A constructor is called only called once when the class is instantiated, while methods could be called many times.

3. Can you call one specific constructor of a class, when it has multiple constructors

Yes. Use this() syntax and pass the arguments pertaining to the constructor you wish to invoke

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

Use the super.xxx(); syntax to call methods of the super class and to just call the constructor use super();

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

hashCode()

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

Have the class implement Cloneable interface and call its clone() method. If the class doesnt implement the interface and still the clone() is called, you will get an exception.

7. Describe the wrapper classes in Java ?

Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type and creates an Object.

Ex: java.lang.Boolean is the Wrapper for boolean, java.lang.Long is the wrapper for long etc.

8. Which class is extended by all other classes?

The Object class is extended by all other classes.

9. Does a class inherit the constructors of its superclass?

A class does not inherit constructors from any of its superclasses. But, a class can invoke the constructors of its super class by calling super();

10. 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 coded by the programmer who created the class.

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

12. How are this and super used?

this is used to refer to the current object instance. super is used to refer to the variables and methods of the superclass of the current object instance.

13. When a new object of derived Class is created, whose constructor will be called first, childs or parents

Even when the new object of child class is created, first the Base class constructor gets executed and then the child classes constructor. This is because, super() is the first line of code in any constructor and so, classes get created top to bottom and hence, the constructor of the Object class gets created first and then all the other classes in the hierarchy.

14. Can constructors be overloaded

Yes.

15. If you use super() or this() in a constructor where should it appear in the constructor

It should always be the first statement in the constructor and a point to note is, you cannot have both super() and this() in the same constructor for a simple reason - you cannot have two first lines in a method.

16. What is the ultimate ancestor of all java classes

Object class is the ancestor of all the java classes

17. What are important methods of Object class

wait(), notify(), notifyAll(), equals(), toString().


If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on Objects that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.

More Java & J2EE Interview Questions with Answers - Click Here
© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers