TutorialsPoint.com Java Interview Questions Flashcards

1
Q

Five features of Java?

A
  1. Object Oriented
  2. Platform independent
  3. Robust
  4. Interpreted
  5. Multi-threaded
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Why architectural neutral?

A

Compiler generates byte code which then can be interpreted by Java runtime

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What do you know about Java?

A
  1. High level programming language originally developed by Sun Microsystems.
  2. Runs on many platforms such as Windows, Mac OS, Unix various OS
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Supported platforms?

A
  1. Windows
  2. Mac OS
  3. Unix/Linux various versions
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How Java enabled high performance?

A

Uses just-in-time compiler which is a program that turns Java byte code which is interpreted into instructions that can be sent directly to the processor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why Java is considered dynamic?

A

Designed to adapt to an evolving environment

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is Java Virtual Machine (JVM)?

A
  1. Java is compiled into platform independent byte code.
  2. The byte code is distributed over the web and interpreted by the Java Virtual Machine on the platform it is being run.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

List two or three Java IDEs?

A
  1. Eclipse
  2. Netbeans
  3. IntelliJ
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

List some Java keywords unlike C, C++?

A
  1. Import
  2. Super
  3. Finally
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Describe Object?

A
  1. A runtime entity in which it’s state is stored in fields and behavior is shown via methods.
  2. Methods operate on object’s internal state and serve as the primary mechanism for object-to-object communication.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Define class?

A
  1. A blue print from which individual objects are created.
  2. Contains fields and methods to describe the behavior of an object.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What kind of variables a class can consist of?

A
  1. Local variable
  2. Instance variables
  3. Class variables
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is a local variable?

A
  1. Variables defined inside methods, constructors, or blocks.
  2. Declared and initialized within method and destroyed when method completes.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is an instance variable?

A
  1. Variable within a class but outside any method.
  2. Instantiated when class is loaded.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is a class variable?

A

Declared within a class, outside any method, with the static keyword.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is Singleton class?

A

Ensures that only one instance of a class is created.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Define Constructor?

A
  1. A special method which is invoked when a new object is created.
  2. Every class has a constructor.
  3. Java compiler builds default constructor when none explicitly found.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

List three steps for creating an Object for a class?

A
  1. Declared
  2. Instantiated
  3. Initialized
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Default value of byte data type?

A

0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Default value of float and double data type?

A
  1. 0.0f
  2. 0.0d
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

When byte data type is used?

A

Save space in large arrays, in place of integers, since 4 times smaller than int.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is a static variable?

A

Class variable which is declared with static keyword in class, but outside a method, constructor, or block

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Define Access Modifier?

A

Used to set access levels for classes, variables, methods, and constructors. Defaults to package access level.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is protected access modifier?

A

Variables, methods, and constructors declared protected in a superclass can be accessed only by:

  1. subclasses in other package
  2. any class within the package of the protected members’ class.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is synchronized Non Access Modifier?

A

Used to indicate that method can be accessed by only one thread at a time.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Variables used in switch statement can be used with which datatypes?

A
  1. byte
  2. short
  3. int
  4. char
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

When parseInt() method can be used?

A
  1. Used to get primitive data type of a certain String.
  2. For translating base 2, 8, 10, and 16 numbers stored as strings into integers.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Why is String class considered immutable?

A

Once created a String object cannot be changed. This enables safe sharing between many threads which is essential for multithreaded programming.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Which operators have highest precedence?

A
  1. ()
  2. []
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Why is StringBuffer mutable?

A

When necessary to make changes, StringBuffer to be used instead of String.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What is difference between String, StringBuffer, and StringBuilder classes?

A
  1. String cannot be updated and thus to concat strings requires create of new String object. It is thread safe.
  2. StringBuilder is faster, but not thread safe. Recommended for single thread programs.
  3. StringBuffer is thread safe
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Which package is used for pattern matching with regular expressions?

A

java.util.regex

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

java.util.regex consists of which classes?

A
  1. Pattern
  2. Matcher
  3. PatternSyntaxException
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What is finalize() method?

A
  1. Method which is called just before object’s final destruction by the garbage collector.
  2. Can be used to ensure object terminates cleanly.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is an Exception?

A
  1. A problem that arises during the execution of a program.
  2. Exceptions are caught by handlers positioned along the thread’s method invocation stack.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Explain Checked Exceptions?

A
  1. Exceptions that are checked at compile time to ensure code handles them properly.
    • If code within a method throws a checked exception, then the method must either handle the exception or specify the exception using throws keyword.
  2. Examples:
    1. FileNotFoundException
    2. IOException
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Explain Runtime Exception?

A

Exceptions that aren’t checked at compile time and which should be preventable by proper coding.

Examples:

  1. ArrayIndexOutOfBoundsException
  2. ClassCastException
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What are the two subclasses under Exception class?

A
  1. IOException (checked exception)
  2. RuntimeException (runtime exception)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

When throws keyword is used?

A

If method does not handle a checked exception, the method must declare it using the throws keyword.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

When throw keyword is used?

A

An exception can be thrown, either newly instantiated one or an exception that was just caught, by using throw keyword.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

How is finally used under Exception Handling?

A

Used to create a block of code that follows a try block. It executes whether or not an exception has occurred.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What things to be kept in mind while creating own exceptions?

A
  1. All exceptions must be child of throwable
  2. Depending on exception type:
    1. Must extend Exception class to write checked exception that is to be enforced by the Handle or Declare Rule
    2. Must extend RuntimeException when writing runtime exception
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

Define inheritance?

A

Process where one class is built upon another class inheriting (re-using) methods and adding of other methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

When super keyword used?

A
  1. If method overrides its super class’s method, overridden method can be invoked using super keyword. Applies to constructors too.
  2. Also used to refer to hidden field (when super class and sub-class have same field name which is a bad practice).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

What is Polymorphism?

A

Ability of an object to take on many forms.

Common uses:

  1. When parent class reference is used to refer to child class object.
    • Deer d = new Deer();
    • Animal a = d;
    • Vegetarian v = d;
    • Object o = d;
  2. When class has multiple inheritance.
    • public class Deer extends Animal implements Vegetarian{}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

What is abstraction?

A
  1. Ability to make a class abstract in OOP.
  2. Abstract classes usually have one or more abstract methods in which method is declared but not implemented.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What is Abstract class?

A
  1. Class cannot be Instantiated and is either partially or not at all implemented.
  2. The class contains one or more abstract methods which are simply method declarations without body.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

When Abstract methods are used?

A

When wanting a class to contain a particular method but you want actual implementation to be determined by child classes, you declare parent class as abstract.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

What is Encapsulation?

A

Technique of making fields private and providing access to the fields via public methods. AKA data hiding.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

What are primary benefits of Encapsulation?

A
  1. Ability to modify implemented code without breaking code of others using our code.
  2. Gives maintainability, flexibility, and extensibility to our code.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

What is an interface?

A
  1. Collection of abstract methods.
  2. A class implements an interface, thereby inheriting the abstract methods of the interface.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

Give some features of Interface?

A
  1. Cannot be Instantiated
  2. Does not contain any constructors
  3. All methods are abstract (not implemented)
  4. All fields automatically constants (public static final)
  5. Class can implement multiple interfaces
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

Define Packages in Java?

A

A group of related types (classes, interfaces, enumerations, and annotations) providing access protection and name space management.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

Why packages are used?

A
  1. Prevent naming conflicts
  2. To control access
  3. Make searching/locating and usage of classes, interfaces, enumerations, and annotations, etc. easier.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

Define Multithreaded program?

A
  1. Contains two or more parts that can run concurrently.
  2. Each part is called a thread and each thread defines a separate path of execution.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

Explain two ways in which a Thread can be created?

A
  1. Implementing Runnable interface
  2. Extending Thread class
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

What is an applet?

A
  1. Java program that runs in a Web browser.
  2. An applet can be fully functional because it has entire Java API at its disposal.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

An applet extends which class?

A

java.applet.Applet

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

Explain garbage collection in Java?

A

Used to free the memory by cleaning objects no longer referenced.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

Define immutable object?

A

Can’t be changed once created.

Example: String

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

Explain the usage of this() with constructors?

A

Used with variables or methods and used to call constructor of same class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

Explain Set Interface?

A
  1. Collection of elements which cannot contain duplicate elements.
  2. Contains only methods inherited from Collection and adds restriction that duplicate elements are prohibited.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

Explain TreeSet?

A

It is Set implemented when we want elements in sorted order.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

What is Comparable Interface?

A
  1. Used to sort collections and arrays of objects using collections.sort() and Java.utils.
  2. Objects of the class implementing the Comparable interface can be ordered.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

Difference between throw and throws?

A
  1. Throw is used to trigger an exception.
  2. Throws is used in declaration of exception.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

Explain the following:

public static void main (String args[])

A
  1. public: is the access specifier
  2. static: allows main() to be called without instantiating a particular instance of a class
  3. void: affirms the compiler that no value is returned
  4. main(): method is called at the beginning of Java program
  5. String args[]: args parameter is an instance array of class String
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

Define JRE (Java Runtime Environment)?

A

Implementation of the Java Virtual Machine which invokes Java programs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

What is a JAR file?

A
  1. Java Archive file which aggregates many files into one.
  2. Holds Java classes in a library.
  3. Built in ZIP file format and has .jar file extension.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

What is WAR file?

A
  1. Web Archive file used to store XML, Java classes, and JavaServer pages.
  2. Used to distribute a collection of JavaServer Pages, Java Servlets, Java classes, XML files, static Web pages, etc.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

Define JIT compiler?

A
  1. Just-in-time compiler that improves runtime performance of computer programs based on bytecode.
  2. It compiles the bytecode into platform specific executable code that is immediately executed.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

Difference between object oriented programming language and object based programming language?

A

Object based follows all features of OOP except inheritance.

Example: JavaScript is object based.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

What is purpose of default constructor?

A

Java compiler creates default constructor only if there is no constructor in the class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

Can a constructor be made final?

A

No

You use the final keyword in a method declaration to indicate that the method cannot be overridden

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

What is static block?

A

Used to initialize the static data member. It is used before main method at time of classloading.

A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

static { // whatever code is needed for initialization goes here }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

Define composition?

A

Holding the reference of another class within some class.

Example:

class Fruit { … }

class Apple { private Fruit fruit = new Fruit(); //… }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
76
Q

What is function/method overloading?

A

When a class has multiple methods by same name but different parameters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
77
Q

What is function/method overriding?

A

When a subclass provides a specific implementation of a method that is already provided by its parent class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
78
Q

What is final class and final method?

A
  1. Class declared as final cannot have subclasses.
  2. Methods declared as final cannot be overridden.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
79
Q

What is NullPointerException?

A

NullPointerException is thrown when calling the instance method of a null object, accessing or modifying the field of a null object.

To prevent:

public void doSomething(Integer num)

{ if (num != null) { // do something to num } }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
80
Q

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

A
  1. By invoking its sleep() or wait() method
  2. By blocking on IO
  3. By unsuccessfully attempting to acquire an object’s lock
  4. Invoking deprecated suspend() method.
81
Q

How does multi-threading take place on a computer with a single CPU?

A

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

82
Q

What invokes a thread’s run() method?

A

After a thread is started, via start() method of the Thread class, the JVM invokes the thread’s run() method when thread is initially executed.

83
Q

Does it matter in which order catch statements for FileNotFoundException and IOException are written?

A

Yes. FileNotFoundException is inherited from IOException. Exception’s subclasses have to be caught first.

84
Q

What is difference between yielding and sleeping?

A
  1. When task invokes yield() method, it returns to ready state.
  2. When task invokes sleep() method, it returns to waiting state.
85
Q

Why Vector class is used?

A

Ability to implement a growable array of objects.

86
Q

How many bits are used to represent ASCII, UTF-16, and UTF8 chars?

A
  1. ASCII: 8
  2. UTF-8: one to four 8-bit units
  3. UTF-16: one or two 16-bit units

UTF: Unicode Transformation Format

87
Q

What are wrapper classes?

A

Classes that allow primitive types to be accessed as objects.

Example: Integer, Character, Double, Boolean, etc.

88
Q

What is difference between a Window and a Frame?

A

Frame class extends Window to define a window with a title and a border.

89
Q

Which package has light weight components?

A

java.Swing package.

All components in Swing except JApplet, JDialog, JFrame, and JWindow are lightweight components.

90
Q

What is difference between paint() and repaint() methods?

A
  1. The paint() method supports painting via Graphics object.
  2. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.
91
Q

What is the purpose of the File class?

A

Used to create objects that provide access to files and directories of local file system.

92
Q

What is difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

A
  1. Reader/Writer is character-oriented.
  2. InputStream/OutputStream is byte-oriented.
93
Q

Which class is used for obtaining design information about an object?

A

The Class class.

The java.lang.Class class instance represents classes and interfaces in a running Java application.

Example:
Class cls = Class.forName(“ClassDemo”);

ClassLoader cLoader = cls.getClassLoader();

94
Q

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

A
  1. A static variable is associated with the class as a whole rather than specific instances of a class.
  2. Non-static variables take on their own values with each object instance.
95
Q

What is Serialization and deserialization?

A
  1. Serialization is process of writing the state of object to a byte stream.
  2. Deserialization is process of restoring these objects.
96
Q

What are use cases?

A

Describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance.

97
Q

Explain the use of subclass in a Java program?

A

Subclass inherits all the public and protected methods and the implementation. It also inherits all the default modifier methods and their implementation.

98
Q

How to add a menu shortcut to menu item?

A
  1. If there is a button instance called b1, you add short cut by calling b1.setMnemonic(‘F’) so user can use Alt+F to click the button.
  2. Using setShortcut(MenuShortcut s) method in MenuItem class.
99
Q

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

A

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

100
Q

What is the difference between Swing and AWT components?

A
  1. AWT components are heavyweight, whereas Swing components are lightweight.
  2. Heavyweight components depend on the local windowing toolkit. For example when java.awt.Button is running on the Java platform for Unix platform, it maps to a real Motif button.
101
Q

What is the difference between constructors and other methods?

A
  1. Constructors must have same name as the class and cannot return a value.
  2. Constructors are only called once while other methods could be called many times.
102
Q

Is there any limitation of using inheritance?

A

Yes, since inheritance inherits everything from the superclass and interface, it may make the subclass error-prone in some situations when dynamic overriding or dynamic overloading.

103
Q

When is ArrayStoreException thrown?

A

When copying elements between arrays, if the source or destination arguments are not arrays or their types are not compatible.

104
Q

Can you call one constructor from another constructor?

A

Yes, use this() syntax.

105
Q

What is difference between methods sleep() and wait()?

A
  1. The code sleep(2000) puts thread aside for exactly 2 seconds whereas wait(2000) causes a wait of up to 2 seconds.
  2. A thread could stop waiting earlier if it receives the notify() or notifyAll() call.
  3. wait() is defined in the class Object. sleep() is defined in the class Thread.
106
Q

When ArithmeticException is thrown?

A
  1. When integer is divided by zero.
  2. Non-terminating decimal numbers using BigDecimal. For example 1/3 = 0.3333…
107
Q

What is a transient variable?

A

A variable that may not be serialized during Serialization and which is initialized by its default value during de-serialization. Useful for minimizing network traffic.

Example:

private Image image;

private transient Image thumbnailImage;

108
Q

What is synchronization?

A
  1. The capability to control the access of multiple threads to shared resources.
  2. The synchronized keyword in Java provides locking which ensures mutual exclusive access of shared resource and prevents data race.
109
Q

What is the Collections API or Collections Framework?

A

The Collections API or Framework is a set of interfaces (ex: see diagram below), implementations (ex: HashSet, TreeSet), aggregate operations (ex: forEach), and algorithms (ex: Collections.sort) that support operations on collections of objects.

110
Q

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

A

No, program can use up memory resources faster than they are garbage collected. It is possible for programs to create objects that are not subject to garbage collection.

111
Q

What class is the immediate superclass of the Applet class?

A

Panel. A panel provides space in which an application can attach any other component, including other panels.

112
Q

Which Java operator is right associative?

A

The = operator.

113
Q

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

A
  1. A break terminates the statement for which it applies (switch, for, do, or while).
  2. A continue statement is used to end the current loop iteration and return control to the loop statement.
114
Q

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

A

Only may be accessed within the class in which it is declared.

115
Q

What is the purpose of the System class?

A

Provides access to system resources.

116
Q

List primitive Java types?

A
  1. Integer types:
    1. byte (8 bit signed)
    2. short (16 bit signed)
    3. int (32 bit signed)
    4. long (64 bit signed or unsigned)
  2. Floating types:
    1. float (32 bit)
    2. double (64 bit)
  3. char (single 16-bit Unicode character)
  4. boolean
117
Q

What is the relationship between clipping and repainting under AWT?

A

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

118
Q

Which class is the immediate superclass of the Container class?

A

Component

119
Q

What class of exceptions are generated by the Java run-time system?

A
  1. RuntimeException
  2. Error
120
Q

Under what conditions is an object’s finalize() method invoked by the garbage collector?

A

When the object has become unreachable

121
Q

How can a dead thread be restarted?

A

It can’t

122
Q

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

A

Division by zero

123
Q

Variable of boolean type is automatically initialized as?

A

false

124
Q

Can try statements be nested?

A

Yes

125
Q

What are ClassLoaders?

A

Java ClassLoader loads a java class file into java virtual machine.

126
Q

What is the difference between an Interface and an Abstract class?

A
  1. An abstract class can have instance methods that implement default behavior.
  2. An interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation.
127
Q

What will happen if you remove static modifier from the signature of the main method?

A

Program throws NoSuchMethodError error at runtime.

128
Q

What is the default value of an object reference declared as an instance variable?

A

Null, unless defined explicitly.

129
Q

Can a top level class be private or protected?

A

No. Must use public or no access modifier.

130
Q

Why do we need wrapper classes?

A

We can pass them around as method parameters where a method expects an object. It also provides utility methods.

131
Q

What is the difference between error and an exception?

A
  1. An error is an unrecoverable condition occurring at runtime such as OutOfMemory error.
  2. Exceptions can be caught and dealt with by the program.
132
Q

Is it necessary that each try block must be followed by a catch block?

A

No. It should be followed by either a catch block or a finally block.

133
Q

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

A

ready

134
Q

What is the Locale class?

A

It is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

135
Q

What are synchronized methods and synchronized statements?

A
  1. Synchronized methods are methods that are used to control access to an object.
  2. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
136
Q

What is runtime polymorphism or dynamic method dispatch?

A

A process in which a call to an overridden method is resolved at runtime rather than at compile time. In this process an overridden method is called through the reference variable of a superclass.

137
Q

What is Dynamic Binding (late binding)?

A

Refers to the linking of a procedure call to the code to be executed in response to the call. Occurs when the code associated with a given procedure call is not known until the time of the call at run-time.

138
Q

Can a constructor be inherited?

A

No

139
Q

What are the advantages of ArrayList over arrays?

A
  1. Can grow dynamically
  2. Provides more powerful insertion and search mechanisms than arrays.
140
Q

Why deletion in LinkedList is faster than ArrayList?

A

It only involves updating the next pointer in the before the deleted node and the previous pointer in the node after the deleted node.

141
Q

How to decide when to use ArrayList or LinkedList?

A
  1. LinkedList when frequently adding and removing from middle of the list and only access list elements sequentially.
  2. ArrayList when you need to support random access, without inserting or removing other than from the end.
142
Q

What is a Values Collection View?

A

A collection returned by the values() method of the Map Interface. It contains all the objects present as values in the map.

143
Q

What is dot operator?

A
  1. The dot operator (.) is used to access the instance variables and methods of class objects.
  2. Also used to access classes and sub-packages from a package.
144
Q

Where and how can you use a private constructor?

A

When you don’t want other classes to Instantiate the object and to prevent subclassing.

145
Q

What is type casting?

A

It the treating of a variable of one type as though it is another type.

Example of casting to int using (int):

double x = 9.997;

int nx = (int) x;;

int rnx = (int) Math.round(x);

146
Q

Describe life cycle of thread?

A
  1. Newborn state
  2. Runnable state
  3. Running state
  4. Blocked state
  5. Dead state
147
Q

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

A
  1. >> operator carries the sign bit when shifting right.
  2. >>> operator zero-fills bits when shifting right.
148
Q

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

A

setBounds()

149
Q

What is the range of the short type?

A

-(2^15) to 2^15 - 1

150
Q

What is the immediate superclass of Menu?

A

MenuItem

151
Q

Does Java allow Default Arguments?

A

No

152
Q

Which Numbers is denoted by leading zero in Java?

A

Octal. For example 06

153
Q

Which Number is denoted by leading 0x or 0X?

A

Hexadecimal. Example oxF

154
Q

Break statement can use labels?

A

Yes.

Example:

first:

for( int i = 0; i < 10; i++) {

second:

for(int j = 0; j < 5; j ++ ) {

break first; }

}

155
Q

Where import statement is used in Java program?

A

It is allowed at the beginning of the program after package statement.

156
Q

Explain suspend() method under Thread class?

A

Used to pause or temporarily stop execution of the thread.

157
Q

Explain isAlive() method under Thread class?

A

It used to determine whether a thread is still running or not.

158
Q

What is currentThread()?

A

A public static method used to obtain a reference to the current thread.

159
Q

Explain main thread under Thread class execution?

A

The main thread is created automatically and begins to execute immediately when a program starts. It is a thread from which all child threads originate.

160
Q

Life cycle of an applet includes which steps?

A
  1. Initialization
  2. Starting
  3. Stopping
  4. Destroying
  5. Painting
161
Q

Why is the role of init() method under applets?

A

It initialized the applet and is the first method to be called.

162
Q

Which method is called by Applet class to load an image?

A

getImage(URL object,file name)

Example:

import java.applet.Applet;

import java.awt.Graphics;

import java.awt.Image;

public class ImageApplet extends Applet {

Image im;

public void init() {

im = getImage(getDocumentBase(), “image.jpg”);

}

public void paint(Graphics g) {

g.drawImage(im, 0, 0, this);

}

}

163
Q

Define CODE as an attribute of Applet?

A

It is used to specify the name of the applet class.

Example:

<applet>CODE="Main.class" WIDTH="800" HEIGHT="500"&gt; </applet>

164
Q

Define canvas?

A

It is a simple drawing surface which is used for painting images or to perform other graphical operations.

Canvas control represents a rectangular area where application can draw something or can receive inputs created by user.

165
Q

Define Networking Programming?

A

It refers to writing programs that execute across multiple devices, in which the devices are all connected to each other using a network.

166
Q

What is a Socket?

A

Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.

167
Q

Advantages of Java Sockets?

A
  1. Sockets are flexible and sufficient.
  2. Efficient socket based programming can be easily implemented for general communications.
168
Q

What are the disadvantages of Sockets?

A
  1. Socket based communications allows only to send packets of raw data between applications.
  2. Both the client-side and server-side have to provide mechanisms to make data useful in any way.
169
Q

Which class is used by server applications to obtain a port and listen for client requests?

A

Java.net.ServerSocket

170
Q

Which class represents the socket that both the client and server use to communicate with each other?

A

Java.net.Socket

171
Q

Why Generics are used in Java?

A
  • Stronger type checks at compile time.
  • Elimination of casts.
  • Can implement generic algorithms that work on collections of different types

Preferred: Using generics:
List<string> list = new ArrayList<string>(); list.add("hello");</string></string>

String s = list.get(0); // no cast

Using cast:

List list = new ArrayList();

list.add(“hello”);

String s = (String) list.get(0); // cast

172
Q

What environment variables do I need to set my machine in order to be able to run Java programs?

A

CLASSPATH - tells applications, including the JDK tools, where to look for user classes

PATH - conveniently run the executables (javac.exe, java.exe, javadoc.exe, and so on) from any directory

173
Q

Is there any need to import Java.lang package?

A

No, JVM loads by default.

174
Q

What is Nested top-level class?

A

If a class is declared within a class and specify the static modifier, the compiler treats the class like any other top-level class. Nested top-level class is an inner class.

175
Q

What is Externalizable interface?

A

An interface in which contains two methods readExternal and writeExternal. These methods give you control over the serialization mechanism.

176
Q

If System.exit(0); is written at the end of the try block, will the finally block still execute?

A

No because control immediately goes out of the program.

177
Q

What is daemon thread?

A

Low priority thread which runs intermittently in the background doing garbage collection operation for the Java runtime system.

178
Q

Which method is used to create the daemon thread?

A

setDaemon

179
Q

Which method must be implemented by all threads?

A

run()

180
Q

What is the GregorianCalendar class?

A

Provides support for traditional Western calendars.

181
Q

What is the SimpleTimeZone class?

A

It is a concrete subclass of TimeZone that represents time zone for use with a Gregorian calendar.

  • Holds an offset from GMT, called raw offset.
  • Also holds start and end rules for a daylight saving time schedule.
182
Q

What is the difference between the size and capacity of a Vector?

A

Size is actual number of elements stored.

Capacity is the maximum number of elements that can be stored at a given instance of time.

183
Q

Can a vector contain heterogeneous objects?

A

Yes because it stores everything in terms of Object.

184
Q

What is an enumeration?

A

Enumeration is a special data type that enables a variable to be a set of predefined constants

Example of declaration:
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

Example of iteration:
for (Planet p : Planet.values()) { System.out.printf(“Your weight on %s is %f%n”, p, p.surfaceWeight(mass)); }

185
Q

What is the difference between Path and ClassPath?

A

They are both operating system level environment variables.

Path defines where system can find the executables (.exe) files.

ClassPath is used to specify location of .class files.

186
Q

Can a class declared as private be accessed outside its package?

A

No; private is the most restrictive access modifier

187
Q

What are the restrictions imposed on a static method or a static block of code? Aka class method

A

Class (static) methods:

  1. Cannot access instance variables or instance methods directly
  2. Must use an object reference
  3. Cannot use the “this” keyword as there is no instance for “this” to refer to.
188
Q

Can an interface extend another interface?

A

Yes and it can extend multiple interfaces.

189
Q

Which object oriented Concept is achieved by using overloading and overriding?

A

Polymorphism

190
Q

What is an object’s lock and which objects have locks?

A

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

191
Q

What is Downcasting?

A

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

Example:

class Parent{ /* … */}

class ChildClass extends Parent { /* … */ }

public class Tester {

public static void main (String args[]) {

Parent p = new Parent ( );

ChildClass c = (ChildClass) p;

} }

192
Q

What are order of precedence and associativity and how are the used?

A

Order of precedence determines order in which operators are evaluated in expressions.

Associativity determines whether expression is evaluated left-to-right or right-to-left.

Examples of right-to-left Associativity:

Unary: ++, - -, !, ~

Conditional: ?:

Assignment: =, +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=

193
Q

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

A

May only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.

194
Q

What is the difference between inner class and nested class?

A
  1. When a class is defined within a scope of another class, then it becomes inner class.
  2. If the access modifier of the inner class is static, then it becomes nested class.
195
Q

What restrictions are placed on method overriding?

A
  1. Must have same name, argument list, and return type.
  2. Cannot limit the access of the method it overrides.
196
Q

What is constructor chaining and how is it achieved?

A

A child object constructor always first needs to construct its parent. It is done via an implicit call to the no-args constructor as the first statement.

197
Q

Can a double value be cast to a byte?

A

Yes

double d1 = 10.5; // 8 bytes
 // byte b1 = d1; // error as 8 bytes to 1 byte

byte b1 = (byte) d1; // 8 bytes cast to 1 byte
System.out.println(b1); // prints 10

198
Q

How does a try statement determine which catch clause should be used to handle an exception?

A

The catch clauses are examined in order they appear. The first one capable of handling the exception is executed. The remaining are ignored.

199
Q

What will be the default values of all the elements of an array defined as an instance variable?

A

If the array is an array of primitive types, then all the elements will be initialized to the default value corresponding to that primitive type.