java interview for all

59
JAVA Interview 2013 2013 2013 2013 IIMT [ Learn Java core concepts and design/coding issues ]

Upload: pragati-singh

Post on 16-Apr-2017

134 views

Category:

Education


1 download

TRANSCRIPT

JAVA Interview

2013201320132013

IIMT

[ Learn Java core concepts and design/coding issues ]

1

Learn Java core concepts and design/coding issues

With

Java Job Interview Companion

By

Pragati Singh

MCA Deptt,IIMT Gr Noida

Technical Reviewers

Akhter Ali Ansari

Acknowledgements

Bhoopendra Modanwal

Cover Design

Mani Tiiwari

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

1. Are true and false keywords?

Answer

The values true and false are not keywords.

2. What do you mean by platform independence?

Answer

Platform independence means that we can write and compile the java code in one platform (eg

Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc).

3. Are JVM's platform independent?

Answer

JVM's are not platform independent. JVM's are platform specific run time implementation provided

by the vendor.

4. What is a JVM?

Answer

JVM is Java Virtual Machine which is a run time environment for the compiled java class files.

5. What is the difference between a JDK and a JVM?

Answer

JDK is Java Development Kit which is for development purpose and it includes execution environment

also. But JVM is purely a run time environment and hence you will not be able to compile your source

files using a JVM.

6. What is a pointer and does Java support pointers?

Answer

Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory

leaks and reliability issues hence Java doesn't support the usage of pointers.

7. What is the base class of all classes?

Answer

java.lang.Object

8. Does Java support multiple inheritance?

Answer

Java doesn't support multiple inheritance.

9. Is Java a pure object oriented language?

Answer

Java uses primitive data types and hence is not a pure object oriented language.

10. Are arrays primitive data types?

Answer

In Java, Arrays are objects.

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

11. What is difference between Path and Classpath?

Answer

Path and Classpath are operating system level environment variales. Path is used define where the

system can find the executables(.exe) files and classpath is used to specify the location .class files.

12. What are local variables?

Answer

Local varaiables are those which are declared within a block of code like methods. Local variables

should be initialised before accessing them.

13. What are instance variables?

Answer

Instance variables are those which are defined at the class level. Instance variables need not be

initialized before using them as they are automatically initialized to their default values.

15. Should a main method be compulsorily declared in all java classes?

Answer

No not required. main method should be defined only if the source class is a java application.

16. What is the return type of the main method?

Answer

Main method doesn't return anything hence declared void.

17. Why is the main method declared static?

Answer

main method is called by the JVM even before the instantiation of the class hence it is declared as

static.

18. What is the arguement of main method?

Answer

main method accepts an array of String object as arguement.

19. Can a main method be overloaded?

Answer

Yes. You can have any number of main methods with different method signature and implementation

in the class.

20. Can a main method be declared final?

Answer

Yes. Any inheriting class will not be able to have it's own default main method.

21. Does the order of public and static declaration matter in main method?

Answer

No it doesn't matter but void should always come before main().

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

22. Can a source file contain more than one Class declaration?

Answer

Yes a single source file can contain any number of Class declarations but only one of the class can

be declared as public.

23. What is a package?

Answer

Package is a collection of related classes and interfaces. package declaration should be first statement

in a java class.

24. Which package is imported by default?

Answer

java.lang package is imported by default even without a package declaration.

25. Can a class declared as private be accessed outside it's package?

Answer

Not possible.

26. Can a class be declared as protected?

Answer

A class can't be declared as protected. only methods can be declared as protected.

27. What is the access scope of a protected method?

Answer

A protected method can be accessed by the classes within the same package or by the subclasses of

the class in any package.

28. What is the purpose of declaring a variable as final?

Answer

A final variable's value can't be changed. final variables should be initialized before using them.

29. What is the impact of declaring a method as final?

Answer

A method declared as final can't be overridden. A sub-class can't have the same method signature

with a different implementation.

30. I don't want my class to be inherited by any other class. What should i do?

Answer

You should declared your class as final. But you can't define your class as final, if it is an abstract

class. A class declared as final can't be extended by any other class.

31. Can you give few examples of final classes defined in Java API?

Answer

java.lang.String,java.lang.Math are final classes.

32. How is final different from finally and finalize?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

final is a modifier which can be applied to a class or a method or a variable. final class can't be

inherited, final method can't be overridden and final variable can't be changed.

finally is an exception handling code section which gets executed whether an exception is raised or

not by the try block code segment.

finalize() is a method of Object class which will be executed by the JVM just before garbage collecting

object to give a final chance for resource releasing activity.

33. Can a class be declared as static?

Answer

No a class cannot be defined as static. Only a method,a variable or a block of code can be declared

as static.

34. When will you define a method as static?

Answer

When a method needs to be accessed even before the creation of the object of the class then we

should declare the method as static.

35. What are the restriction imposed on a static method or a static block of code?

Answer

A static method should not refer to instance variables without creating an instance and cannot use

"this" operator to refer the instance.

36. I want to print "Hello" even before main is executed. How will you acheive that?

Answer

Print the statement inside a static block of code. Static blocks get executed when the class gets

loaded into the memory and even before the creation of an object. Hence it will be executed before

the main method. And it will be executed only once.

37. What is the importance of static variable?

Answer

static variables are class level variables where all objects of the class refer to the same variable. If

one object changes the value then the change gets reflected in all the objects.

38. Can we declare a static variable inside a method?

Answer

Static variables are class level variables and they can't be declared inside a method. If declared, the

class will not compile.

39. What is an Abstract Class and what is it's purpose?

Answer

A Class which doesn't provide complete implementation is defined as an abstract class. Abstract

classes enforce abstraction.

40. Can a abstract class be declared final?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

Not possible. An abstract class without being inherited is of no use and hence will result in compile

time error.

41. What is use of a abstract variable?

Answer

Variables can't be declared as abstract. only classes and methods can be declared as abstract.

42. Can you create an object of an abstract class?

Answer

Not possible. Abstract classes can't be instantiated.

43. Can a abstract class be defined without any abstract methods?

Answer

Yes it's possible. This is basically to avoid instance creation of the class.

44. Class C implements Interface I containing method m1 and m2 declarations. Class C has provided

implementation for method m2. Can i create an object of Class C?

Answer

No not possible. Class C should provide implementation for all the methods in the Interface I. Since

Class C didn't provide implementation for m1 method, it has to be declared as abstract. Abstract

classes can't be instantiated.

45. Can a method inside a Interface be declared as final?

Answer

No not possible. Doing so will result in compilation error. public and abstract are the only applicable

modifiers for method declaration in an interface.

46. Can an Interface implement another Interface?

Answer

Intefaces doesn't provide implementation hence a interface cannot implement another interface.

47. Can an Interface extend another Interface?

Answer

Yes an Interface can inherit another Interface, for that matter an Interface can extend more than

one Interface.

48. Can a Class extend more than one Class?

Answer

Not possible. A Class can extend only one class but can implement any number of Interfaces.

49. Why is an Interface be able to extend more than one Interface but a Class can't extend more than

one Class?

Answer

Basically Java doesn't allow multiple inheritance, so a Class is restricted to extend only one Class.

But an Interface is a pure abstraction model and doesn't have inheritance hierarchy like classes(do

remember that the base class of all classes is Object). So an Interface is allowed to extend more

than one Interface.

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

50. Can an Interface be final?

Answer

Not possible. Doing it will result in compilation error.

51. Can a class be defined inside an Interface?

Answer

Yes it's possible.

51. Can a class be defined inside an Interface?

Answer

Yes it's possible.

53. What is a Marker Interface?

Answer

An Interface which doesn't have any declaration inside but still enforces a mechanism.

54. Which OO Concept is achieved by using overloading and overriding?

Answer

Polymorphism.

55. If i only change the return type, does the method become overloaded?

Answer

No it doesn't. There should be a change in method arguements for a method to be overloaded.

56. Why does Java not support operator overloading?

Answer

Operator overloading makes the code very difficult to read and maintain. To maintain code simplicity,

Java doesn't support operator overloading.

57. Can we define private and protected modifiers for variables in interfaces?

Answer

No

58. What is Externalizable?

Answer

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)

59. What modifiers are allowed for methods in an Interface?

Answer

Only public and abstract modifiers are allowed for methods in interfaces.

60. What is a local, member and a class variable?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

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.

61. What is an abstract method?

Answer

An abstract method is a method whose implementation is deferred to a subclass.

62. What value does read() return when it has reached the end of a file?

Answer

The read() method returns -1 when it has reached the end of a file.

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

Answer

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

64. What is the difference between a static and a non-static inner class?

Answer

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.

65. What is an object's lock and which object's have locks?

Answer

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.

66. What is the % operator?

Answer

It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first

operand by the second operand.

67. When can an object reference be cast to an interface reference?

Answer

An object reference be cast to an interface reference when the object implements the referenced

interface.

68. Which class is extended by all other classes?

Answer

The Object class is extended by all other classes.

68. Which class is extended by all other classes?

Answer

The Object class is extended by all other classes.

69. Which non-Unicode letter characters may be used as the first character of an identifier?

Answer

The non-Unicode letter characters $ and _ may appear as the first character of an identifier.

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

70. What restrictions are placed on method overloading?

Answer

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

71. What is transient variable?

Answer

Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable

class and the class is written to an ObjectStream, the value of the variable can't be written to the

stream instead when the class is retrieved from the ObjectStream the value of the variable becomes

null.

72. What is Collection API?

Answer

The Collection API is a set of classes and interfaces that support operation on collections of objects.

These classes and interfaces are more flexible, more powerful, and more regular than the vectors,

arrays, and hashtables if effectively replaces.

Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.

Example of interfaces: Collection, Set, List and Map.

73. What is casting?

Answer

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.

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

Answer

void.

75. If a variable is declared as private, where may the variable be accessed?

Answer

A private variable may only be accessed within the class in which it is declared.

76. What do you understand by private, protected and public?

Answer

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.

77. What is Downcasting ?

Answer

Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy.

78. What modifiers may be used with an inner class that is a member of an outer class?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

79. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?

Answer

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.

80. What restrictions are placed on the location of a package statement within a source code file?

Answer

A package statement must appear as the first line in a source code file (excluding blank lines and

comments).

81. What is a native method?

Answer

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

82. What are order of precedence and associativity, and how are they used?

Answer

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.

83. Can an anonymous class be declared as implementing an interface and extending a class?

Answer

An anonymous class may implement an interface or extend a superclass, but may not be declared

to do both.

84. What is the range of the char type?

Answer

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

85. What is the range of the short type?

Answer

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

86. Why isn't there operator overloading?

Answer

Because C++ has proven by example that operator overloading makes code almost impossible to

maintain.

87. What does it mean that a method or field is "static"?

Answer

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.

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

88. Is null a keyword?

Answer

The null value is not a keyword.

89. Which characters may be used as the second character of an identifier,but not as the first

character of an identifier?

Answer

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.

90. Is the ternary operator written x : y ? z or x ? y : z ?

Answer

It is written x ? y : z.

91. How is rounding performed under integer division?

Answer

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

92. If a class is declared without any access modifiers, where may the class be accessed?

Answer

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.

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

Answer

A class does not inherit constructors from any of its superclasses.

95. What restrictions are placed on the values of each case of a switch statement?

Answer

During compilation, the values of each case of a switch statement must evaluate to a value that can

be promoted to an int value.

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

Answer

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.

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

Answer

A local inner class may be final or abstract.

98. When does the compiler supply a default constructor for a class?

Answer

The compiler supplies a default constructor for a class if no other constructors are provided.

99. If a method is declared as protected, where may the method be accessed?

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

Answer

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.

100. What are the legal operands of the instanceof operator?

Answer

The left operand is an object reference or null value and the right operand is a class, interface, or

array type.

101. Are true and false keywords?

Answer

The values true and false are not keywords.

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

Answer

The result is a String object.

103. What is the diffrence between inner class and nested class?

Answer

When a class is defined within a scope od another class, then it becomes inner class. If the access

modifier of the inner class is static, then it becomes nested class.

104. Can an abstract class be final?

Answer

An abstract class may not be declared as final.

105. What is numeric promotion?

Answer

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.

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

Answer

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

of its package.

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

Answer

The default value of the boolean type is false

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

Answer

The prefix form performs the increment operation and returns the value of the increment operation.

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

operation on that value.

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

109. What restrictions are placed on method overriding?

Answer

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. The overriding method may not throw

any exceptions that may not be thrown by the overridden method.

110. What is a Java package and how is it used?

Answer

A Java package is a naming context for classes and interfaces. A package is used to create a separate

name space for groups of classes and interfaces. Packages are also used to organize related classes

and interfaces into a single API unit and to control accessibility to these classes and interfaces.

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

Answer

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

112. What is the difference between an if statement and a switch statement?

Answer

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.

113. Can a method be overloaded based on different return type but same argument type ?

Answer

No, because the methods can be called without using their return type in which case there is

ambiquity for the compiler

114. What happens to a static var that is defined within a method of a class ?

Answer

Can't do it. You'll get a compilation error

115. How many static init can you have ?

Answer

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.

116. What is the difference between method overriding and overloading?

Answer

Overriding is a method with the same name and arguments as in a parent, whereas overloading is

the same method name but different arguments

117. What is constructor chaining and how is it achieved in Java ?

Answer

A child object constructor always first needs to construct its parent (which in turn calls its parent

constructor.). In Java it is done via an implicit call to the no-args constructor as the first statement.

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

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

Answer

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.

119. Which Java operator is right associative?

Answer

The = operator is right associative.

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

Answer

Yes, a double value can be cast to a byte.

121. What is the difference between a break statement and a continue statement?

Answer

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.

122. Can a for statement loop indefinitely?

Answer

Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;

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

Answer

The default value of an String type is null.

124. What is the difference between a field variable and a local variable?

Answer

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.

125. How are this() and super() used with constructors?

Answer

this() is used to invoke a constructor of the same class. super() is used to invoke a superclass

constructor.

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

Answer

A final class cannot be inherited. A final method cannot be overridden in a subclass. A final field

cannot be changed after it's initialized, and it must include an initializer statement where it's declared.

127. What does it mean that a method or class is abstract?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

An abstract class cannot be instantiated. 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 it also

should be declared abstract.

128. Can an anonymous class be declared as implementing an interface and extending a class?

Answer

An anonymous class may implement an interface or extend a superclass, but may not be declared

to do both.

129. What is the catch or declare rule for method declarations?

Answer

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.

130. What are some alternatives to inheritance?

Answer

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

131. What are the different identifier states of a Thread?

Answer

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.

132. What is garbage collection? What is the process that is responsible for doing that in java?

Answer

Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this

process.

133. What kind of thread is the Garbage collector thread?

Answer

It is a daemon thread.

134. What is a daemon thread?

Answer

These are the threads which can run without user intervention. The JVM can exit when there are

daemon thread by killing them abruptly.

135. How will you invoke any external process in Java?

Answer

Runtime.getRuntime().exec(….)

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

136. What is the finalize method do?

Answer

Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some

resources before it got garbage collected.

137. What is mutable object and immutable object?

Answer

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, …)

138. What is the basic difference between string and stringbuffer object?

Answer

String is an immutable object. StringBuffer is a mutable object.

139. What is the purpose of Void class?

Answer

The Void class is an uninstantiable placeholder class to hold a reference to the Class object

representing the primitive Java type void.

140. What is reflection?

Answer

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.

141. What is the base class for Error and Exception?

Answer

Throwable

142. What is the byte range?

Answer

128 to 127

143. What is the implementation of destroy method in java.. is it native or java code?

Answer

This method is not implemented.

144. What are the approaches that you will follow for making a program very efficient?

Answer

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.

145. What is a DatabaseMetaData?

Answer

Comprehensive information about the database as a whole.

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

146. What is Locale?

Answer

A Locale object represents a specific geographical, political, or cultural region.

147. How will you load a specific locale?

Answer

Using ResourceBundle.getBundle(…);

148. What is JIT and its use?

Answer

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.

149. Is JVM a compiler or an interpreter?

Answer

Interpreter

150. What is the purpose of assert keyword used in JDK1.4.x?

Answer

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.

151. How will you get the platform dependent values like line separator, path separator, etc., ?

Answer

Using Sytem.getProperty(…) (line.separator, path.separator, …)

152. Is "abc" a primitive value?

Answer

The String literal “abc” is not a primitive value. It is a String object.

153. What is singleton?

Answer

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 … }

154. Can you instantiate the Math class?

Answer

You can’t instantiate the math class. All the methods in this class are static. And the constructor is

not public.

155. What are the methods in Object?

Answer

clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString.

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

156. What is aggregation?

Answer

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.

157. What is composition?

Answer

Holding the reference of the other class within some other class is known as composition.

158. What is inner class?

Answer

If the methods of the inner class can only be accessed via the instance of the inner class, then it is

called inner class.

159. What is nested class?

Answer

If all the methods of a inner class is static then it is a nested class.

160. What is the major difference between LinkedList and ArrayList?

Answer

LinkedList are meant for sequential accessing. ArrayList are meant for random accessing.

161. What is the significance of ListIterator?

Answer

You can iterate back and forth.

162. What is the final keyword denotes?

Answer

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.

163. What is skeleton and stub? what is the purpose of those?

Answer

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.

164. Why does it take so much time to access an Applet having Swing Components the first time?

Answer

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.

165. What is the difference between instanceof and isInstance?

Answer

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

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

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.

166. What does the "final" keyword mean in front of a variable? A method? A class?

Answer

FINAL for a variable: value is constant. FINAL for a method: cannot be overridden. FINAL for a class:

cannot be derived.

167. Describe what happens when an object is created in Java?

Answer

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.

168. What is the difference amongst JVM Spec, JVM Implementation, JVM Runtime ?

Answer

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.

169. How does Java handle integer overflows and underflows?

Answer

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

operation.

170. Why are there no global variables in Java?

Answer

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.

171. Whats the difference between notify() and notifyAll()?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

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

172. How can my application get to know when a HttpSession is removed?

Answer

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.

173. What interface must an object implement before it can be written to a stream as an object?

Answer

An object must implement the Serializable or Externalizable interface before it can be written to a

stream as an object.

174. What is your platform's default character encoding?

Answer

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.

175. What an I/O filter?

Answer

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.

176. What is the purpose of finalization?

Answer

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup

processing before the object is garbage collected.

177. Which class should you use to obtain design information about an object?

Answer

The Class class is used to obtain information about an object’s design.

178. What is the purpose of the System class?

Answer

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

179. Can we use the constructor, instead of init(), to initialize servlet?

Answer

Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you

shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke

constructors with arguments, so there was no way to give the constructur a ServletConfig. That no

longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have

access to a ServletConfig or Servlet Context.

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

180. How can a servlet refresh automatically if some new data has entered the database?

Answer

You can use a client-side Refresh or Server Push.

181. The code in a finally clause will never fail to execute, right?

Answer

Using System.exit(1); in try block will not allow finally code to execute.

182. How many messaging models do JMS provide for and what are they?

Answer

JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.

183. What information is needed to create a TCP Socket?

Answer

The Local System?s IP Address and Port Number. And the Remote System’s IPAddress and Port

Number.

184. What Class.forName will do while loading drivers?

Answer

It is used to create an instance of a driver and register it with the DriverManager. When you have

loaded a driver, it is available for making a connection with a DBMS.

185. How many JSP scripting elements are there and what are they?

Answer

There are three scripting language elements: declarations, scriptlets, expressions.

186. What are stored procedures? How is it useful?

Answer

A stored procedure is a set of statements/commands which reside in the database. The stored

procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements

everytime a query is run. Each database has its own stored procedure language, usually a variant of

C with a SQL preproceesor. Newer versions of db’s support writing stored procedures in Java and

Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to

implement the business logic( A lot of systems still do it). The biggest advantage is of course speed.

Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism

to do these manipulations. Stored procs are also useful when you want to do Batch

updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be

significant in these cases.

187. How do I include static files within a JSP page?

Answer

Static resources should always be included using the JSP include directive. This way, the inclusion is

performed just once during the translation phase. Do note that you should always supply a relative

URL for the file attribute. Although you can also include static resources using the action, this is not

advisable as the inclusion is then performed for each and every request.

188. Why does JComponent have add() and remove() methods but Component does not?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

Because JComponent is a subclass of Container, and can contain other components and jcomponents.

189. How can I implement a thread-safe JSP page?

Answer

You can make your JSPs thread-safe by having them implement the SingleThreadModel interface.

This is done by adding the directive <%@ page isThreadSafe="false" % > within your JSP page.

190. What is the difference between procedural and object-oriented programs?

Answer

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.

191. What are Encapsulation, Inheritance and Polymorphism?

Answer

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.

192. What is the difference between Assignment and Initialization?

Answer

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

193. What is OOPs?

Answer

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.

194. What are Class, Constructor and Primitive data types?

Answer

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.

195. What is an Object and how do you allocate memory to it?

Answer

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.

196. What is the difference between constructor and method?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

Constructor will be automatically invoked when an object is created whereas method has to be called

explicitly.

197. What are methods and how are they defined?

Answer

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.

198. What is the use of bin and lib in JDK?

Answer

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

packages.

199. How many ways can an argument be passed to a subroutine and explain them?

Answer

An argument can be passed in two ways.

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.

200. What is the difference between an argument and a parameter?

Answer

While defining method, variables passed in the method are called parameters. While using those

methods, values passed to those variables are called arguments.

201. How would you implement a thread pool?

Answer

The ThreadPool class is a generic implementation of a thread pool, which takes the following input

Size of the pool to be constructed and name of the class which implements Runnable (which has a

visible default constructor) and constructs a thread pool with active threads that are waiting for

activation. once the threads have finished processing they come back and wait once again in the

pool.

202. What are the advantages and disadvantages of reference counting in garbage collection?

Answer

An advantage of this scheme is that it can run in small chunks of time closely linked with the execution

of the program. These characteristic makes it particularly suitable for real-time environments where

the program can't be interrupted for very long time. A disadvantage of reference counting is that it

does not detect cycles. A cycle is two or more objects that refer to one another. Another disadvantage

is the overhead of incrementing and decrementing the reference count each time. Because of these

disadvantages, reference counting currently is out of favor.

203. Why java is said to be pass-by-value ?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

When assigning an object to a variable, we are actually assigning the memory address of that object

to the variable. So the value passed is actually the memory location of the object. This results in

object aliasing, meaning you can have many variables referring to the same object on the heap.

204. What are the access modifiers available in Java?

Answer

Access modifier specify where a method or attribute can be used.

� Public is accessible from anywhere.

� Protected is accessible from the same class and its subclasses.

� Package/Default are accessible from the same package.

� Private is only accessible from within the class.

205. What is the difference between a switch statement and an if statement?

� Answer

� If statement is used to select from two alternatives. It uses a boolean expression to decide

which alternative should be executed. The expression in if must be a boolean value. The switch

statement is used to select from multiple alternatives. The case values must be promoted to

an to int value.

206. What are synchronized methods and synchronized statements?

Answer

Synchronized methods are methods that are declared with the keyword synchronized. thread

executes a synchronized method only after it has acquired the lock for the method's object or

class. Synchronized statements are similar to synchronized methods. It is a block of code

declared with synchronized keyword. A synchronized statement can be executed only after a

thread has acquired the lock for the object or class referenced in the synchronized statement.

207. What are the different ways in which a thread can enter into waiting state?

Answer

There are three ways for a thread to enter into 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() metho

208. What is the difference between static and non static variables ?

Answer

A static variable is associated with the class as a whole rather than with specific instances of a class.

There will be only one value for static variable for all instances of that class. Non-static variables take

on unique values with each object instance.

209. What is the difference between notify and notifyAll method?

Answer

notify wakes up a single thread that is waiting for object's monitor. If any threads are waiting on this

object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of

the implementation. notifyAll Wakes up all threads that are waiting on this object's monitor. A thread

waits on an object's monitor by calling one of the wait methods.

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

210. What are different type of exceptions in Java?

Answer

There are two types of exceptions in java. Checked exceptions and Unchecked exceptions. Any

exception that is is derived from Throwable and Exception is called checked exception except

RuntimeException and its sub classes. The compiler will check whether the exception is caught or

not at compile time. We need to catch the checked exception or declare in the throws clause. Any

exception that is derived from Error and Runtime Exception is called unchecked exception. We don't

need to explicitly catch a unchecked exception.

211. Explain about the select method with an example?

Answer

Select part is useful in selecting text or part of the text. Arguments specified for the select command

are the same as applicable to substring. First index is usually represents the start of the index. End

of line makers are counted as one character. Example t.select (10,15) .

212. Can there be an abstract class with no abstract methods in it?

Answer

Yes.

213. Can we define private and protected modifiers for variables in interfaces?

Answer

No.

214. What is garbage collection? What is the process that is responsible for doing that in java?

Answer

Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this

process.

215. Can there be an abstract class with no abstract methods in it?

Answer

Yes.

216. Can an Interface have an inner class?

Answer

Yes.

public interface abc {

static int i=0;

void dd();

class a1 {

a1() {

int j;

System.out.println("in interfia");

};

public static void main(String a1[]) {

System.out.println("in interfia"); } } }

217. What is user defined exception?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

Apart from the exceptions already defined in Java package libraries, user can define his own exception

classes by extending Exception class.

218. What is the difference between logical data independence and physical data independence?

Answer

Logical Data Independence - meaning immunity of external schemas to changed in conceptual

schema.

Physical Data Independence - meaning immunity of conceptual schema to changes in the internal

schema.

219. What are the practical benefits, if any, of importing a specific class rather than an entire package

(e.g. import java.net.* versus import java.net.Socket)?

Answer

It makes no difference in the generated class files since only the classes that are actually used are

referenced by the generated class file. There is another practical benefit to importing single classes,

and this arises when two (or more) packages have classes with the same name. Take java.util.Timer

and javax.swing.Timer, for example. If I import java.util.* and javax.swing.* and then try to use

"Timer", I get an error while compiling (the class name is ambiguous between both packages). Let’s

say what you really wanted was the javax.swing.Timer class, and the only classes you plan on using

in java.util are Collection and HashMap. In this case, some people will prefer to import

java.util.Collection and import java.util.HashMap instead of importing java.util.*. This will now allow

them to use Timer, Collection, HashMap, and other javax.swing classes without using fully qualified

class names in.

220. How many methods do u implement if implement the Serializable Interface?

Answer

The Serializable interface is just a "marker" interface, with no methods of its own to implement.

Other ’marker’ interfaces are

java.rmi.Remote

java.util.EventListener

221. What does the "abstract" keyword mean in front of a method? A class?

Answer

Abstract keyword declares either a method or a class. If a method has a abstract keyword in front of

it,it is called abstract method.Abstract method has no body.It has only arguments and return

type.Abstract methods act as placeholder methods that are implemented in the subclasses.

Abstract classes can’t be instantiated.If a class is declared as abstract,no objects of that class can be

created.If a class contains any abstract method it must be declared as abstract.

222. You can create a String object as String str = "abc"; Why cant a button object be created as

Button bt = "abc";? Explain

Answer

The main reason you cannot create a button by Button bt= "abc"; is because "abc" is a literal string

(something slightly different than a String object, by-the-way) and bt is a Button object. The only

object in Java that can be assigned a literal String is java.lang.String. Important to note that you are

NOT calling a java.lang.String constuctor when you type String s = "abc";

223. Can RMI and Corba based applications interact ?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

Yes they can. RMI is available with IIOP as the transport protocol instead of JRMP.

224. What is passed by reference and pass by value ?

Answer

All Java method arguments are passed by value. However, Java does manipulate objects by

reference, and all object variables themselves are references.

225. What is a "stateless" protocol ?

Answer

Without getting into lengthy debates, it is generally accepted that protocols like HTTP are stateless

i.e. there is no retention of state between a transaction which is a single request response

combination.

226. Difference between a Class and an Object ?

Answer

A class is a definition or prototype whereas an object is an instance or living representation of the

prototype.

227. What are the four corner stones of OOP?

Answer

Abstraction, Encapsulation, Polymorphism and Inheritance.

228. What gives java it's "write once and run anywhere" nature?

Answer

Java is compiled to be a byte code which is the intermediate language between source code and

machine code. This byte code is not platorm specific and hence can be fed to any platform. After

being fed to the JVM, which is specific to a particular operating system, the code platform specific

machine code is generated thus making java platform independent.

229. How can a dead thread be restarted?

Answer

A dead thread cannot be restarted.

230. What happens if an exception is not caught?

Answer

An uncaught exception results in the uncaughtException() method of the thread’s ThreadGroup being

invoked, which eventually results in the termination of the program in which it is thrown.

231. What is a compilation unit?

Answer

A compilation unit is a Java source code file.

232. What is a task's priority and how is it used in scheduling?

Answer

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.

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

233. What value does readLine() return when it has reached the end of a file?

Answer

The readLine() method returns null when it has reached the end of a file.

234. Can an object's finalize() method be invoked while it is reachable?

Answer

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.

235. Does garbage collection guarantee that a program will not run out of memory?

Answer

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.

236. Is sizeof a keyword?

Answer

The sizeof operator is not a keyword.

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

Answer

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

238. Can a lock be acquired on a class?

Answer

Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object.

239. How are Observer and Observable used?

Answer

Objects that subclass the Observable class maintain a list of observers. When an Observable object

is updated it invokes the update() method of each of its observers to notify the observers that it has

changed state. The Observer interface is implemented by objects that observe Observable objects.

240. what is a transient variable?

Answer

transient variable is a variable that may not be serialized.

242. What are E and PI?

Answer

E is the base of the natural logarithm and PI is mathematical value pi.

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

Answer

Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.

244. Can an exception be rethrown?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

Yes, an exception can be rethrown.

245. What is the purpose of the File class?

Answer

The File class is used to create objects that provide access to the files and directories of a local file

system.

246. Is a class subclass of itself?

Answer

No. A class is not a subclass of itself.

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

Answer

An interface may be declared as public or abstract.

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

Answer

A catch clause can catch any exception that may be assigned to the Throwable type. This includes

the Error and Exception types.

249. What is the difference between the Reader/Writer class hierarchy and the

InputStream/OutputStream class hierarchy?

Answer

The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class

hierarchy is byte-oriented.

250. Can an object be garbage collected while it is still reachable?

Answer

A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.

251. What is an object's lock and which object's have locks?

Answer

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.

252. How are commas used in the intialization and iteration parts of a for statement?

Answer

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

statement.

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

Answer

It must provide all of the methods in the interface and identify the interface in its implements clause.

254. What is the difference between preemptive scheduling and time slicing?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

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.

255. What restrictions are placed on the location of a package statement within a source code file?

Answer

A package statement must appear as the first line in a source code file (excluding blank lines and

comments).

256. What are wrapped classes?

Answer

Wrapped classes are classes that allow primitive types to be accessed as objects.

257. Is it possible to specify multiple JNDI names when deploying an EJB?

Answer

No. To achieve this you have to deploy your EJB multiple times each specifying a different JNDI name.

258. What is JAVA and their uses?

Answer

Java is an object-programming language that was designed to be portable across multiple platforms

and operating systems. Developed by Sun Microsystems, Java is modeled after the C++

programming language and includes special features that make it ideal for programs on the Internet.

Still, you may be wondering why Java is suddenly receiving so much hype, and what possible

improvements could have been made to this new language so as to push aside a well-established

language such as C++.

First and foremost, Java makes it easy to put interactive graphics and other special effects on a World

Wide Web page. As with any programming language, Java lets you write programs. Special Java

programs, called applets, execute inside a Web page with a capacity matching that of any traditional

program. Furthermore, when you run a Java applet, the remote server, Java transmits the applet to

your browser across the Internet. So rather than going out to a computer store to buy software, Java

applets let you download applications automatically when you need them.

259. What is HotJava?

Answer

Programmers often mention the name "HotJava" in the same breath as Java. Whereas Java is a

programming language, HotJava was the first Web browser that could download and play (execute)

Java applets. HotJava, created by Sun, is simply a browser, much like the Netscape Navigator or

Microsoft's Internet Explorer.

Although HotJava was the first browser to support Java applets, many browsers now support or will

soon support applets. Starting with Netscape Navigator 2.0, for example, you can play Java applets

for many platforms (Windows 95, the Mac, and so on). Another distinguishing feature of HotJava is

that unlike most browsers which are written in C/C++, the HotJava browser is written with the Java

programming language.

260. How can you say Java is Object Oriented?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

Java is an object-oriented programming language which means you can use Java to develop your

programs in terms of data and the methods (functions) that operate on the data. In Java, a class is

a collection of the data and methods which describe an object with which your program works. Think

of an object as a "thing," such as a graphics image, a dialog box, or a file.

Java applets can arrange classes in hierarchical fashion which means you can build new classes from

existing classes, improving upon or extending the existing class's capabilities. Everything in Java,

except for a few primitive types such as numbers, characters, and boolean (true and false) types, is

an object. Java comes with an extensive set of classes that you can use in your programs. In fact, a

Java applet itself is a Java class.

261. Why Java is Platform Independent? Explain.

Answer

When you write and compile a Java applet, you end up with a platform-independent file called a

bytecode. Like a standard program, a bytecode consists of ones and zeros. Unlike a standard

program, however, the bytecode is not processor specific. In other words, the bytecode does not

correspond to an Intel Pentium or a Motorola processor. Instead, after the server downloads the

bytecode to your browser, special code within the browser reads and interprets the bytecode, in turn

running the applet. To run the bytecode in this way, the interpreter translates the platform

independent ones and zeros into ones and zeros your computer's processor understands. In other

words, it maps the bytecode to ones and zeros that correspond to the current processor, such as a

Pentium.

Each computer platform (Mac, Windows, and so on) can have its own Java interpreter. However, the

bytecode file that the server downloads to each browser is identical. In this way, you use the same

bytecode on a browser running on a Mac, a PC, or a Silicon Graphics workstation. The multi-platform

bytecode file is just one aspect of Java's portability. Java's designers also took the extra effort to

remove any platform dependence in the Java language. Thus, you will not find any hardware specific

references in Java.

262. Why Java is Secure? Explain.

Answer

A computer virus is a program written by someone who to maliciously damage the files you have

stored on your disks or your computer's disk itself. To encounter a virus from across the Internet,

you must download and run a program. Unfortunately, with Java applets, a remote sever downloads

the applet to a browser on your system which, in turn, runs the applet. At first glance these

downloaded Java applets are an ideal way for malicious programmers to create viruses. Luckily, the

Java developers designed Java with networking in mind. Therefore, Java has several built-in security

defenses which reduce a programmer's ability to use Java to create a virus.

First, Java applets cannot read or write local files that reside on your disk. In this way, the applet

cannot store the virus on your disk or attach the virus to a file. That the applet simply cannot perform

disk input and output. Second, Java applets are "blind" to your computer's memory layout.

Specifically, Java applets do not have pointers to memory, and programmers cannot use this

traditional back door to your computer. Third, Java cannot use memory outside its own memory

space. By building these precautions into programming language itself, the Java developers have

greatly impaired Java's use in creating and transmitting computer viruses.

263. Why do people says "Java is Robust"?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

When people talk about code being robust, they are referring to the code's reliability. Although Java

has not eliminated unreliable code, it has made writing high-quality software easier. To begin, Java

eliminates many of the memory problems that are common in languages such as C and C++. Java

does not support direct access to pointers to memory. As a result, a Java applet cannot corrupt your

computer's memory. Also, Java performs run-time checks (while the applet is running) to make sure

that all array and string references are within each items's bounds. In other programming languages,

many software bugs result from the program not freeing memory that ought to be freed or freeing

the same memory more than once. Java, on the other hand, performs automatic garbage collection

(which releases unused memory), eliminating the program's need to free unused memory.

Next, Java is more strongly typed than C++ and requires method declarations, which reduces the

potential for type-mismatch errors. Finally, Java institutes an error trapping method known as

exception handling. When a program error occurs Java signals the program with an exception, which

provides the program with a chance to recover from the error- and warns the user that something

caused a specific operation to fail.

264. How Java is similar to C?

Answer

If you are already familiar with C/C++, you will find that Java is actually a simpler language to

master. Java incorporates the basic tenets of object-oriented design, yet it eliminates some of the

more complicated of the other language, such as multiple inheritance and templates. Many of the

language keywords are the same or have only minor differences, which increases portability.

If you are a C programmer dreading the seemingly inevitable push toward C++, you may rejoice

over Java's cleaner approach to object-oriented programming. In fact, you want to skip C++

altogether and learn Java instead. Java's manageable selection of predefined classes are both useful

and easy to understand. Many of the common operations that may take you hundreds or thousands

of lines of code are already done for you. For example, you can write a simple network chat program

without having to know much about sockets, protocols, and other low-level network issues.

265. What's the difference between Applets and Standalone Program?

Answer

Sun designed Java from the start to fit hand-in-glove on the Internet. Applets are special Java

programs that execute from within a Web browser. In contrast, a Java application (an application

program as opposed to an applet) does not run within a browser. As it turns out, Java applets are

not much different from standalone Java application. You can start developing your Java program

from either an applet or an application and cross over any time. For example, assume that you are

writing a new Java-based application that is initially designed as a standalone (non-Internet) game

for Mac computers. At the end of your program's development cycle, you decide that you want it to

run on Web browsers. Your task to make it into a Web-based applet involves very trivial changes,

and the addition of some simple HTML code. At the same time, you will find that the game will also

run on computers other than Macs! The point you should remember is that Java applets run within

browsers across the Web, whereas Java application programs do not.

266. Why Java applets are more useful for Intranets as compared to Internet?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

An intranet is an in-house version of the Internet. An intranet uses the same technologies, software,

and equipment that the Internet uses (primarily TCP/IP). Whereas the Internet has information

servers miles away controlled by other organizations, your company controls the servers and client

computers inside your office in an intranet. During the past year, intranets have experienced

explosive popularity growth because they offer a very low cost way for companies to maintain and

distribute internal information in an easy-to-use format.

Because intranets work like the Internet, Java also finds a home on company intranets. All the

techniques that you will learn and, in fact the same applets that you will use for the Internet, may

be applied in your intranet. You may find that Java applets will help you solve special software

problems within the intranet. You can use applets to provide a friendly interface to company

databases, documentation stores, equipment controls, and so on, while running on any computer

from a Mac to a PC to a UNIX workstation.

267. How can you set the Applet Size?

Answer

Java applets run within their own window: Within your HTML file, you set the size of an applet window,

using the <APPLET> tag's WIDTH and HEIGHT attributes. The size values you specify for each

attribute are in pixels. For example, the following <APPLET> entry creates applet window that is 30

pixels tall by 100 pixels wide:

<APPLET CODE=clock.class WIDTH=100 HEIGHT=30> </APPLET>

268. How can you set an Applet's Height and Width as a Percentage?

Answer

You use the <APPLET> tag WIDTH and HEIGHT attributes to specify the pixel size of an applet

window. In addition to letting you specify the applet window size in terms of pixels, many browsers

let you specify the applet window's size as a percentage of the browser's window's size. You do this

by specifying a percentage value for the HEIGHT and WIDTH attributes within the <APPLET> tag.

For example, the following <APPLET> entry creates an applet window based on 50% of the height

and 100% of the width of the browser's window:

<applet code=test.class width=100% height=50%> </applet>.

269. What is Codebase?

Answer

The Java applets your browser executes reside in a file with the .class extension. When you create a

Web page, you can store you Java .class files in a directory which is different from the directory that

contains the page's HTML files. Within the HTML <APPLET> tag, you can use the CODEBASE attribute

to specify the directory within which the applet's .class files reside. The CODEBASE location can be

a directory on the same computer or a directory at another computer. The CODEBASE attribute

specifies (to the browser) the base URL (relative or specifies) of the directory that contain

the .class files. If an <APPLET> tag does not use the CODEBASEattribute, the browser uses the

current directory (the one containing the HTML file) to locate the .class files. The

following <APPLET> tag directs the browser to look for the applet files in the directory

called/server_a/applets.

<APPLET CODE="MyFirst.class"CODEBASE^"/server_a/applets" WIDTH=300

HEIGHT=300>.</APPLET>

270. What is Appletviewer?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

Most Java development environments include a special program called an appletviewer. using

the appletviewer,you can execute your applet just as if it were running within a Web page displayed

a browser. In most cases, the appletviewer can run your applet faster than a browser, making the

appletviewer convenient for testing your applet. As you develop your applet, you will want to run it

each time you add features. By using theappletviewer, you can quickly try out your applet without

starting your Java-enabled Web browser. You run theappletviewer that accompanies Sun's Java

Developer's Kit from the command line, specifying the name of the HTML file that contains

the <APPLET> entry for applet you want to view:

C:> appletviewer SomeFileName.HTML <ENTER>

271. Explain, Java is compatible with all Servers but not all Browsers?

Answer

When a Java applet runs over a network, two sides are working. One is the server, which is

responsible for maintaining and handling browser requests for the various files it controls. On the

server side, a Java applet is just a file like any other file an HTTP server already handles. You do not

need any special server software for Java since the real work of executing the Java applet is

performed by the browser, not the server.

On the other side is the client, or browser, which request, receives, and interprets files from the

server. The browser is responsible for displaying the Web page, playing sounds, running animations

and. in general, determining the type of data the server is sending and handling that data accordingly.

When a Web page contains a Java applet, the page's HTML file will contain an <APPLET> entry. If

the browser is Java-enabled, the browser will request the applet file from the server. The server, in

turn, will send the applet's bytecode to the browser, which will start its Java interpreter to execute

the code.

272. What is the Program Development Process?

Answer

� Depending on what development package you use to create your Java programs, will go about

compiling, organizing, and testing your programs in different ways. However, the general

development process is mostly the same no matter which package or platform you use.

� As discussed, the end result of the Java programs development process is a bytecode file which

the server downloads to the browser for interpretation and execution. When you compile your

Java source file, you are creating a bytecode file. Java source-code files, on the other hand,

contain the class definitions and program statements you write using the Java language. In

addition to the Java source-code files, you must create a small HTML file, which the browser

uses to invoke your applet.

� After the compiler creates the bytecode and you create an HTML file, you can test your applet

using either your browser or an appletviewer. If your applet contains errors, many Java

development environments provide a debugger program that you can use to track down the

errors. When you are ready to release your applet to the public, you must place the applet and a

corresponding HTML file on a Web server.

� Therefore, the general development cycle of a Java applet includes the creation of source-code

and HTML files, compiling the source into bytecode, testing the bytecode through an

appletviewer, detecting and removing any errors from the applet using a debugger and, finally,

releasing the applet for use on a Web server.

273. What is the File Type?

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

Answer

� When you create Java source-code files that contain classes and methods, you need to be aware

of the Java file-naming convention. Each Java source-code file must end with the Java

extension. In addition, the file's name must match the name of the public class the file defines.

For example, if your source-code file creates a class named MorphaMatic, your source-code file

must use the name MorphaMatic.java. As you can see, the letters of the source-code file name

must match the class name exactly, including the use of upper and lowercase letters.

� The HTML file that you use to run the applet can have any name. As a rule, however, you should

use the standard extension for your system, typically .html or .htm. Also, to help organize your

files, you may want to use a name similar to that of your applet for the HTML file name, such as

MorphaMatic. html.

� Finally, the bytecode file the Java compiler creates will have the .class extension. In this case,

the bytecode file will have the name MorphaMatic.class. As discussed, the .class file is the file

the Web server downloads to your browser which, in turn, interprets and executes the files's

contents.

274. What is javac_g?

Answer

As you have learned, the javac compiler examines your source-code files and produces the

bytecode .classfiles. As your Java applets become more complex, it may become difficult for you to

locate errors (bugs) within your code. To help you locate such errors, most Java development

environments provide a special debugger program. In the case of the Sun's Java Developer's Kit, the

debugger program is named jdb (for Java debugger). To provide jdb with more information to work

with, the Sun's JDK provides special version of the compiler named javac__g. Sun designed the javac

_g compiler for use with debuggers. Essentially, javacjg is a non-optimized version of

the javac compiler which place tables of information within the bytecode that the debugger can use

to track down errors. To compile a Java applet using the javac__g compiler, you simply specify the

applet source-file named within the javac^g command line, as shown here:

C:JAVACODE> javac „ g SomeFile.Java <Enter>

275. How to optimize the Javac Output?

Answer

When you compare the performance of a Java program against that of a C/C++ program, you will

find that the current generation of Java programs can be as much as twenty times slower than their

C/C++ counterparts. This performance loss is mostly due to the fact that the browser

musf interpret the Java bytecode and convert it into the computer's native code (such as a Pentium

or Motorola-specific code) before the code can run. In C/C++, the code is in the processor's native

format to begin with, so this time-consuming translation step is not required. Remember, however,

that Java's generic bytecode allows the same Java code to run on multiple platforms.

The Java designers are working on various solutions to speed up Java. In the meantime, you can use

the -Ocompiler switch with javac, which may increase the applet's performance. The -0 switch

directs javac to optimize its bytecode by "inlining" static, final and private methods. For now, don't

worry what "inlining" such code means other than it may improve your applet performance.

Unfortunately, when you use inlining, you may increase the size of your bytecode file, which will

increase the applet's download time. The following Javac command illustrates how you use the -0

switch:

C:JAVACODE> javac -O MyFirst.java <Enter>

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

276. What is the difference between Java Applets and Applications?

Answer

� With Java, you can create two types of programs: an applet or an application. As you have

learned, a Java applet is a program that executes from within a Web browser. A Java

application, on the other hand, is a program that is independent of the browser and can run as a

standalone program.

� Because an applet is run from within a Web browser, it has the advantage of having an existing

vindow and the ability to respond to user interface events provided though the browser. In

addition, because applets are designed for network use Java is much restrictive in the types of

access that applets can have to your file system than it is with non-network applications.

� As you will, when you write a Java application, you must specify a main method (much like the

C/ C++ main), which the program executes when it begins. Within the main method, you specify

the functionality that your application performs. With an applet, on the other hand, you need to

write additional methods that respond to events which are an important part of the applet's life

cycle. The methods include init, start, stop, destroy and paint. Each of these events has a

corresponding method and, when the event occurs, Java will call the appropriate method to

handle it.

� When you write your first Java programs, you can write them as if .they were applets and use

the appletviewer to execute them. As it turns out, you can later convert your applet to an

application by replacing your init method with a main method.

277. Can you explain the cs option of Java interpreter?

Answer

When you develop Java using Sun's JDK, you normally compile your source by using

the javac compiler. If no compile errors exist, you then run your application using the java interpreter.

As a shortcut, you can specify the -cs command-line switch when you invoke the java interpreter. The

java command, in turn, will automatically compile out-of-date (modified) source-code files for you.

By using the -cs switch, you can make changes to your source and immediately execute the

java interpreter without having to manually run the java compiler yourself. The java interpreter

knows which files it needs to recompile by comparing each file's modification dates against the

corresponding class modification date. Normally, programmers use the -cs option when they have

made a minor change to the source files and know that the files contain no compilation errors. The

following command illustrates the use of the -cs switch:

C: JAVACODE> Java -cs MyProgram <Enter>

278. What is the Statements?

Answer

A Java program consists of instructions that you want the computer to perform. Within a Java applet,

you use statements to express these instructions in a format the Java compiler understands. If you

are already familiar with C/C++, you will discover that Java statements are very similar. For example,

the following statements produce a programs which prints the words "Hello, Java!" in applet window:

import java.applet.*; import java.awt.Graphics;

public class hello_java extends Applet

{

public void paint(Graphics g)

{

g.drawstring("Hello, Java!", 20, 20);

}

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

}

279. What is Style and indentation?

Answer

As you write Java programs, you will discover that you have considerable flexibility in how you line

your statements and indent lines. Some editor programs help you line up indented lines and indent

new block. If you have already programmed in another language, you probably have your own style

of indentation. Java does not impose any specific style, However, you may want to be consistent with

your own style and always be conscious that a well-formatted program is easier to read and maintain.

For example, the following two programs function equivalently. However, one is much easier to read

than the other:

import java.applet. * ;

public class am_i_readable extends

Applet{public void init()

{

System.out.println("Can you guess whatI do?");

}

}

import java.applet.*;

public class am__i_readable extends Applet

{

public void init()

{

System.out.println("Can you guess what I do?");

}

}

280. What is the Program Compilation Process?

Answer

When you create programs, you will normally follow the same steps. To begin, you will use an editor

to create your source file. Next, you will compile the program using a Java compiler. If the program

contains syntax errors, you must edit the source file, correct the errors, and re-compile.

After the program successfully compiles, the compiler generates a new file, known as bytecode. By

using a Java interpreter, or appletviewer, you can execute the bytecode to test if it runs successfully.

If the program does not work as you expected, you must review the source code to locate the error.

After you correct the error, you must compile the source code to create a new byte code file. You

can then test the new program to ensure that it performs the desired task. This illustrates the

program development process.

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

281. What is Java Literals?

Answer

Literals correspond to a specific value in your Java program. For example, if you type the number 7

(the literal number 7) in a Java program, Java will treat the value as an int type. If you use the

character JC within single quotes (V), Java will treat it as a char type. Likewise, if you place the literal

x within double quotes Ox'), Java will treat it as a String. Depending on the literal you are using,

Java provides special rules for hexadecimal, octal, characters, strings and boolean values. As you

will learn, you can force a literal to be a certain type. For example, Java will treat the number 1 as

an int. But you can force Java to treat the value as the type long by appending the L character to the

literal number: 1L.

282. What is the Primitive Type Byte?

Answer

A byte is a primitive Java data type that uses eight bites to represent a number ranging from -128

to 127. The following statements declare two byte variables. The first variable, flag_bits, can store

one value. The second byte variable, data_table, is an array, capable of holding four values. In this

case, the Java compiler will preassign the array elements using the values specified between the left

and right braces:

� byte flag__bits;

� byte data__table = { 32, 16, 8, 4 }; // Creates an array.

283. What is the Primitive Type Short?

Answer

The type short is a primitive Java data type that uses two bytes to represent a number in the range

-32768 to 32767. The Java type short is identical to the two-byte hit in many C/C++ compilers.

The following statements declare two variables of type short:

short age;

short height, width;

284. Why call by Value Prevents Parameter Value change?

Answer

� When you pass primitive types such as the types float, boolean, hit and char to a method, Java

passes the variables by value. In other words, Java makes a copy of the original variable which

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

the method can access and the original remains unchanged. Within a method, the code can

change the values as much as it needs because Java created these values as copies of the

originals.

� Wherever you pass a primitive type as a parameter to a method, Java copies this parameter to a

special memory location known as the stack. The stack maintains information about variables

used by the method while the method executes. When the method is complete, Java discards

the stack's contents and the copies of the variables you passed into the method are gone

forever.

� Because Java copies your original primitive type parameters, there is never any danger of a

method altering your original values. Remember, this only applies to primitive types, which are

automatically passed by value. Objects and arrays are not passed by value (instead they are

passed by reference) and they are in danger of being changed.

285. What is Remote Method Invocation (RMI)?

Answer

As you develop more complicated Java applets, and as other developers publish their own applet,

you may find that you need to have your Java objects invoke other Java object methods residing on

other computers. This is a natural extension of Java—you are able to use Java-based resources

throughout the Web to give your applet additional functionality. Remote Method Invocation (RMI)

lets methods within your Java objects be invoked from Java code that may be running in a different

virtual machine, often on another computer.

286. What is JAVA JIT Compilers?

Answer

� When your Java-enabled browser connects to a server and tries to view a Web page that

contains a Java applet, the server transmits the bytecode for that applet to your computer.

Before your browser can run the applet, it must interpret the bytecode data. The Java

interpreter performs the task of interpreting the bytecode data.

� As you have learned, using an interpreter to read bytecode files makes it possible for the same

bytecode to run on any computer (such as a Window-based or Mac-based computer) that

supports Java. The big drawback is that interpreters can be 20 to 40 times slower than code that

was custom or native, for a specific computer.

� As it turns out, a new type of browser-side software, called a Just-In-Time compiler (JIT), can

convert (compile) the bytecode file directly into native code optimized for the computer that is

browsing it. The JIT compiler will take the bytecode data sent by the server and compile it just

before the applet needs to run. The compiled code will execute as fast as any application you

already use on your computer. As you might expect, the major compiler and IDE manufacturers,

such as Borland, Microsoft, Symantec and Metroworks, are all developing JIT compilers.

287. What is the Java IDL System?

Answer

The Interface Definition Language (IDL) is an industry standard format useful for letting a Java client

transparently invoke existing IDL object that reside on a remote server. In addition, it allows a Java

server to define objects that can be transparently invoked from IDL clients. The Java IDL system lets

you define remote interfaces using the IDL interface definition language which you can then compile

with the idlgen stub generator tool to generate Java interface definitions and Java client and server

stubs.

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

288. What is Java Beans?

Answer

Java Beans is the name of a project at JavaSoft to define a set of standard component software APIs

(Application Programmers Interface) for the Java platform. By developing these standards, it

becomes possible for software developers to develop reusable software components that end-users

can then hook together using application-builder tools. In addition, these API's make it easier for

developers to bridge to existing component models such as Microsoft's ActiveX, Apple's OpenDoc and

Netscape's LiveConnect.

289. What is Object-Oriented Programming?

Answer

To programmers, an object is a collection of data and methods are a set of operations that manipulate

the data. Object-oriented programming provides a way of looking at programs in terms of the objects

(things) that make up a system. After you have identified your system's objects, you can determine

the operations normally performed on the object. If you have a document object, for example,

common operations might include printing, spell-checking, faxing or even discarding.

Object-oriented programming does not require a special programming language such as Java.You

can write object-oriented programs in such languages as C++ or Java or C#. However, as you will

learn, languages described as "object-oriented" normally provide class-based data structures that let

your programs group the data and methods into one variable. Objects-oriented programming has

many advantages, primarily object reuse and ease of understanding. As it turns out, you can often

use the object that you write for one program in another program. Rather than building a collection

of function libraries, object-oriented programmers build class libraries. Likewise, by grouping an

object's data and methods, object-oriented programs are often more readily understood than their

non-object- based counterparts.

290. What is Abstraction?

Answer

Abstraction is the process of looking at an object in terms of its methods (the operations), while

temporarily ignoring the underlying details of the object's implementation. Programmers use

abstraction to simplify the design and implementation of complex programs. For example, if you are

told to write a word processor, the task might at first seem insurmountable. However, using

abstraction, you begin to realize that a word processor actually consists of objects such as a document

object that users will create, save, spell-check and print. By viewing programs in abstract terms, you

can better understand the required programming. In Java, the class is the primary tool for supporting

abstraction.

291. What is Encapsulation?

Answer

As you read articles and books about object-oriented programming and Java, you might encounter

the term encapsulation. In the simplest sense, encapsulation is the combination of data and methods

into a single data structure. Encapsulation groups together all the components of an object. In the

"object-oriented" sense, encapsulation also defines how your programs can reference an object's

data. Because you can divide a Java class into public and private sections; you can control the degree

to which class users can modify or access the class data. For example, programs can only access an

object's private data using public methods defined within the class. Encapsulating an object's data

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

in this way protects the data from program misuses. In Java, the class is the fundamental tool for

encapsulation.

292. How does the Application server handle the JMS Connection?

Answer

1. App server creates the server session and stores them in a pool.

2. Connection consumer uses the server session to put messages in the session of the JMS.

3. Server session is the one that spawns the JMS session.

4. Applications written by the Application programmers creates the message listener.

293. What is a Superclass?

Answer

When you derive one class from another in Java, you establish relationships between the various

classes. The parent class (or the class it is being derived from) is often called the superclass or base

class. The superclass is really an ordinary class which is being extended by another class. In other

words, you do not need to do anything special to the class in order for it to become a superclass.

Any of the classes you write may some day become a superclass if someone decides to create a new

subclass derived from your class.

Of course, you can prevent a class from becoming a superclass (that is, do not allow it to be

extended). If you use the final keyword at the start of the class declaration, the class cannot be

extended.

294. Explain the Abstract Class Modifier?

Answer

As you have learned, Java lets you extend an existing class with a subclass. Over time, you may

start to develop your own class libraries whose classes you anticipate other programmers will extend.

For some classes, there may be times when it does not make sense to implement a method until you

know how a programmer will extend the class. In such cases, you can define the method as abstract,

which forces a programmer who is extending the class to implement the method.

When you use the abstract keyword within a class, a program cannot create an instance of that class.

As briefly discussed, abstract classes usually have abstract methods which the class did not

implement. Instead, a subclass extends the abstract class and the subclass must supply the abstract

method's implementation. To declare a class abstract, simply include the abstract keyword within

the class definition, as shown:

public abstract class Some abstract Class

{

}

295. What is the Final Class Modifier?

Answer

As you have learned, Java lets one class extend another. When you design a class, there may be

times when you don't want another programmer to extend the class. In such cases, by including the

final keyword within a class definition, you prevent the class from being subclassed. The following

statement illustrates the use of the final keyword within a class definition:

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

public final class TheBuckStopsHere

{

}

296. Explain the Public Class Modifier.

Answer

As you develop Java programs, there may be times when you create classes that you don't want the

code outside of the class package (the class file) to access or even to have the knowledge of.

When you use the public keyword within a class declaration, you make that class visible (and

accessible) everywhere. A non-public class, on the other hand, is visible only to the package within

which it is defined. To control access to a class, do not include the public keyword within the class

declaration. Java only lets you place one public class within a source-code file. For example, the

following statement illustrates the use of the public keyword within a class:

public class ImEverywhereYouWantMeToBe

{

}

297. What is the Public Field Modifier?

Answer

A variable's scope defines the locations within a program where the variable is known. Within a class

definition, you can control a class member variable's scope by preceding a variable's declaration with

the public, private or protected keywords. A public variable is visible (accessible) everywhere in the

program where the class itself is visible (accessible). To declare a variable public, simply use the

public keyword at the start of the variable declaration, as shown:

public int seeMeEveryWhere;

298. Explain the Private Field Modifier?

Answer

To control a class member variable's scope, you can precede the variable's declaration with the public,

private or protected key words. A private variable is only visible within its class. Subclasses cannot

access private variables. To declare a variable private, simply use the private keyword at the start

of the variable declaration, as shown:

private int InvisibleOutside;

299. Explain the Protected Field Modifier?

Answer

To control a class member variable's scope, you can precede the variable's declaration with the public,

private ox protected keywords. A protected variable is one that is only visible within its class, within

subclasses or within the package that the class is part of. The different between a private class

member and a protected class member is that & private class member is not accessible within a

subclass. To declare a variable protected, simply use the protected keyword at the start of the

variable declaration, as shown:

protected int ImProtected;

300. Can you explain the Private Protected Field Modifier?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

To control a class member variable's scope, you can precede the variable's declaration with the public,

private or protected keywords. A private protected variable is only visible within its class and within

subclasses of the class. The difference between a protected class member and a private protected

variable is that a private protected variable is not accessible within its package. To declare a variable

private protected, simply use the private protected keyword at the start of variable declaration, as

shown:

private protected int ImPrivateProtected;

301. What is the Static Field Modifier?

Answer

Class member variables are often called instance variables because each instance of the class, each

object, gets its own copy of each variables. Depending on your program's purpose, there may be

times when the class objects need to share information. In such cases, you can specify one or more

class variables as shared among the objects. To share a variable among class objects, you declare

the variable as static, as shown:

public static int ShareThisValue;

In this case, if object changes the value of the ShareThisValue variables, each object will see the

updated value.

302. What is the Final Field Modifier?

Answer

When you declare variable in a class final, you tell the compiler that the -variable has a constant

value that program should not change. To define a final variable, you must also include an initializer

that assigns a value to the constant. For example, the following statement creates a constant value

named MAXJCEYS, to which the program assigns the value 256:

protected static final int MAX_KEYS = 256;

303. Explain the Transient Field Modifier?

Answer

When you declare a variable in a class transient, you tell Java that the variable is not a part of the

object's persistent state. Currently, Java does not use the transient keyword. However, future

(persistent) versions of Java may use the transient keyword to tell the compiler that the program is

using the variable for "scratch pad" purposes and that the compiler does not need to save the variable

to disk. The following statement illustrates the use of the transient keyword:

transient float temp__swap__value;

304. Explain the use of Volatile Field Modifier?

Answer

When you compile a program, the compiler will examine your code and perform some "tricks" behind

the scenes that optimize your program's performance. Under certain circumstances, you may want

to force the compiler not to optimize a variable. Optimization can make certain assumptions about

where and how memory is handled. If, for example, you are building an interface to memory-mapped

device, you may need to suppress optimization. To protect a variable from being optimized, you

should use the volatile keyword, as shown:

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

volatile double system_bit_flags;

305. What is Default Constructors?

Answer

When you create your classes, you should always provide one or more constructor methods.

However, if you do not specify constructor, Java will provide a default constructor for you. Java's

default constructor will allocate memory to hold the object and will then initialize all instance variables

to their defaults. Java will not provide a default constructor, however, if your class specifies one or

more constructor for the class.

306. What is the Public Method Modifier?

Answer

Using the public, private and protected keywords, you can control a variable's scope. In a similar

way, Java lets you use these attributes with class methods as well. A public method is visible

everywhere that the class is visible. To declare a method as public, simply precede the method header

with the public keyword, as shown:

public float myPublicMethod();

307. What is the Private Method Modifier?

Answer

Using the public, private and protected keywords, you can control a variable's scope. In a similar

way, Java lets you use these attributes with class methods as well. A private method is only visible

within its class. Subclasses cannot access private methods. To declare a method as private, simply

precede the method header with the private keyword, as shown:

private int myPrivateMethod();

308. What is the Protected Method Modifier?

Answer

Using the public, private and protected keywords, you can control a variable's scope. In a similar

way, Java lets you use these attributes with class methods as well. A protected method is only visible

within its class, within subclasses or within the class package. To declare a method as protected,

simply precede the method header with the protected keyword, as shown:

protected int myProtectedMethod();

310. Can you explain the Final Method Modifier?

Answer

Java lets you extend one class (the superclass) with another (the subclass). When a subclass extends

a class, the subclass can override the superclass methods. In some cases depending on a method's

, purpose, you may want to prevent a subclass from overriding a specific method. When you declare

a class method as final, another class cannot override the methods. Methods which you declare static

or private are implicitly final. To declare a method as final, simply precede the method header with

the final keyword, as shown:

public final CannotOverrideThisMethod();

311. What is the Abstract Method Modifier?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

When the abstract keyword precedes a class method, you cannot create an instance of the class

containing the method. Abstract methods do not provide an implementation. Instead, your abstract

method definition only indicates the arguments return type. When a subclass extends the class

containing the abstract method, the subclass is required to supply the implementation for the abstract

method. To declare a method abstract, simply provides the abstract keyword , as follows:

public abstract void implementMeLater(int x) ;

312. What is the Synchronized Method Modifier?

Answer

Java supports multiple threads of execution which appear to execute simultaneously within your

program. Depending on your program's processing, there may be times when you must guarantee

that two or more threads cannot access method at the same time. To control the number of threads

that can access a method at any one time, you use the synchronized keyword. When the Java

compiler encounters the synchronized keyword, the compiler will include special code that locks the

method as one thread starts executing the method's instruction and later unlocks the method as the

thread exits. Normally, programs synchronize methods that access shared data. The following

statement illustrates the use of the synchronized keyword:

synchronized void refreshData( )

313. Explain the init Method?

Answer

When a Web browser (or an appletviewer) runs a Java applet, the applet's execution starts with the

init method. Think of the Java init method as similar to the main function in C/C++, at which the

program's execution starts. However, unlike the C/C++ main function, when the Java init method

ends, the applet does not end. Most applets use init to initialize key variables (hence, the name init).

If you do not supply an init method within your applet, Java will run its own default init method which

is defined in the Applet class library. The following statements illustrate the format of an init method:

public void init()

{

//statements

}

The public keyword tells the Java compiler that another object (in this case, the browser) can call

the init method from outside of the Applet class. The void keyword tells the Java compiler that the

init method does not return a value to the browser. As you can see from the empty parentheses

following the method name, init does not use any parameters.

314. What is the Destroy Method?

Answer

Each time your applet ends, Java automatically calls the destroy method to free up memory the

applet was using. The destroy method is the compliment of the init method. However, you normally

do not need to override, the destroy method unless you have specific resources that you need to

remove, such as large graphical files or special threads that your applet has created. In short, the

destroy method provides a convenient way to group your applet's "clean up" processing into one

location, as shown:

public void destroy()

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

{

// Statements here

}

315. What is Multithreading?

Answer

Multithreading is the ability to have various parts of a program perform steps seemingly at the same

time. For example, many Web browsers let users view various pages and click on hot links while the

browser is downloading various pictures, text, sounds, and while drawing objects on the screen, The

Java design began with the goal of supporting multiple threads of execution. Java lets programs

interleave multiple program steps through the use of threads.

316. How Java uses the String and StringBuffer Classes?

Answer

Java strings are immutable, which means after you create a String object, you cannot change that

object's contents. The Java designers found that most of the time, programmers do not need to

change a string after it is created. By making String objects immutable, Java can provide better error

protection and more efficient handling of strings. However, in case you do need to change the String,

you can use a class called StringBuffer as a temporary "scratchpad" which you use to make changes.

In short, your programs can change the String objects you store within a Stringbuffer and later copy

the buffer's contents back to the String object after your alterations are complete.

In short, you should use String objects for "frozen" character strings whose contents you don't expect

to change. In contrast, you should use the StringBuffer class for strings you expect to change in

content or size. Within your programs, you can take advantage of features from both classes because

both provide methods to easily convert between the two.

317. What is the Epoch Date?

Answer

Within a Java program, you can create a Date object by specifying a year, month, date and optionally,

the hour, minute and second as parameters to the constructor function. You can also create a Date

object with no arguments to the constructor, in which case the Date object will contain the current

date and time. Finally, you can create a Date object by specifying the number of milliseconds since

the epoch date, which is midnight GMT, January 1st, 1970. The Date class uses the epoch date as a

reference point which lets your programs refer to subsequent dates in terms of a single long integer.

You cannot set a year before 1970.

318. What is an Arrays?

Answer

Sometimes you will need to manipulate a series of related objects within an array object. Arrays let

your programs work conveniently with a group of related objects. In short, an array simply lets you

store and access a set of objects of the same type within the same variable. For example, you can

use an array to keep track of grades for fifty students or to store a series of file names.

Even though Java arrays are similar in syntax to C/C++ arrays, they have subtle differences. In Java,

an array is basically an object that points to a set of other objects or primitive data types. The only

visible difference between arrays and objects is that arrays have a special syntax to make them

behave like the arrays found in other languages. Unlike C and C++, however, Java arrays cannot

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

change in size, nor can a program use an out-of-bound index with a Java array. Also, you declare

and create arrays in Java very differently than in C/C++.

319. What is Binary Search?

Answer

You know that you can find an element in an array by searching each element of the array one by

one. Unfortunately, sequential searches are very inefficient for large arrays. If your array is sorted,

you can use a binary search instead to locate a value within the array. A binary search repeatedly

subdivides the array until it finds your desired element. For example, you have undoubtedly searched

for a word in a dictionary. A sequential search is equivalent to searching each word one by one,

starting from the very first word. If the word is much past the first page, this type of search is a very

inefficient process.

A binary search is equivalent to opening a dictionary in the middle, and then deciding if the word is

in the first half or second half of the book. You then open the next section in the middle and if the

word is in the first half or second half of that section. You can then repeat this process of dividing

the book in half until you find the word for which you are looking. If you have never tried, pick a

word and try to find it in a dictionary using a binary search technique. You might be surprised at how

few divisions it takes to get very close to the word you are looking for. A binary search is very

efficient. However, the array must be sorted for it to work.

320. Can a Private Method of a Superclass be declared within a Subclass?

Answer

Sure. A private field or method or inner class belongs to its declared class and hides from its

subclasses. There is no way for private stuff to have a runtime overloading or overriding

(polymorphism) features.

321. What is Quick Sort?

Answer

For large arrays, you need an efficient sorting technique. One of the most efficient techniques is the

quick sort. The quick sort technique takes the middle element of an array and sub-divides the array

into two smaller arrays. One array will contain elements greater than the middle value of the original

array. Conversely, the other array will contain elements that are less than the middle value. The

quick sort will repeat this process for each new array until the final arrays contain only a single

element. At this point, the single element arrays are in the proper order, as shown below

322. What is the difference between Final, Finally and Finalize?

Answer

� final—declare constant

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

� finally—handles exception

� Finalize—helps in garbage collection.

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

� Answer

� System is a predefined final class, out is a PrintStream object and println is a built-in

overloaded method in the out object.

324. What is meant by "Abstract Interface"?

Answer

First, an interface is abstract. That means you cannot have any implementation in an interface. All

the methods declared in an interface are abstract methods or signatures of the methods.

325. What is the difference between Swing and AWT Components?

Answer

AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight

components depend on the local windowing toolkit. For example, java.awt. Button is a heavy weight

component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.

326. Why Java does not support Pointers?

Answer

Because pointers are unsafe. Java uses reference types to hide pointers and programmers feel easier

to deal with reference types without pointers.

327. What are Parsers? DOM vs SAX Parser.

Answer

Parsers are fundamental xml components, a bridge between XML documents and applications that

process that XML. The parser is responsible for handling xml syntax, checking the contents of the

document against constraints established in a DTD or Schema.

328. What is a Platform?

Answer

A platform is the hardware or software environment in which a program runs. Most platforms can be

described as a combination of the operating system and hardware, like Windows 2000/XP, Linux,

Solaris and MacOS.

329. What is the main difference between Java Platform and other Platforms?

Answer

The Java platform differs from most other platforms in that it's a software-only platform that runs

on top of other hardware-based platforms, The Java platform has two components:

1. The Java Virtual Machine (Java VM).

2. The Java Application Programming Interface (Java API).

330. What is the Java Virtual Machine?

Answer

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

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

331. What is the Java API?

Answer

The Java API is a large collection of ready-made software components that provide many useful

capabilities, such as graphical user interface (GUI) widgets.

332. What is the Package?

Answer

The package is a Java namespace or part of Java libraries. The Java API is grouped into libraries of

related classes and interfaces; these libraries are known as packages.

333. What is Native Code?

Answer

The native code is a code that after you compile it, the compiled code runs on a specific hardware

platform.

334. Is Java Code slower than Native Code?

Answer

Not really. As a platform-independent environment, the Java platform can be a bit slower than native

code. However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can

bring performance close to that of native code without threatening portability.

335. What is the Serialization?

Answer

The serialization is a kind of mechanism that makes a class or a bean persistence by having its

properties or fields and state information saved and restored to and from storage.

336. How to make a Class or a Bean Serializable?

Answer

By implementing either the java.io.Serializable interface or the java.io.Externalizable interface. As

long as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that

class is serializable.

337. How many methods are there in the Serializable Interface?

Answer

There is no method in the Serializable interface. The Serializable interface acts as a marker, telling

the object serialization tools that your class is serializable.

338. How many methods are there in the Externalizable Interface?

Answer

There are two methods in the Externalizable interface. You have to implement these two methods in

order to make your class externalizable. These two methods are

� readExternal() and

� writeExternal().

339. Which containers use a Border Layout as their Default Layout?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

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

340. What is Synchronization and why is it important?

Answer

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

causes dirty data and leads to significant errors.

341. What are three ways in which a Thread can enter the Waiting State?

Answer

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.

342. What is the preferred size of a Component?

Answer

The preferred size of a component is the minimum component size that will allow the component to

display normally.

343. Can Java object be locked down for exclusive use by a given thread?

Answer

Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible

to any thread other than the one that explicitly claimed it.

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

Answer

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.

346. What are the High-Level Thread states?

Answer

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

347. What is the Collections API?

Answer

The Collections API is a set of classes and interfaces that support operations on collections of objects.

348. What is the List Interface?

Answer

The List interface provides support for ordered collections of objects.

349. How many bits are used to represent Unicode, ASCII, UTF-16 and UTF-8 characters?

Answer

� Unicode requires 16 bits.

� ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented

as 8 bits.

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

� UTF-8 represents characters using 8, 16, and 18 bit patterns.

� UTF-16 uses 16-bit and larger bit patterns.

350. What is the Properties Class?

Answer

The properties class is a subclass of Hashtable that can be read from or written to a stream.

It also provides the capability to specify a set of default values to be used.

351. What is the purpose of the Runtime Class?

Answer

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

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

Answer

The finally clause is used to provide the capability to execute code no matter whether or not an

exception is thrown or caught.

353. What is the Locale Class?

Answer

The Locale class is used to tailor program output to the conventions of a particular geographic,

political or cultural region.

354. What is a Protected Method?

Answer

A protected method is a method that can be accessed by any method in its package and inherited

by any subclass of its class.

355. What is a Static Method?

Answer

A static method is a method that belongs to the class rather than any object of the class and doesn't

apply to an object or even require that any objects of the class have been instantiated.

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

Answer

A frame is a resizable, movable window with title bar and close button. Usually it contains Panels. Its

derived from a window and has a borderlayout by default.

A window is a Container and has BorderLayout by default. A window must have a parent Frame

mentioned in the constructor.

357. What are Peerless Components?

Answer

The peerless components are called light weight components.

358. What is the difference between the Reader/Writer Class Hierarchy and the

InputStream/OutputStream Class Hierarchy?

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

Answer

The Reader/Writer class hierarchy is character-oriented and the InputStream/OutputStream class

hierarchy is byte-oriented.

359. What is the difference between Throw and Throws Keywords?

Answer

The throw keyword denotes a statement that causes an exception to be initiated. It takes the

Exception object to be thrown as argument. The exception will be caught by an immediately

encompassing try-catch construction or propagated further up the calling hierarchy. The throws

keyword is a modifier of a method that designates that exceptions may come out of the method,

either by virtue of the method throwing the exception itself or because it fails to catch such exceptions

that a method it calls may throw.

361. How can a GUI Component handle its own events?

Answer

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

adding itself as its own event listener.

362. What advantage do Java's Layout Managers provide over Traditional Windowing Systems?

Answer

Java uses layout managers to layout 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 accommodate platform-specific differences among windowing systems.

363. What are the problems faced by Java programmers who don't use Layout Managers?

Answer

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.

364. What is the difference between Static and Non-static Variables?

Answer

A static variable is associated with the class as a whole, rather than with specific instances of a class.

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

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

Answer

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.

366. What is a Container in a GUI?

Answer

A Container contains and arranges other components (including other containers) through the use

of layout managers, which use specific layout policies to determine where components should go as

a function of the size of the container.

367. Is Iterator a Class or Interface? What is its use?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

Iterator is an interface which is used to step through the elements of a Collection.

368. How you can force the Garbage Collection?

Answer

Garbage collection is an automatic process and can't be forced.

369. Describe the principles of OOPS?

Answer

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

Encapsulation.

370. Explain the Encapsulation Principle?

Answer

Encapsulation is a process of binding or wrapping the data and the codes that operates on the data

into a single entity. This keeps the data safe from outside interface and misuse. One way to think

about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily

accessed by the other code defined outside the wrapper.

371. Explain the Inheritance Principle?

Answer

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

372. How to define an Abstract Class?

Answer

A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.

Example of Abstract class: abstract

class testAbstractClass {

protected String myString;

public String getMyString() { return myString;

}

public abstract string anyAbstractFunction{);

}

373. How to define an interface?

Answer

In Java, Interface defines the methods but does not implement them. Interface can include constants.

A class that implements the interfaces is bound to implement all the methods defined in Interface.

Example of Interface:

public interface samplelnterface {

public void functionOne();

public long CONSTANTJDNE = 1000;

}

374. Explain the Polymorphism principle?

Answer

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

The meaning of Polymorphism is something like one name, many forms. Polymorphism enables one

entity to be used as a general category for different types of actions. The specific action is determined

by the exact nature of the situation. The concept of polymorphism can be explained as "one interface,

multiple methods".

375. Explain the different forms of Polymorphism?

Answer

From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:

� Method overloading

� Method overriding through inheritance

� Method overriding through the Java interface.

376. What are Access Specifiers available in Java?

Answer

Access specifiers are keywords that determine the type of access to the member of a class. These

are:

� Public

� Protected

� Private

� Defaults.

377. What do you understand by a Variable?

Answer

The variables play a very important role in computer programming. Variables enable programmers to

write flexible programs. It is a memory location that has been named so that it can be easily be referred

to in the program. The variable is used to hold the data and it can be changed during the course of

the execution of the program.

378. What do you understand by Numeric Promotion?

Answer

The 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 the numerical promotion process the 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.

379. Differentiate between a Class and an Object.

Answer

A Class is only the definition or prototype of real life object. Whereas an object is an instance or living

representation of real life object. Every object belongs to a class and every class contains one or more

related objects.

380. What is the use of Object and Class Classes?

Answer

The Object class is the superclass of all other classes and it is highest-level class in the Java class

hierarchy. Instances of the class Class represent classes and interfaces in a running Java application.

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with

the same element type and number of dimensions. The primitive Java types (boolean, byte, char,

short, int, long, float and double) and the keyword void are also represented as Class objects.

381. What do you understand by Casting in Java Language?

Answer

The process of converting one datatype to another in Java language is called Casting.

382. What are the types of Casting?

Answer

There are two types of casting in Java, these are Implicit casting and Explicit casting.

383. What do you understand by Downcasting?

Answer

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

down the hierarchy.

384. What do you understand by Final Value?

Answer

FINAL for a variable: value is constant.

FINAL for a method: cannot be overridden.

FINAL for a class: cannot be derived.

Final for Object- Make a object Static

385. What are Keyboard Events?

Answer

When Java generates a keyboard event, it passes an Event object that contains information about

the key pressed, Java recognizes normal keys, modifier keys, and special keys, For normal keys, the

event object contains the key's ASCII value. For the function, arrow and other special keys, there

are no ASCII codes, so Java uses special Java-defined code. You have learned how to detect modifier

keys. The modifier keys are stored in the modifiers variable in the Event object.

386. What is the Intersection and Union Methods?

Answer

When your program uses Rectangle objects, you may need to determine the screen region that holds

both objects or two Rectangle objects intersect, to find the intersection or the union of two rectangles,

you can use the Rectangle class intersection and union methods. The intersection method returns

the area where two Rectangle objects overlap. That is, the intersecting method return the area that

two Rectangle objects have in common.

The union method, on the other hand, behaves differently than you might expect. The union method

returns the smallest rectangle that encloses two Rectangle objects, instead of returning just the area

covered by both objects. This illustrates the behavior of the intersection and union methods.

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

387. What are Controls and their different types in AWT?

Answer

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 the subclasses of the Component.

388. What is the difference between Choice and List?

Answer

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.

389. What is the difference between Scrollbar and Scrollpane?

Answer

A Scrollbar is a Component, but not a Container whereas Scrollpane is a Container and handles its

own events and perform its own scrolling.

390. Which containers use a Flow Layout as their default layout?

Answer

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

391. What are Wrapper Classes?

Answer

Wrapper classes are classes that allow primitive types to be accessed as objects.

392. What is the difference between Set and List?

Answer

Set stores elements in an unordered way but does not contain duplicate elements, where as list

stores elements in an ordered way but may contain duplicate elements.

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

Answer

By associating Checkbox objects with a CheckboxGroup.

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

Answer

setEditable()

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

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

Answer

getLabel() and setLabel().

396. What is the difference between yield() and sleep()?

Answer

When a object invokes yield() it returns to ready state. But when an object invokes sleep() method

enters to not ready state.

397. How to handle a Web Browser Resize Operation?

Answer

You know how important it is to suspend your threads when Java calls an applet's stop method.

Normally, Java calls the stop method when a browser leaves the corresponding Web page. However,

in some cases, a Web browser will unexpectedly call an applet's stop method. When a browser window

is resized, the browser may first call the stop method and then the start method. If you only stop a

thread when its applet stops and create a new thread when the applet restarts, the applet will

probably not behave the way that a user expects. To prevent unwanted behavior after resizing the

browser, your program should suspend threads when the applet stops and resume the threads when

the applet starts.

398. Explain the concept of Hashtables?

Answer

A hashtable is a data structure that lets you look up stored items using an associated key. With an

array, you can quickly access an element by specifying an integer index. The limitation of an array

is that the look up key can only be an integer. With a hashtable, on the other hand, you can associate

an item with a key and then use the key to look up the item. You can use an object of any type as a

key in a hashtable. For example, you might specify the license-plate number as the key and use the

key to look up the vehicle owner's record. To distinguish one item from the next, the associated key

that you use must be unique for each item, as in the case of a vehicle's license plate number.

397. How to handle a Web Browser Resize Operation?

Answer

You know how important it is to suspend your threads when Java calls an applet's stop method.

Normally, Java calls the stop method when a browser leaves the corresponding Web page. However,

in some cases, a Web browser will unexpectedly call an applet's stop method. When a browser window

is resized, the browser may first call the stop method and then the start method. If you only stop a

thread when its applet stops and create a new thread when the applet restarts, the applet will

probably not behave the way that a user expects. To prevent unwanted behavior after resizing the

browser, your program should suspend threads when the applet stops and resume the threads when

the applet starts.

398. Explain the concept of Hashtables?

Answer

A hashtable is a data structure that lets you look up stored items using an associated key. With an

array, you can quickly access an element by specifying an integer index. The limitation of an array

is that the look up key can only be an integer. With a hashtable, on the other hand, you can associate

an item with a key and then use the key to look up the item. You can use an object of any type as a

key in a hashtable. For example, you might specify the license-plate number as the key and use the

Interview Questions Core Java

Query / Feedback [email protected] Copyright @2013 ER Pragati Singh

key to look up the vehicle owner's record. To distinguish one item from the next, the associated key

that you use must be unique for each item, as in the case of a vehicle's license plate number.