Sunteți pe pagina 1din 31

1. What if the main method is declared as private?

The program compiles properly but at runtime it will give Main method not public. message. 2. What is meant by pass by reference and pass by value in Java? Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value. 3. If youre overriding the method equals() of an object, which other method you might also consider? hashCode(). 4. What is Byte Code? (or) What gives java its write once and run anywhere nature? All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent. 5. Expain the reason for each keyword of public static void main(String args[])? public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public. static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static. void: main does not return anything so the return type must be void. The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line. 6. What is encapsulation? Encapsulation describes the ability of an object to hide its data and methods from the rest of the world. 7. What if the static modifier is removed from the signature of the main method? (or) What if I do not provide the String array as the argument to the method? Program compiles. But at runtime throws an error NoSuchMethodError. 8. Why oracle Type 4 driver is named as oracle thin driver? Oracle provides a Type 4 JDBC driver, referred to as the Oracle thin driver. This driver includes its own implementation of a TCP/IP version of Oracles Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.

9. What is the difference between final, finally and finalize? (or) What does it mean that a class or member is final? o final -declare constant o finally - handles exception o finalize - helps in garbage collection. Variables defined in an interface are implicitly final. A final class cant be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method cant be overridden when its class is inherited. You cant change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method. 10. What is the Java API? The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets. 11. What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars. 12. What is the ResourceBundle class? The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the programs appearance to the particular locale in which it is being run. 13. Why there are no global variables in Java? Global variables are globally accessible. Java does not support globally accessible variables due to following reasons: The global variables breaks the referential transparency. Global variables creates collisions in namespace. 14. How to convert String to Number in java program? The valueOf() function of Integer class is is used to convert string to Number. Here is the code example: String numString = 1000; int id=Integer.valueOf(numString).intValue(); 15. What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar.

16. What is the difference between a while statement and a do statement? A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) 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 loop body at least once. 17. What is the Locale class? The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region. 18. Describe the principles of OOPS. There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation. 19. Explain the Inheritance principle. Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places. 20. What is implicit casting? Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios. Example: int i = 1000; ong j = i; //Implicit casting 21. Is sizeof a keyword in java? The sizeof operator is not a keyword. 22. What is a native method? A native method is a method that is implemented in a language other than Java. 23. In System.out.println(), what is System, out and println? System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object. 24. What are Encapsulation, Inheritance and Polymorphism (or) Explain the Polymorphism principle. Explain the different forms of Polymorphism.

Polymorphism in simple terms means 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. Polymorphism exists in three distinct forms in Java: Method overloading Method overriding through inheritance Method overriding through the Java interface. 25. What is explicit casting? Explicit casting in the process in which the complier are specifically informed to about transforming the object. Example long i = 700.20; int j = (int) i; //Explicit casting. 26. What is the Java Virtual Machine (JVM)? The Java Virtual Machine is software that can be ported onto various hardware-based platforms. 27. What do you understand by downcasting? The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy. 28. What are Java Access Specifiers? (or) What is the difference between public, private, protected and default Access Specifiers? (or) What are different types of access modifiers? Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing, privileges to parts of a program such as functions and variables. These are: Public : accessible to all classes Protected : accessible to the classes within the same package and any subclasses. Private : accessible only to the class to which they belong Default : accessible to the class to which they belong and to subclasses within the same package. 29. Which class is the superclass of every class? Object.

30. Name primitive Java types. The 8 primitive types are byte, char, short, int, long, float, double, and boolean. 31. What is the difference between static and non-static variables? (or) What is a static method? A static variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static variables i.e. there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class. These are declared outside a class and stored in static memory. Class variables are mostly used for constants. Static variables are always called by the class name. This variable is created when the program starts and gets destroyed when the programs stops. The scope of the class variable is same an instance variable. Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than any object of the class and doesnt apply to an object or even require that any objects of the class have been instantiated. Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you cant override a static method with a non-static method. In other words, you cant change a static method into an instance method in a subclass. Non-static variables take on unique values with each object instance. 32. What is the difference between the boolean & operator and the && operator? If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. 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. If the first operand evaluates to false, the evaluation of the second operand is skipped. 33. 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. 34. What if I write static public void instead of public static void? Program compiles and runs properly. 35. What is the difference between declaring a variable and defining a variable? In declaration we only mention the type of the variable and its name without initializing it. Defining means declaration + initialization. E.g. String s; is just a declaration while String s = new String (bob); Or String s = bob; are both definitions. 36. What type of parameter passing does Java support?

In Java the arguments (primitives and objects) are always passed by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object. 37. Explain the Encapsulation principle. 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. Objects allow procedures to be encapsulated with their data to reduce potential interference. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper. 38. What do you understand by a variable? Variable is a named memory location that can be easily referred 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. 39. What do you understand by numeric promotion? The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integral 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. 40. What do you understand by casting in java language? What are the types of casting? The process of converting one data type to another is called Casting. There are two types of casting in Java; these are implicit casting and explicit casting. 41. What is the first argument of the String array in main method? The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name. If we do not provide any arguments on the command line, then the String array of main method will be empty but not null. 42. How can one prove that the array is not null but empty? Print array.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print array.length. 43. Can an application have multiple classes having main method? Yes. While starting the application we mention the class name to be run. The JVM will look for the main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method. 44. When is static variable loaded? Is it at compile time or runtime? When exactly a static block is loaded in Java?

Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks. Static block is not member of a class, they do not have a return statement and they cannot be called directly. Cannot contain this or super. They are primarily used to initialize static fields. 45. Can I have multiple main methods in the same class? We can have multiple overloaded main methods but there can be only one main method with the following signature : public static void main(String[] args) {} No the program fails to compile. The compiler says that the main method is already defined in class.

the

46. Explain working of Java Virtual Machine (JVM)? JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte codes. 47. Why is UTFDataFormatException thrown by DataOutputStream.writeUTF() when serializing a String? DataOutputStream.writeUTF() does not support writing out strings larger than 64K. The first two bytes of a UTF string in the stream are the length of the string. If a java.lang.String is larger than 64K, it needs to be stored in the stream by an alternative method rather than depending on the default method of storing a String in the stream, writeUTF. 48. Why is OutOfMemoryError thrown after writing a large number of objects into an ObjectOutputStream? The ObjectOutputStream maintains a table mapping objects written into the stream to a handle. The first time an object is written to a stream, its contents are written into the stream; subsequent writes of the object result in a handle to the object being written into the stream. This table maintains references to objects that might otherwise be unreachable by an application, thus, resulting in an unexpected situation of running out of memory. A call to the ObjectOutputStream.reset() method resets the object/handle table to its initial state, allowing all previously written objects to be eligible for garbage collection. 49. How can I get the serialVersionUID of a class? By running the serialver tool with the name of the class as the command line argumet, as shown in the example that follows: serialver java.lang.String. 50. What is abstraction?

An abstraction is an idea, concept, or word which defines the phenomena which make up the concrete events or things which the abstraction refers to, the referents. 51. Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK. 52. What is phantom memory?

Phantom memory is false memory. Memory that does not exist in reality.

53. Can a method be static and synchronized? A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang. Class instance associated with the object. It is similar to saying: synchronized(XYZ.class) { } 54. What is difference between String and StringTokenizer? A StringTokenizer is utility class used to break up string. Example: StringTokenizer st = new StringTokenizer(Hello World); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } Output: Hello World 55. Why threads block or enters to waiting state on I/O?

Threads enters to waiting state or block on I/O because other threads can execute while the I/O operations are performed. 56. What are transient variables in java?

Transient variables are variable that cannot be serialized.

57. How Observer and Observable are used? Subclass of Observable class maintain a list of observers. Whenever an Observable object is updated, it invokes the update() method of each of its observers to notify the observers that it has a changed state. An observer is any object that implements the interface Observer. 58. What is Synchronization? Synchronization is the ability to control the access of multiple threads to shared resources. Synchronization stops multithreading. With synchronization , at a time only one thread will be able to access a shared resource. 59. What is List interface ?

List is an ordered collection of objects.

60. What is a Vector?

Vector is a dynamic growable array of objects.

61. What is the difference between yield() and sleep()? When a object invokes yield() it returns to ready state. But when an object invokes sleep() method enters to not ready state. 62. What are Wrapper Classes ?

They are wrappers to primitive data types. They allow us to access primitives as objects.

63. Can we call finalize() method ? Yes. Nobody will stop us to call any method , if it is accessible in our class. But a garbage collector cannot call an object's finalize method if that object is reachable. 64. What is the difference between time slicing and preemptive scheduling ? In preemptive scheduling, highest priority task continues execution till it enters a not running state or a higher priority task comes into existence. In time slicing, the task continues its execution for a predefined period of time and reenters the pool of ready tasks. 65. What is the initial state of a thread when it is created and started?

The thread is in ready state.

66. Can we declare an anonymous class as both extending a class and implementing an interface? No. An anonymous class can extend a class or implement an interface, but it cannot be declared to do both. 67. What are the differences between boolean & operator and & operator. When an expression containing the & operator is evaluated, both operands are evaluated. And the & operator is applied to the operand. When an expression containing && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then only the second operand is evaluated otherwise the second part will not get executed. && is also called short cut and. 68. What is the use of the finally block? Finally is the block of code that executes always. The code in finally block will execute even if an exception is occurred. finally will not execute when the user calls System.exit().

69. What is an abstract method ?

An abstract method is a method that don't have a body. It is declared with modifier abstract.

70. what is a the difference between System.err and System.out

We can redirect System.out to another file but we cannot redirect System.err stream.

71. What are the differences between an abstract class and an interface? An abstract class can have concrete method, which is not allowed in an interface. Abstract class can have private or protected methods and variables and only public methods and variables are allowed in interface. We can implement more than one interface , but we can extend only one abstract class. Interfaces provides loose coupling where as abstract class provides tight coupling. 72. What is the difference between synchronized block and synchronized method ? Synchronized blocks place locks for the specified block where as synchronized methods place locks for the entire method. 73. How can you force garbage collection in java? You cannot force Garbage Collection, but you can request for it by calling the method System.gc(). But it doesn't mean that Garbage Collection will start immediately. The garbage collection is a low priority thread of JVM. 74. How can you call a constructor from another constructor ?

By using this() reference.

75. How can you call the constructor of super class ?

By using super() syntax.

76. What's the difference between normal methods and constructors? Constructors must have the same name of the class and can not have a return type. They are called only once, while regular methods can be called whenever required. We cannot explicitly call a constructor. 77. What is the use of packages in java ? Packages are a way to organize files in java when a project consists of more than one module. It helps in resolving name conflicts when different modules have classes with the same names. 78. What must be the order of catch blocks when catching more than one exception?

The sub classes must come first. Otherwise it will give a compile time error.

79.How can we call a method or variable of the super class from child class ?

We can use super.method() or super.variable syntax for this purpose.

80. If you are overriding equals() method of a class, what other methods you might need to override ?

hashCode

81. How can you create your own exception ?

Our class must extend either Exception or its sub class.

82. What is serialization ?

Serialization is the process of saving the state of an object.

83. What is de-serialization?

De-serialization is the process of restoring the state of an object.

84. What is externalizable ? It is an interface that extends Serializable. It is having two different methods writeExternal() and readExternal. This interface allows us to customize the output. properly. 85. Does garbage collection guarantee that a program will not run out of memory? Garbage collection does not guarantee that a program will not run out of memory. It is also possible for programs to create objects that are not subject to garbage collection. And there is no guarantee that Garbage Collection thread will be executed. 86. What is a native method?

native method is a method that is implemented in a language other than java.

87. What are different type of exceptions in Java? 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 RuntimeException is called unchecked exception. We don't need to explicitly catch a unchecked exception. 88. Can we catch an error in our java program ? Yes. We can . We can catch anything that is derived from Throwable. Since Error is a sub class of Throwable we can catch an error also.

89. What is thread priority? Thread Priority is an integer value that identifies the relative order in which it should be executed with respect to others. The thread priority values ranging from 1- 10 and the default value is 5. But if a thread have higher priority doesn't means that it will execute first. The thread scheduling depends on the OS. 90. How many times may an object's finalize() method be invoked by the garbage collector?

Only once.

91. What is the difference between a continue statement and a break statement? Break statement results in the immediate 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. 92. What must a class do to implement an interface? It must identify the interface in its implements clause. Also it must provide definition for all the methods in the interface otherwise it must be declared abstract. 93. What isan abstract class? An abstract class is an incomplete class. It is declared with the modifier abstract. We cannot create objects of the abstract class. It is used to specify a common behavioral protocol for all its child classes. 94. What is the difference between notify and notifyAll method ? 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. 95. What does wait method do ?

It causes current thread to wait until either another thread invokes notify or notifyAll method of the current object, or a specified amount of time has elapsed. 96. What are the different states of a thread ?

The different thread states are ready, running, waiting and dead.

97. What is the difference between static and non static inner class ? A non-static inner class can have an object instances that are associated with instances of the class's outer class. A static inner class can not have any object instances. 498. What is the difference between String and StringBuffer class ? Strings are immutable (constant), their values cannot be changed after they are created. StringBuffer support mutable objects,their values can be changed. 99. What is the difference between readers and streams? Readers are character oriented where streams are byte oriented. The readers are having full supportfor Unicode data. 100. What is constructor chaining ? When a constructor of a class is executed it will automatically call the default constructor of the super class (if no explicit call to any of the super class constructor) till the root of the hierarchy. 101. What are the different primitive data type in java ?

There are 8 primitive types in java. boolean , char, byte, short, int long, float, double.

102. What is static ?

static means one per class. static variables are created when the class loads. They are associated with the class. In order to access a static we don't need objects. We can directly access static methods and variable by calling classname.variablename.. 103. Why we cannot override static methods? Static means they are associated with a class. In static methods , the binding mechanism is static binding. So it must be available at the compile time. 104. What is the difference between static and non static variables ? A static variable is associated with the class as a whole rather than with specific instances 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. 105. When does a compiler supplies a default constructor for a class?

If there is no other constructor exist in a class, the compiler will supply a default constructor.

106. What are the restrictions placed on overriding a method ? The overridden method have the exact signature of the super class method, including the return type. The access specified cannot be less restrictive than the super class method. We cannot throw any new exceptions in overridden method. 107. What are the restrictions placed on overloading a method ?

Overloading methods must differ in their parameter list, or number of parameters.

108. What is casting ? Casting means converting one type to another. There are mainly two types of casting. Casting between primitive types and casting between object references. Casting between primitive numeric types is used to convert larger data types to smaller data types. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

109. What is the difference between == and equals ? The equals method can be considered to perform a deep comparison of the value of an object, whereas the == operator performs a shallow comparison. If we are not overriding the equals method both will give the same result. == will is used to compare the object references. It is used to check whether two objects are points to the same reference. 110. What is a void return type ?

void indicates that the method will not return anything.

111. What will happen if an exception is not caught ? An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup, which results in the termination of the program. 112. What are the different ways in which a thread can enter into waiting state? 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() method. 113. What is a ResourceBundle class? The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to create the program's appearance to the particular locale in which it is being run. 114. What is numeric promotion? Numeric promotion is the conversion of a smaller numeric type to a larger numeric type. In numerical promotion, byte, char, and short values are converted to int values. The int, long and float values are converted to the desired types if required. 115. What is the difference between the prefix and postfix forms of the ++ operator?

The prefix form first performs the increment operation and then returns the value of the increment operation. The postfix form first returns the current value of the expression and then performs the increment operation on that value. 116. What are synchronized methods and synchronized statements? Synchronized methods are methods that are declared with the keyword synchronized. A 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. 117. How can we create a thread? A thread can be created by extending Thread class or by implementing Runnable interface. Then we need to override the method public void run(). 118. What is the difference between a switch statement and an if statement? 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. 119. What is hashCode? The hashcode of a Java Object is simply a number (32-bit signed int) that allows an object to be managed by a hash-based data structure. A hashcode should be, equal for equal object (this is mandatory!) , fast to compute based on all or most of the internal state of an object, use all or most of the space of 32-bit integers in a fairly uniform way , and likely to be different even for objects that are very similar. If you are overriding hashCode you need to override equals method also. 120. What is an I/O filter? An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. 121. What is the difference between RandomAccessFile and File?

The File class contains information the files and directories of the local file system. The RandomAccessFile class contains the methods needed to directly access data contained in any part of a file. 122. What is final ? A final is a keyword in java. If final keyword is applied to a variable, then the variable will become a constant. If it applied to method, sub classes cannot override the method. If final keyword is applied to a class we cannot extend from that class. 123. What is the difference among JVM Spec, JVM Implementation, JVM Runtime ? 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. 124. How is the difference between thread and process? A process runs in its own address space. No two processes share their address space. Threads will run in the same address space of the process that owns them. 125. What is the difference between Vector and ArrayList ? Vector is synchronized, ArrayList is not. Vector is having a constructor to specify the incremental capacity. But ArrayList don't have. By default Vector grows by 100% but ArrayList grows by 50% only. 126. What is the difference between Hashtable and HashMap ? Hashtable is synchronized . but HashMap is not synchronized. Hashtable does not allow null values , but HashMap allows null values. 127. What are the access modifiers available in Java. 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.

128. Why java is said to be pass-by-value ? 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. 129. What do you mean by immutable ? How to create an immutable object ? Immutability means an object cannot be modified after it has been initialized. There will not be any setter methods in an immutable class. And normally these classes will be final. 130. What is class loader in java? A class loader is a class that is responsible for loading the class. All JVM contains one class loader called primordial class loader. 131. What is a weak reference ? A weak reference is the one that does nor prevent the referenced object from being garbage collected. The weak reference will not keep the object that it refers to alive. A weak reference is not counted as a reference in garbage collection. This will make the memory use more effective. 132. What is object cloning? It is the process of duplicating an object so that two identical objects will exist in the memory at the same time. 133. What is object pooling? Creating a large number of identical short lived objects is called object pooling. This helps to minimize the need of garbage collection and makes the memory use more effective. 134. What is garbage collection?

Garbage collection is the process of releasing memory used by unreferenced objects. It relieves the programmer from the process of manually releasing the memory used by objects . 135. What is the disadvantage of garbage collection? It adds an overhead that can affect performance. Additionally there is no guarantee that the object will be garbage collected. 136. What is a Dictionary? Dictionary is a parent class for any class that maps keys to values., In a dictionary every key is associated with at most one value. 137. What is JAR file ? JAR stands for Java Archive. This is a file format that enables you to bundle multiple files into a single archive file. A jar file will contains a manifest.mf file inside META-INF folder that describes the version and other features of jar file. 138. Why Java is not fully objective oriented ?

Due to the use of primitives in java, which are not objects.

139. What is a marker interface ? An interface that contains no methods. Eg: Serializable, Cloneable, SingleThreadModel etc. It is used to just mark java classes that support certain capability. 140. What are tag interfaces?

Tag interface is an alternate name for marker interface.

141. What are the restrictions placed on static method ? We cannot override static methods. We cannot access any object variables inside static method. Also the this reference also not available in static methods. 142. What is JVM? JVM stands for Java Virtual Machine. It is the run time for java programs. All are java programs are running inside this JVM only. It converts java byte code to OS specific commands. In addition to governing the execution of an applications byte codes, the virtual machine handles related tasks such as managing the system's memory, providing security against malicious code, and managing multiple threads of program execution. 143. What is java byte code?

Byte code is an sort of intermediate code. The byte code is processed by virtual machine.

144. What is method overloading? Method overloading is the process of creating a new method with the same name and different signature.It means argument must be different. 145. What is method overriding? Method overriding is the process of giving a new definition for an existing method in its child class. It means argument must be same. 146. What is finalize() ? Finalize is a protected method in java. When the garbage collector is executes , it will first call finalize( ), and on the next garbage-collection it reclaim the objects memory. So finalize( ), gives you the chance to perform some cleanup operation at the time of garbage collection. 147. What is multi-threading?

Multi-threading is the scenario where more than one threads are running.

148. What is deadlock? Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread. 149. What is the difference between Iterator and Enumeration? Iterator differ from enumeration in two ways Iterator allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. And , method names have been improved. 150. What is the Locale class?

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

151. What is internationalization? Internationalization is the process of designing an application to that it can be adapted to various languages and regions without changes. 152. What is anonymous class ?

An anonymous class is a type of inner class that don't have any name.

153. What is the difference between URL and URLConnection? A URL represents the location of a resource, and a URLConnection represents a link for accessing or communicating with the resource at the location.

154. What are the two important TCP Socket classes? ServerSocket and Socket. ServerSocket is useful for two-way socket communication. Socket class help us to read and write through the sockets. getInputStream() and getOutputStream() are the two methods available in Socket class. 155. Strings are immutable. But String s="Hello"; String s1=s+"World" returns HelloWorld how ?

Here actually a new object is created with the value of HelloWorld.

156. What is classpath?

Classpath is the path where Java looks for loading class at run time and compile time.

157. What is path?

It is an the location where the OS will look for finding out the executable files and commands.

158. What is java collections?

Java collections is a set of classes, that allows operations on a collection of classes.

159. Can we compile a java program without main? Yes, we can. In order to compile a java program, we don't require any main method. But to execute a java program we must have a main in it (unless it is an applet or servlet). Because main is the starting point of a java program. 160. What is a java compilation unit.

A compilation unit is a java source file.

161. What are the restrictions when overriding a method ? Overridden methods must have the same name, argument list, and return type (i.e., they must have the exact signature of the method we are going to override, including return type.) The overriding method cannot be less visible than the method it overrides( i.e., a public method cannot be override to private). The overriding method may not throw any exceptions that may not be thrown by the overridden method 162. What is static initializer block? What is its use? A static initializer block is a block of code that declares with the static keyword. It normally contains the block of code that must execute at the time of class loading. The static initializer block will execute only once at the time of loading the class only. 163. What is difference between java.lang .Class and java.lang.ClassLoader? What is the hierarchy of ClassLoader ? Class 'java.lang.Class' represent classes and interfaces in a running Java application. JVM construct 'Class' object when class in loaded. Where as a ClassLoader is also a class which loads the class files into memory in order for the Java programs to execute properly. The hierarchy of ClassLoaders is: Bootstrap ClassLoaders Extensive ClassLoaders System Classpath ClassLoaders Application ClassLoaders 164. What is daemon thread? Theards which are running on the background are called deamon threads. daemon thread is a thread which doesn't give any chance to run other threads once it enters into the run state it doesn't give any chance to run other threads. Normally it will run forever, but when all other non-daemon threads are dead, daemon thread will be killed by JVM. 165. What is a green thread? Native threads can switch between threads preemptively. Green threads switch only when control is explicitly given up by a thread ( Thread.yield(), Object.wait(), etc.) or a thread performs a blocking operation (read(), etc.). On multi-CPU machines, native threads can run more than one thread simultaneously by assigning different threads to different CPUs. Green threads run on only one CPU. Native threads create the appearance that many Java processes are running: each thread takes up its own

entry in the process table. One clue that these are all threads of the same process is that the memory size is identical for all the threads - they are all using the same memory. The process table is not infinitely large, and processes can only create a limited number of threads before running out of system resources or hitting configured limits. 166. What is volatile variable? A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Volatile modifier requests the JVM to always access the shared copy of the variable so the its most current value is always read. 167. Why java does not support multiple inheritance?

Because the multiple inheritance causes the redundancy. Also we cannot solve diamond problem.

168. What is diamond problem? The diamond problem is an ambiguity that can occur when a class multiply inherits from two classes that both descend from a common super class. 169. How many JVM's we can run in a system? Any number of JVMs can run in a system. Whenever we issue the command 'java' a new JVM will start. 170. Why java is not 100% pure object oriented language?

Because java uses primitives.

171. Why ArrayList is faster than Vector?

A Because Vector is synchronized. Synchronization reduces the performance.

172. What is the security mechnaism used in java?

Java uses sand box security model.

173. What is sandbox? sandbox is a security mechanism for safely running programs. The sandbox typically provides a tightly-controlled set of resources for guest programs to run in, such as scratch space on disk and memory. 174. What is phantom memory?

Phantom memory is the memory that does not exist in reality.

175. What is reflection?

Reflection is the process of finding out the different features of a class dynamically.

176. What are the differences between JIT and HotSpot? The Hotspot VM is a collection of techniques, the most important of which is called adaptive optimization. The original JVMs interpreted byte codes one at a time. Second-generation JVMs added a JIT compiler, which compiles each method to native code upon first execution, then executes the native code. Thereafter, whenever the method is called, the native code is executed. The adaptive optimization technique used by Hotspot is a hybrid approach, one that combines byte code interpretation and run-time compilation to native code. Hotspot, unlike a regular JIT compiling VM, doesn't do "premature optimization". 177. What are the advantages and disadvantages of reference counting in garbage collection? 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.

178. How would you implement a thread pool? 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. 179. What is the difference between throw and throws clause? throw is used to throw an exception manually, where as throws is used in the case of checked exceptions, to tell the compiler that we haven't handled the exception, so that the exception will be handled by the calling function. 180. What is JAR file? JAR file (short for Java Archive) is a ZIP file used to distribute a set of Java classes. It is used to store compiled Java classes and associated metadata that can constitute a program 181. What is a classloader?

A class loader is an object that is responsible for loading classes.

182. What is the difference between Comparable and Comparator ? The Comparable is for natural ordering and Comparator is for custom ordering. But we can override the compareTo method of comparable interface to give a custom ordering. 183. What is the difference between List, Set and Map? Set is a collection that has no duplicate elements. A List is a collection that has an order associated with its elements. A map is a way of storing key/value pairs. The way of storing a Map is similar to twocolumn table.

184. What is meant by Open Source ? In general, open source refers to any program whose source code is made available for use or modification as users or other developers see fit. Open source software is usually developed as a public collaboration and made freely available. 185. How do you send data from an applet to Servlet ? What are the steps involved in it ? You can use the java.net.URLConnection and java.net.URL classes to open a standard HTTP connection to the web server. The server then passes this information to the servlet in the normal way. Basically, the applet pretends to be a web browser, and the servlet doesn't know the difference. As far as the servlet is concerned, the applet is just another HTTP client. 186. What is polymorphism?

It is the ability of an object to behave differently on different situations for the same message.

187. What is a class, member and local variable? Variables declared within a method are local variables. Variables declared within the class are member variables. Variables declared within the class with static modifier are class variables. 188. How do I convert a numeric IP address like 66.29.36.130 into a hostname like www.javacertificate.net String hostname = InetAddress.getByName("66.29.36.130").getHostName();

189. What is the difference between a constructor and a method? constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. We cannot invoke a constructor directly. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. 190. What are the different inner classes types?

There are mainly four types available. They are Member classes, Nested top-level classes, Local classes, Anonymous classes 192. What is Nested top-level classes? A class declared within a class with static modifier is called nested top level class. Any class outside the declaring class can access the nested top level class with the declaring class dot nested top level class. Top-level inner classes have access to static variables only . 193. What is Member classes? A class declared inside a class without static modifier is called member class. Member classes are just like any other member methods or member variables. 194. What is Local inner classes ? Local inner classes are class declared inside a block of code. They are visible only within the block of their declaration. 195. 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 197. What is the purpose of the Runtime class?

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

198. What is the difference between TCP/IP and UDP? TCP/IP is a two-way communication between the client and the server and it is a reliable and there is a confirmation regarding reaching the message to the destination. UDP is a one-way communication only between the client and the server and it is not a reliable and there is no confirmation regarding reaching the message to the destination.

199. Why is UTFDataFormatException thrown by DataOutputStream.writeUTF() when serializing a String? DataOutputStream.writeUTF() does not support writing out strings larger than 64K. The first two bytes of a UTF string in the stream are the length of the string. If a java.lang.String is larger than 64K, it needs to be stored in the stream by an alternative method rather than depending on the default method of storing a String in the stream, writeUTF. 200. Why is OutOfMemoryError thrown after writing a large number of objects into an ObjectOutputStream? The ObjectOutputStream maintains a table mapping objects written into the stream to a handle. The first time an object is written to a stream, its contents are written into the stream; subsequent writes of the object result in a handle to the object being written into the stream. This table maintains references to objects that might otherwise be unreachable by an application, thus, resulting in an unexpected situation of running out of memory. A call to the ObjectOutputStream.reset() method resets the object/handle table to its initial state, allowing all previously written objects to be eligible for garbage collection.

S-ar putea să vă placă și