Java Interview Questions -24

 Java Interview Questions -24

1. How could Java classes direct program messages to the system console, but error messages, say to a file?

The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st =new Stream (new
FileOutputStream (“techinterviews_com.txt”));

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

3. Why would you use a synchronized block vs. synchronized method?
Synchronized blocks place locks for shorter periods than synchronized methods.

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

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

6. How do you know if an explicit object casting is needed?
If you assign a superclass object to a variable of a subclass’s data type, you need to do explicit casting. For example:
Object a;Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.

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

8. Can you write a Java class that could be used both as an applet as well as an application?
Yes. Add a main() method to the applet.

9. What’s the difference between constructors and other methods?
Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

10. Can you call one constructor from another if a class has multiple constructors
Yes. Use this() syntax.

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

12. If a class is located in a package, what do you need to change in the OS environment to be able to use it?
You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let’s say a class Employee belongs to a package; and is located in the file c:/dev/ In this case, you’d need to add c:/dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:

13. What’s the difference between J2SDK 1.5 and J2SDK 5.0?
There’s no difference, Sun Microsystems just re-branded this version.

14. What would you use to compare two String variables – the operator == or the method equals()?
I’d use the method equals() to compare the values of the Strings and the = = to check if two variables point at the same instance of a String object.

15. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception’s subclasses have to be caught first.

16. Can an inner class declared inside of a method access local variables of this method?
It’s possible if these variables are final.

17. What can go wrong if you replace && with & in the following code:
String a=null;
if (a!=null && a.length()>10)
A single ampersand here would lead to a NullPointerException.

18. What’s the main difference between a Vector and an ArrayList
Java Vector class is internally synchronized and ArrayList is not.

19. When should the method invokeLater()be used?
This method is used to ensure that Swing components are updated through the event-dispatching thread.

20. How can a subclass call a method or a constructor defined in a superclass?
Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass’s constructor.

21. What’s the difference between a queue and a stack?
Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule.

22. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?
Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.

23. What comes to mind when you hear about a young generation in Java?
Garbage collection.

24. What comes to mind when someone mentions a shallow copy in Java?
Object cloning.

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

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

27. How would you make a copy of an entire Java object with its state?
Have this class implement Cloneable interface and call its method clone().

28. How can you minimize the need of garbage collection and make the memory use more effective?
Use object pooling and weak object references.

29. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?
If these classes are threads I’d consider notify() or notifyAll(). For regular classes you can use the Observer interface.

30. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?
You do not need to specify any access level, and Java will use a default package access level.

31.What is difference between Path and Classpath?
Ans: Path and Classpath are operating system level environment variables. Path is used define where the system can find the executables(.exe) files and classpath is used to specify the location .class files.

32.What is JIT (Just-in-Time) Compilation ?
When JVM compiles the class file he does not compile the full class file in one shot. Compilation is done on function basis or file basis. Advantage gained from this is that heavy parsing of original source code is avoided. Depending on need basis the compilation is done. This typ of compilation is termed as JIT or Just-in- Time compilation.
33.How do you implement inheritance in Java?
inheritance is implemented by using “EXTEND” keyword.
34.How can we implement polymorphism in Java ?
Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. There are two types of polymorphism:-
Method Polymorphism through overloading.
Object polymorphism by inheritance / interfaces.
35.what are packages ?
packages group related classes and interfaces together and thus avoiding any name conflicts. From OOP’s point of view packages are useful for grouping related classes together. Classes are group together in a package using “package” keyword.
36.What is the use if “instanceof” keyword ?
“ instanceof ” keyword is used to check what is the type of object. F
37.What are Native methods in Java ?
There may be times when we want to call subroutines which are written in some other language other than Java like C++, VB6 etc.
38.Explain in depth Garbage collector ?
Garbage collection is the process of automatically freeing objects that are no longer referenced by the program. This frees the programmer from having to keep track of when to free allocated memory, thereby preventing many potential bugs. Thus making programmers more productive as they can now put more effort in coding rather than worrying about memory management.
The only disadvantage of garbage collector is it adds overheads. Because the JVM (Java virtual machine) has to keep a constant track of the objects which are not referenced and then free these unreferenced objects on fly. This whole process has a slight impact on the application performance. But garbage collector has a good algorithm and it runs in its own thread thus having a least impact on the application performance but still it has some impact.
39.How can we force the garbage collector to run?
Garbage collector can be run forcibly using “System.gc()” or “Runtime.gc()”
40. What’s the use of JAVAP tool ?
javap disassembles compiled Java files and spits out representation of the Java program. This is a useful option when the original source code is not available.

41.What are applets ?
Applets are small applications that are accessed from web server automatically installed, and run from the browser. Once an applet arrives on the client it has limited access to resources thus ensuring security for the end user. An applet is controlled by the software that runs it. Usually, the underlying software is a browser, but it can also be applet viewer. If you run the applet source code from eclipse it runs inside an applet viewer. All applets should inherit from applet class.
Below are sequences of events which occur in applet:-
The init Method: The init method is called when the applet is first loaded. Init method can be used to initialize color, fonts or any type of one type operation needed for the applet.
The start Method: The start method is called when user visits a browser with an applet on it. In start method applet spawns a thread in which it runs the paint method.
paint() is called every time when applet has to re-display everything. paint() event can occur due to various reasons some of the reasons are :-.
42.In which package is the applet class located?
Applet classes are located in " java.applet "package.
43.How can you copy one array in to a different array?
System.arraycopy(myOldArray, 0, myNewArray, 0, length);+

44.What is a package?
Package is a collection of related classes and interfaces. package declaration should be first statement in a java class.
45.what’s the main difference between ArrayList / HashMap and Vector / Hashtable?
Vector / HashTable are synchronized which means they are thread safe. Cost of thread safe is performance degradation. So if you are sure that you are not dealing with huge number of threads then you should use ArrayList / HashMap.But yes you can still
synchronize List and Map’s using Collections provided methods :-
List OurList = Collections.synchronizedList (OurList);
Map OurMap = Collections.synchronizedMap (OurMap);
46.what is a StringBuffer class and how does it differs from String class?
StringBuffer is a peer class of String that provides almost all functionality of strings. String represents fixed-length, immutable character sequences. Comparatively StringBuffer represents mutable, growable and writeable character sequences. But StringBuffer does not create new instances as string so it’s more efficient when it comes to intensive concatenation operation.
47. What is JAVAdoc utility?
Javadoc parses comments in JAVA source files and produced HTML pages for the same. Below is the syntax for the same javadoc [ options ] [ packagenames ] [ sourcefiles ] [ @files ] Arguments can be in any order. Options Command-line options that is doctitle, windowtitle, header, bottom etc
Packagenames: -
A series of names of packages, separated by spaces, such as java.lang java.lang.reflect java.awt. You must separately specify each package you want to document. Javadoc uses -sourcepath to look for these package names. Javadoc does not recursively traverse subpackages.
sourcefiles :-
A series of source file names, separated by spaces, each of which can begin with a path and contain a wildcard such as asterisk (*). The path that precedes the source file name determines where javadoc will look for it. (Javadoc does not use -sourcepath to look for these source file names.)
@files: - One or more files that contain packagenames and sourcefiles in any order, one name per line.
48.How much subclasses you can maximum in Inheritance?
In one of our old JAVA projects we had an inheritance depth of five. Believe us we never liked that code. It’s bad to have a huge inheritance depth. A maintainable inheritance depth should be maximum 5. Anything above that is horrible. There is no limit as such specified anywhere that there is some limit on the inheritance sub classing . But depending on environments you will get stack over flow error.

49. How to define a constant variable in Java?
Ans: The variable should be declared as static and final. So only one copy of the variable exists for all instances of the class and the value can’t be changed also.static final int PI = 2.14; is an example for constant.

50.What is the return type of the main method?
Ans: Main method doesn’t return anything hence declared void.

51. What is the arguement of main method?(
Ans: main method accepts an array of String object as arguement.

52. What is the most important feature of Java?
 Java is a platform independent language.

53. What is a JVM?(
Ans: JVM is Java Virtual Machine which is a run time environment for the compiled java class files.

54. What is the difference between a JDK and a JVM?
Ans: 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.

55.What are the restriction imposed on a static method or a static block of code?
Ans: A static method should not refer to instance variables without creating an instance and  cannot use “this” operator to refer the instance.(

56.When will you define a method as static?
Ans : 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.

57. What is the importance of static variable?
Ans: 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.

58.Does Java support multiple inheritance?
Ans: Java doesn’t support multiple inheritance.

59. Which package is imported by default?
Ans: java.lang package is imported by default even without a package declaration.

60. What is the purpose of declaring a variable as final?
Ans : A final variable’s value can’t be changed. final variables should be initialized before using them.

61.What is use of a abstract variable?
Ans:Variables can’t be declared as abstract. only classes and methods can be declared as abstract.

62.Can a method inside a Interface be declared as final?
No not possible. Doing so will result in compilation error. public and abstract are the only applicable modifiers for method declaration in an interface.

63.Why is an Interface be able to extend more than one Interface but a Class can't extend more than one Class?
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.

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

65.Can an Interface be final?
Not possible. Doing so so will result in compilation error.

66.Can a class be defined inside an Interface?
Yes it's possible.

67.Can an Interface be defined inside a class?
Yes it's possible.

68.What is a Marker Interface?
An Interface which doesn't have any declaration inside but still enforces a mechanism.

69.Can we define private and protected modifiers for variables in interfaces?
No. Always all variables declared inside a interface are of public access.

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

71.Can an Interface implement another Interface?
Intefaces doesn't provide implementation hence a interface cannot implement another interface.

72.Can an Interface extend another Interface?
Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.

73.Can a Class extend more than one Class?
Not possible. A Class can extend only one class but can implement any number of Interfaces.

74.When can an object reference be cast to an interface reference?
An object reference can be cast to an interface reference when the object implements the referenced interface.

75.What are Inner Classes?
Inner classes are classes which are defined inside another class.

76.What are Nested Classes?
Static Inner classes are called sometimes referred as nested classes because these classes can exist without any relationship with the containing class.

77.What is the super class of all Inner Classes?
Inner class is just a concept and can be applied to any class, hence there is no common super class for inner classes.

78.Can a regular inner class access a private member of the enclosing class?
Yes. Since inner classes are treated as a member of the outer class they can access private members of the outer class.

79.How will you instantiate a regular inner class from outside the enclosing class?
Outer out=new Outer();Outer.Inner Inner();

80.What are Local Inner Classes or Method Local Inner Classes?
A method-local inner class is defined within a method of the enclosing class.

81.What are the constraints on Method Local Inner Classes?
The following are the restrictions for Method Inner Classes:Method Local Inner classes cannot acccess local variables but can access final variables.Only abstract and final modifiers can be applied to Method Local Inner classesMethod Local Inner classes can be instantiated only within the method in which it is contained that too after the class definition.

82.What are Anonymous Inner Classes? Name the various forms of Anonymous Inner Classes.
Anonymous Inner Classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface. The following are the different forms of inner classes:Anonymous subclass(i.e. extends a class)Anonymous implementer (i.e. implements an interface)Argument-Defined Anonymous Inner Classes

83.How many classes can an Anonymous Inner classes inherit from?

84.What are the disadvantages of Inner classes?
1. Inner classes are not reusable hence defeats one of the fundamental feature of Java.2. Highly confusing and difficult syntax which leads poor code maintainability.

85.Name the different types of Inner Classes?
The following are the different types of Inner classes:Regular Inner ClassMethod Local Inner ClassStatic Inner ClassAnonymous Inner Class

86.What are Regular Inner Classes?
A Regular inner class is declared inside the curly braces of another class outside any method or other code block. This is the simplest form of inner classes.

87.How many Interfaces can an Anonymous Inner classes implement?
One. Normal classes and other inner classes can implement more than one interface whereas anonymous inner classes can either implement a single interface or extend a single class.

88.What are Static Inner Classes?
Static Inner Classes are inner classes which marked with a static modifier. These classes need not have any relationship with the outer class. These can be instantiated even without the existence of the outer class object.

89.Can you instantiate the static Inner Class without the existence of the outer class object?
If Yes, Write a sample statement. Yes. It can be instantiated as follows by referencing the Outer class.Outer.Inner in = new Outer.Inner();

90.What are the constraints on Static Inner Classes?
It cannot access non-static members of the outer class.It cannot use this reference to the outer class.

91.How many class files are produced for source file having one Outer class and one Inner class?
Two class files will be produced as follows:Outer.classOuter$Inner.class

92.In Java, How to make an object completely encapsulated?
All the instance variables should be declared as private and public getter and setter methods should be provided for accessing the instance variables.

93..How is polymorphism acheived in java?
Inheritance, Overloading and Overriding are used to acheive Polymorphism in java.

94..What is a destructor?
Destructor is an operation that frees the state of an object and/or destroys the object itself. In Java, there is no concept of destructors. Its taken care by the JVM.

95. What are the core OOP's concepts?
Abstraction, Encapsulation,Inheritance and Polymorphism are the core OOP's concepts.

96.What is meant by abstraction?
Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. Its the process of focussing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model.

97.What is meant by Encapsulation?
Encapsulation is the process of compartmentalising the elements of an abtraction that defines the structure and behaviour. Encapsulation helps to separate the contractual interface of an abstraction and implementation.

98.What is an Interface?
Interface is an outside view of a class or object which emphaizes its abstraction while hiding its structure and secrets of its behaviour.

99.What is a base class?
Base class is the most generalised class in a class structure. Most applications have such root classes. In Java, Object is the base class for all classes.

100.What is a subclass?
Subclass is a class that inherits from one or more classes.

101.What is a superclass?
Superclass is a class from which another class inherits.

102.What is a constructor?
Constructor is an operation that creates an object and/or initialises its state.

103.What is meant by Binding?
Binding denotes association of a name with a class

104.What is meant by static binding?
Static binding is a binding in which the class association is made during compile time. This is also called as Early binding.

105.What is meant by Dynamic binding?
Dynamic binding is a binding in which the class association is not made until the object is created at execution time. It is also called as Late binding.

106.Define Modularity?
Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules.

107.What is meant by Persistence?
Persistence is the property of an object by which its existence transcends space and time.

108.What is colloboration?
Colloboration is a process whereby several objects cooperate to provide some higher level behaviour.


Post a Comment