Core Java Interview Questions -3

Core Java Interview Questions -3

1. What is a Java package and how is it used?
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.

2. What is the difference between the >> and >>> operators?

The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

3. What restrictions are placed on method overriding?
Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.

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

The default value of the boolean type is false.

5. Can an abstract class be final?

An abstract class may not be declared as final.

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

Top-level class may be public, abstract, or final.

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

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.

8. How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

9. What is the difference between the prefix and postfix forms of the ++ operator?
The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value.

10. What is the difference between a public and a non-public class?
A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package.

11. What are the practical benefits, if any, of importing a specific class rather than an entire package (e.g. import javnet.* versus import javnet.Socket)?
It makes no difference in the generated class files since only the classes that are actually used are referenced by the generated class file. There is another practical benefit to importing single classes, and this arises when two (or more) packages have classes with the same name. Take javutil.Timer and javax.swing.Timer, for example. If I import javutil.* 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 thejavax.swing.Timer class, and the only classes you plan on using in javutil are Collection and HashMap. In this case, some people will prefer to import javutil.Collection and import javutil.HashMapinstead of importing javutil.*. This will now allow them to use Timer, Collection, HashMap, and otherjavax.swing classes without using fully qualified class names in.

12. How many static initializers can you have ?

As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope.

13. Can a double value be cast to a byte?
Yes, a double value can be cast to a byte.

14. To what value is a variable of the String type automatically initialized?
The default value of an String type is null.

15. How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

16. What is the difference between method overriding and overloading?
Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments

17. What is the difference between a field variable and a local variable?
A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.

18. What is the difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

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

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

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

A break statement results in the termination of the statement to which it applies (switch, for, do, or while). Acontinue statement is used to end the current loop iteration and return control to the loop statement.

21. What is the difference between an if statement and a switch statement?
The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.

22. What does it mean that a class or member is final?
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.

23. Can a for statement loop indefinitely?

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

24. What happens to a static variable that is defined within a method of a class ?

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

25. What is numeric promotion?
Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.

26. What is a transient variable?
Transient variable is a variable that may not be serialized.

27. Which Java operator is right associative?
The = operator is right associative.

28. Is sizeof a keyword?
The sizeof operator is not a keyword.

29. What does it mean that a method or class is abstract?
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.

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

31.What are some alternatives to inheritance?
Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

32.What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.

33. What is method overloading?
If a class have multiple methods by same name but different parameters, it is known as Method Overloading. It increases the readability of the program.

34.What does it mean that a method or field is “static”?
Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println() work. out is a static field in the javlang.System class.

35.Is null a keyword?
The null value is not a keyword.

36.Why method overloading is not possible by changing the return type in java?

Becauseof ambiguity….

37.What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.

38.Why do threads block on I/O?
Threads block on i/o (that is enters the waiting state) so that other threads may execute while the I/O operation is performed.

39.What restrictions are placed on the location of a package statement within a source code file?
A package statement must appear as the first line in a source code file (excluding blank lines and comments).

40.Why isn’t there operator overloading?
Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().

41.What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.

42.What modifiers may be used with an inner class that is a member of an outer class?
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

43.How do I convert a numeric IP address like into a hostname like
String hostname = InetAddress.getByName(“”).getHostName();

44.What are order of precedence and associativity, and how are they used?
Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left

45.Which characters may be used as the second character of an identifier,but not as the first character of an identifier?
The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

46.What are the different identifier states of a Thread?
The different identifiers of a Thread are: R – Running or runnable thread, S – Suspended thread, CW – Thread waiting on a condition variable, MW – Thread waiting on a monitor lock, MS – Thread suspended waiting on a monitor lock

47.What is the range of the char type?
The range of the char type is 0 to 2^16 – 1.

48.What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

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

Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

50.Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

51.What is a native method?
A native method is a method that is implemented in a language other than Jav

52.What is the catch or declare rule for method declarations?
If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.

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

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

54.What kind of thread is the Garbage collector thread?
It is a daemon thread.

55.What is a daemon thread?
These are the threads which can run without user intervention. The JVM can exit when there are daemon thread by killing them abruptly.

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

57.What is the finalize method do?
Before the invalid objects get garbage collected, the JVM give the user a chance to clean up some resources before it got garbage collected.

58.What is mutable object and immutable object?
If a object value is changeable then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is immutable object. (Ex., String, Integer, Float, …)

59.What is the basic difference between string and stringbuffer object?
String is an immutable object. StringBuffer is a mutable object.

60.What is the purpose of Void class?
The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.

61.What is the purpose of Void class?
The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.

62.What is reflection?
Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use reflected fields, methods, and constructors to operate on their underlying counterparts on objects, within security restrictions.

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

64.What is the byte range?
128 to 127

65.What is the implementation of destroy method in jav. is it native or java code?
This method is not implemented.

66.What is a package?

To group set of classes into a single unit is known as packaging. Packages provides wide namespace ability.

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

By avoiding too much of static methods avoiding the excessive and unnecessary use of synchronized methods Selection of related classes based on the application (meaning synchronized classes for multiuser and non-synchronized classes for single user) Usage of appropriate design patterns Using cache methodologies for remote invocations Avoiding creation of variables within a loop and lot more.

68.What is a DatabaseMetaData?
Comprehensive information about the database as a whole.

69.What is Locale?

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

70.How will you load a specific locale?
Using ResourceBundle.getBundle(…);

71.What is JIT and its use?
Really, just a very fast compiler… In this incarnation, pretty much a one-pass compiler — no offline computations. So you can’t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, it’s an on-line problem.

72.Is JVM a compiler or an interpreter?

73.When you think about optimization, what is the best way to findout the time/memory consuming process?

Using profiler

74.What is the purpose of assert keyword used in JDK1.4.x?
In order to validate certain expressions. It effectively replaces the if block and automatically throws the AssertionError on failure. This keyword should be used for the critical arguments. Meaning, without that the method does nothing.

75.How will you get the platform dependent values like line separator, path separator, etc., ?
Using Sytem.getProperty(…) (line.separator, path.separator, …)

76.What is skeleton and stub? what is the purpose of those?
Stub is a client side representation of the server, which takes care of communicating with the remote server. Skeleton is the server side representation. But that is no more in use… it is deprecated long before in JDK.

77.What is the final keyword denotes?
final keyword denotes that it is the final implementation for that method or variable or class. You can’t override that method/variable/class any more.

78.What is the significance of ListIterator?
You can iterate back and forth.

79.What is the major difference between LinkedList and ArrayList?
LinkedList are meant for sequential accessing. ArrayList are meant for random accessing.

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

81.What is inner class?
If the methods of the inner class can only be accessed via the instance of the inner class, then it is called inner class.

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

83.What is aggregation?
It is a special type of composition. If you expose all the methods of a composite class and route the method call to the composite method through its reference, then it is called aggregation.

84.What are the methods in Object?
clone, equals, wait, finalize, getClass, hashCode, notify, notifyAll, toString

85.Can you instantiate the Math class?
You can’t instantiate the math class. All the methods in this class are static. And the constructor is not public.

86.What is singleton?
It is one of the design pattern. This falls in the creational pattern of the design pattern. There will be only one instance for that entire JVM. You can achieve this by having the private constructor in the class. For eg., public class Singleton { private static final Singleton s = new Singleton(); private Singleton() { } public static Singleton getInstance() { return s; } // all non static methods … }

87.What is DriverManager?
The basic service to manage set of JDBC drivers.

88.What is Class.forName() does and how it is useful?
It loads the class into the ClassLoader. It returns the Class. Using that you can get the instance ( “class-instance”.newInstance() ).

89.Inq adds a question: Expain the reason for each keyword of
public static void main(String args[])

90.How many types of memory areas are allocated by JVM?
Many types:
1.    Class(Method) Area
2.    Heap
3.    Stack
4.    Program Counter Register
5.    Native Method Stack

91.What is JIT compiler?
Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

92.What is platform?
A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides software-based platform.

93.If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?
It is empty. But not null.

94.What is the default value of the local variables?
The local variables are not initialized to any default value, neither primitives nor object references.

95.What is classloader?The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.

96.Is Empty .java file name a valid source file name?
Yes, save your java file by .java only, compile it by javac .java and run by java yourclassname Let’s take a simple example:
//save by .java only

class A{
public static void main(String args[]){
System.out.println(“Hello java”);

//compile by javac .java
//run by     java A
compile it by javac .java
run it by java A

97.Is delete,next,main,exit or null keyword in java?

98.What is the main difference between Java platform and other platforms?
The Java platform differs from most other platforms in the sense that it’s a software-based platform that runs on top of other hardware-based platforms.It has two components:
1.    Runtime Environment
2.    API(Application Programming Interface)

99.What if I write static public void instead of public static void?
Program compiles and runs properly.

100.What gives Java its ‘write once and run anywhere’ nature?
The bytecode. 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.

101.What is difference between object oriented programming language and object based programming language?
Object based programming languages follow all the features of OOPs except Inheritance. Examples of object based programming languages are JavaScript, VBScript etc.

102.What will be the initial value of an object reference which is defined as an instance variable?
The object references are all initialized to null in Jav

Also Read:
Core Java Interview Questions -1

Core Java Interview Questions -2

Core Java Interview Questions -4

Core Java Interview Questions -5

Core Java Interview Questions -6

Core Java Interview Questions -7 

Core Java Interview Questions -8

Core Java Interview Questions -9



This site uses Akismet to reduce spam. Learn how your comment data is processed.