Q1. What is the difference between encapsulation and abstraction?
Ans. Abstraction - hiding implementation.
Encapsulation - hiding data.
Abstraction is the process of hiding the details and exposing only the essential features of a particular concept or object.
Encapsulation is the ability of an object to be a container (or capsule) for related properties (ie. data variables) and methods (ie. functions).
Q2. Is it possible to make a class abstract without including any abstract methods?
Q2. Is it possible to make a class abstract without including any abstract methods?
Ans Yes. It’s possible to make a class abstract without including any abstract methods. This is useful when you’ve got a class in which it doesn’t make sense to have any abstract methods, and yet you want to prevent any instances of that class.
Ans. modifier “const” is not yet added in the language but marked as reserved.
Java uses the “final” modifier to declare constants. A final variable or constant declared as “final” has a value that is immutable and cannot be modified to refer to any other objects other than one it was initialized to refer to. So the “final” modifier applies only to the value of the variable itself, and not to the object referenced by the variable. This is where the “const” modifier can come in very useful if added to the Java language. A reference variable or a constant marked as “const” refers to an immutable object that cannot be modified. The reference variable itself can be modified, if it is not marked as “final”. The “const” modifier will be applicable only to non-primitive types. The primitive types should continue to use the modifier “final”.
Q4. Is null a keyword?
Java uses the “final” modifier to declare constants. A final variable or constant declared as “final” has a value that is immutable and cannot be modified to refer to any other objects other than one it was initialized to refer to. So the “final” modifier applies only to the value of the variable itself, and not to the object referenced by the variable. This is where the “const” modifier can come in very useful if added to the Java language. A reference variable or a constant marked as “const” refers to an immutable object that cannot be modified. The reference variable itself can be modified, if it is not marked as “final”. The “const” modifier will be applicable only to non-primitive types. The primitive types should continue to use the modifier “final”.
Q4. Is null a keyword?
Ans. The null value is not a keyword but a reserved literal/value like true, false, '\n' and hence, you can't use it as a variable name. So if you were to use null as variable it would be like writing that 5 = 0 where 5 is a variable and 0 is a value.
It's not a "keyword", technically, but it is a character string that is treated specially by the compiler if the compiler encounters it in a java source file. The lexical analyzer will decide that it is not an identifier.
Q5. Why does Java compiler forces you to initialize local variables before using them but not for member variables?
Q5. Why does Java compiler forces you to initialize local variables before using them but not for member variables?
Ans. This is because, uninitialized local variable is considered a programming error and if compiler provides default value in such a case, it would cover up programming error.
However, in case of member variables, they can be initialized by constructors as well as at the time of declaration itself. Hence, compiler provides a default value to them (0 for numbers, space for char and null for object references). Even in the case, where variable is initialized at the point of declaration itself, compiler first allocates a default value and then that is overridden.
Thus member variables are always initialized to default values first of all. The reason for such kind of behavior is that you may not even initialize all variables in constructors i.e initialize few and leave others as such.
Q6. How does java programs compile.
Q11. Can I have multiple main methods in the same class?
Q6. How does java programs compile.
Ans. Unlike C and C++ programs, Java programs are not compiled down to a platform-specific machine language. Instead, Java programs are compiled down to a platform independent language called bytecode. Bytecode is similar to machine language, but bytecode is not designed to run on any real, physical computer. Instead, bytecode is designed to be run by a program, called a Java Virtual Machine (JVM), which simulates a real machine.
Q7. Can I use different classpath while compiling and running the programs?
Q7. Can I use different classpath while compiling and running the programs?
Ans. Yes, classpath can vary from compile time to runtime.
Q8. What happens there are two classes with same names and you create a object of same without giving fully specified class name?
Ans. Lets' say you have written a class with name same name in package A and package B and in default package. Now, you have written a class Test which creates an object of class SameName without giving fully classified class name:
Now, if you compile the Test.java
Q8. What happens there are two classes with same names and you create a object of same without giving fully specified class name?
Ans. Lets' say you have written a class with name same name in package A and package B and in default package. Now, you have written a class Test which creates an object of class SameName without giving fully classified class name:
Now, if you compile the Test.java
a.) with package A and B in path (not including the default package), compiler gives a warning as it's not able to resolve namespace conflict.
b.) with package A/B and default package, compiler works and gives preference to default package.
c.) include only one package at compiler time, compiler works. Now, if you include all
packages while running, result will depend on package included at run time.
Q9. What is the first argument of the String array in main method?
Q9. What is the first argument of the String array in main method?
Ans. 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.
Q10. What if the static modifier is removed from the signature of main method?
Or
What if I do not provide the String array as the argument to the method?
Ans. Program compiles. But at runtime throws an error “NoSuchMethodError”.
Q11. Can I have multiple main methods in the same class?
Ans. 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) {}
Q12. What type of parameter passing does Java support?
Ans. 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.
Q13. Entry point of a java program is main() method. What happens in case of J2EE application, servlets?
Q13. Entry point of a java program is main() method. What happens in case of J2EE application, servlets?
Ans.
J2EE: main() method belonging to Java plugin or J2EE container.
applet: init() and start() methods.
servlet: doGet() and doPost() methods
Q14. Is operator overloading possible in java?
Ans. Java doesn’t allow it. Only overloaded operators in Java are + and “+=”.
J2EE: main() method belonging to Java plugin or J2EE container.
applet: init() and start() methods.
servlet: doGet() and doPost() methods
Q14. Is operator overloading possible in java?
Ans. Java doesn’t allow it. Only overloaded operators in Java are + and “+=”.
Q15. Difference btw access specifier and access modifier.
Ans.
Access specifier: Public, Private, Protected
Access Modifier: volatile, transient, final, static
Java supports both specifiers and modifiers that can dictate the access. An access specifier can be applied to any identifier like variables, methods and classes but modifiers cannot be applied to every identifier, there are limitations. For example, the modifiers applied to variables (ex: transient, volatile) cannot be used with classes and similarly with methods also.
Access Specifiers for Constructors - Constructors can have the same access specifiers used for variables and methods. Their meaning is the same. For example, when a constructor has “private” declared, then only the class itself can create an instance of it (kind of like self-instance). Other class in the same package/file cannot create an instance of that class nor any subclass of that class and nor any other class outside of this package/file.
The following table shows the access to members permitted by each specifier
Q16. Local variables cannot be declared static or final or transient .True/False?
Ans. Interface cannot be declared final as they are implicitly abstract.
Q24. Can private variables or methods be declared as final?
Ans. Package statement must appear as the first line in a source code file (excluding blank lines and comments).
Q30. Can a java file name be different from the class name?
Q31. Can a top level class be private or protected? OR Can we declare a class as private?
Similarly a top level class can't be static.
Q32. Can you define multiple classes in a single file?
Access specifier: Public, Private, Protected
Access Modifier: volatile, transient, final, static
Java supports both specifiers and modifiers that can dictate the access. An access specifier can be applied to any identifier like variables, methods and classes but modifiers cannot be applied to every identifier, there are limitations. For example, the modifiers applied to variables (ex: transient, volatile) cannot be used with classes and similarly with methods also.
Access Specifiers for Constructors - Constructors can have the same access specifiers used for variables and methods. Their meaning is the same. For example, when a constructor has “private” declared, then only the class itself can create an instance of it (kind of like self-instance). Other class in the same package/file cannot create an instance of that class nor any subclass of that class and nor any other class outside of this package/file.
The following table shows the access to members permitted by each specifier
Modifier
|
Class
|
Package
|
Subclass
|
World
|
public
|
Y
|
Y
|
Y
|
Y
|
protected
|
Y
|
Y
|
Y
|
N
|
no modifier
|
Y
|
Y
|
N
|
N
|
private
|
Y
|
N
|
N
|
N
|
Q16. Local variables cannot be declared static or final or transient .True/False?
Ans. True
Q17. What is the order of initialization in java.
Q18. What does the "static" keyword mean in front of a variable, method, class and curly braces {}?
Q23. Can an interface be final?Q17. What is the order of initialization in java.
Ans. As a class is loaded, (object is not created still), all the static initializers are run. i.e
1. First static member variables are initialized.
1. First static member variables are initialized.
2. Static blocks or methods are executed.
3. Then the member variables are initialized in the order of their appearance in class definition. By default, they are initialized to their default values like 0, null, false etc.
NOTE: All the above steps happen, even before object is created for class. They happen, when class is loaded for the first time.
4. Now, when an object of class is created, static initializers don't run again, but member variables are initialized every time with creation of an object and non-static block is also executed every time with creation of an object.
5. Appropriate constructor is called.
4. Now, when an object of class is created, static initializers don't run again, but member variables are initialized every time with creation of an object and non-static block is also executed every time with creation of an object.
5. Appropriate constructor is called.
Ans.
static variable - means a class level variable
static method – doesn't have "this". It is NOT allowed to access non static members of class.
static class - no such thing. It is possible only inside other classes.
static free floating block - is executed at the time the class is loaded. There can be multiple such blocks. This may be useful to load native libraries when using native methods.
Q19. Can we have static method in interface?
Ans. All methods in an interface are implicitly public, abstract and never static.
Q20. Can you import a class/package statically?
Ans. Yes. Using static import language feature, you don't have to write class name (ex: Math) in front of every (math) function.
Ex: Below code allows you to invoke the Math class methods by their simple names.
import static java.lang.Math.*;
cos(angle);
Q21. What specifiers may be used with an interface declaration.
Ans. An interface may be declared as public or abstract.
Q19. Can we have static method in interface?
Ans. All methods in an interface are implicitly public, abstract and never static.
Q20. Can you import a class/package statically?
Ans. Yes. Using static import language feature, you don't have to write class name (ex: Math) in front of every (math) function.
Ex: Below code allows you to invoke the Math class methods by their simple names.
import static java.lang.Math.*;
cos(angle);
Q21. What specifiers may be used with an interface declaration.
Ans. An interface may be declared as public or abstract.
Ans. Interface cannot be declared final as they are implicitly abstract.
Q24. Can private variables or methods be declared as final?
Ans. Yes, but that doesn't add to any advantage. When a method is declared with private, it means that it can't be overridden. Same is the case with final keyword. So you don't get any advantage.
If you define a method (declared private in base class) with same name and signature in derived class, there is no compiler error. However, it doesn't mean method is overridden. Just a new method is defined.
class WithFinals {
// Identical to "private" alone:
private final void f() { print("WithFinals.f()"); }
// Also automatically "final":
private void g() { print("WithFinals.g()"); }
}
class OverridingPrivate extends WithFinals {
private final void f() {
print("OverridingPrivate.f()");
}
private void g() {
print("OverridingPrivate.g()");
}
}
class OverridingPrivate2 extends OverridingPrivate {
public final void f() {
print("OverridingPrivate2.f()");
}
public void g() {
print("OverridingPrivate2.g()");
}
}
public class FinalOverridingIllusion {
public static void main(String[] args) {
OverridingPrivate2 op2 = new OverridingPrivate2();
op2.f();
op2.g();
// You can upcast:
OverridingPrivate op = op2;
// But you can’t call the methods:
//! op.f();
//! op.g();
// Same here:
WithFinals wf = op2;
//! wf.f();
//! wf.g();
}
}
Output:
OverridingPrivate2.f()
OverridingPrivate2.g()
“Overriding” can only occur if something is part of the base-class interface. That is, you must be able to upcast an object to its base type and call the same method. If a method is private, it isn’t part of the base-class interface. It is just some code that’s hidden away inside the class and it just happens to have that name, but if you create a public, protected, or package-access method with the same name in the derived class, there’s no connection to the method that might happen to have that name in the base class. You haven’t overridden the method; you’ve just created a new method. Since a private method is unreachable and effectively invisible, it doesn’t factor into anything except for the code organization of the class for which it was defined.
However, if a public/protected method is declared as final, it can't be overridden in derived class.
Q25. Can method arguments be made as final?
Q28. Doesn't implicit Object inheritance create multiple inheritance?
Q29. What restrictions are placed on the location of a package statement within a source code file?If you define a method (declared private in base class) with same name and signature in derived class, there is no compiler error. However, it doesn't mean method is overridden. Just a new method is defined.
class WithFinals {
// Identical to "private" alone:
private final void f() { print("WithFinals.f()"); }
// Also automatically "final":
private void g() { print("WithFinals.g()"); }
}
class OverridingPrivate extends WithFinals {
private final void f() {
print("OverridingPrivate.f()");
}
private void g() {
print("OverridingPrivate.g()");
}
}
class OverridingPrivate2 extends OverridingPrivate {
public final void f() {
print("OverridingPrivate2.f()");
}
public void g() {
print("OverridingPrivate2.g()");
}
}
public class FinalOverridingIllusion {
public static void main(String[] args) {
OverridingPrivate2 op2 = new OverridingPrivate2();
op2.f();
op2.g();
// You can upcast:
OverridingPrivate op = op2;
// But you can’t call the methods:
//! op.f();
//! op.g();
// Same here:
WithFinals wf = op2;
//! wf.f();
//! wf.g();
}
}
Output:
OverridingPrivate2.f()
OverridingPrivate2.g()
“Overriding” can only occur if something is part of the base-class interface. That is, you must be able to upcast an object to its base type and call the same method. If a method is private, it isn’t part of the base-class interface. It is just some code that’s hidden away inside the class and it just happens to have that name, but if you create a public, protected, or package-access method with the same name in the derived class, there’s no connection to the method that might happen to have that name in the base class. You haven’t overridden the method; you’ve just created a new method. Since a private method is unreachable and effectively invisible, it doesn’t factor into anything except for the code organization of the class for which it was defined.
However, if a public/protected method is declared as final, it can't be overridden in derived class.
Q25. Can method arguments be made as final?
Ans. Yes. Java allows you to make arguments final by declaring them as such in the argument list. This means that inside the method you cannot change what the argument reference points to:
//: reusing/FinalArguments.java
// Using "final" with method arguments.
// Using "final" with method arguments.
class Gizmo {
public void spin() {}
}
}
public class FinalArguments {
void withFinals(final Gizmo g) {
//! g = new Gizmo(); // Illegal -- g is final
}
}
Q26. Is object class concrete or abstract?
Q26. Is object class concrete or abstract?
Ans. Concrete
Q27. Can we explicitly inherit from the Object class?
Ans. If you explicitly extend the Object class and it would not be an error to do so, unless you are not extending any other class as well since multiple inheritance is not allowed.Q28. Doesn't implicit Object inheritance create multiple inheritance?
Ans: No. Every Java class is ultimately descended from the Object superclass, whether there is an “extends” Object statement or not. If you extend an API class, the Object inheritance is passed down through that immediate superclass (and not the class extends the object class). Implicit inheritance from the Object class descends through a single line of parent classes to ensure all user defined classes have the standard toString(), equals() and hashCode() methods.
Ans. Package statement must appear as the first line in a source code file (excluding blank lines and comments).
Q30. Can a java file name be different from the class name?
Ans. Yes, provided that you don't specify any access specifier for the class.class A{
void foo () {
System.out.println("I am in A class");
void foo () {
System.out.println("I am in A class");
}
}
Above code snippet can be saved as B.java.
However, if you mention any access specifier, it will give a compilation error. Ex:
public class A
{
void foo ()
{
System.out.println("I am in A class");
Above code snippet can be saved as B.java.
However, if you mention any access specifier, it will give a compilation error. Ex:
public class A
{
void foo ()
{
System.out.println("I am in A class");
}
}
If you try to save above as "B.java", it gives an error as below:
If you try to save above as "B.java", it gives an error as below:
"B.java: class A is public, should be declared in a file named A.java"
Ans. No, a top level class can’t be private or protected. It can have either "public" or no modifier. If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can’t be private. Only inner classes can be made private. This is because, if you are making top class as private, you can't use it in any way and hence, there is no use.
Q32. Can you define multiple classes in a single file?
Ans. In Java, you can define multiple top level classes in a single file, providing that at most one of these is public. Also, you can't mention any access specifier for any of the other class.
public class PublicClass {
public class PublicClass {
PrivateImpl impl = new PrivateImpl();
}
class PrivateImpl {
int implementationData;
int implementationData;
}
Above code snippet can be saved as PublicClass.java. However, if you say "protected/private/public class PrivateImpl" instead of "class PrivateImpl", this will give a compilation error.
Q33. What method would be called in below case:
Above code snippet can be saved as PublicClass.java. However, if you say "protected/private/public class PrivateImpl" instead of "class PrivateImpl", this will give a compilation error.
Q33. What method would be called in below case:
public class NullTest {
public static void method(Object obj){
System.out.println("method with param type - Object");
}
public static void method(String obj){
System.out.println("method with param type - String");
}
public static void main(String [] args){
method(null);
}
}
Ans. Method with String argument will be called. As per Java specifications, if more than one member method is both accessible and applicable to a method invocation, most specific method is chosen i.e any sub-class would get a preference over the super class in such a situation.
However, in following case it gives a compiler error:
public class NullTest {
public static void method(Object obj) {
System.out.println("method with param type - Object");
}
public static void method(String str) {
System.out.println("method with param type - String");
}
public static void method(StringBuffer strBuf) {
System.out.println("method with param type - StringBuffer");
}
public static void main(String [] args) {
method(null); //... compile-time error!
}
}
Here, compiler is not able to pick 'the most specific' here because both String and StringBuffer are are sub-classes of the Object class, but without being in the same inheritance hierarchy. For finding 'the most specific' method, the compiler needs to find a method having the parameter type, which is a sub-class of the parameter types of all other overloaded methods.
This holds true for overloaded methods having more than one parameters as well. The compiler would pick 'the most specific' by looking which method is having at least one of its parameter types as a clear sub-class of the corresponding parameter type and other parameter types being either the same or clear sub-classes, in all other overloaded methods. If it can find one, that method will be used; otherwise it will throw a compile-time error.
Q34. Talk about method overriding.
Q37. What is the difference b/w overriding and hiding?
public static void method(Object obj){
System.out.println("method with param type - Object");
}
public static void method(String obj){
System.out.println("method with param type - String");
}
public static void main(String [] args){
method(null);
}
}
Ans. Method with String argument will be called. As per Java specifications, if more than one member method is both accessible and applicable to a method invocation, most specific method is chosen i.e any sub-class would get a preference over the super class in such a situation.
However, in following case it gives a compiler error:
public class NullTest {
public static void method(Object obj) {
System.out.println("method with param type - Object");
}
public static void method(String str) {
System.out.println("method with param type - String");
}
public static void method(StringBuffer strBuf) {
System.out.println("method with param type - StringBuffer");
}
public static void main(String [] args) {
method(null); //... compile-time error!
}
}
Here, compiler is not able to pick 'the most specific' here because both String and StringBuffer are are sub-classes of the Object class, but without being in the same inheritance hierarchy. For finding 'the most specific' method, the compiler needs to find a method having the parameter type, which is a sub-class of the parameter types of all other overloaded methods.
This holds true for overloaded methods having more than one parameters as well. The compiler would pick 'the most specific' by looking which method is having at least one of its parameter types as a clear sub-class of the corresponding parameter type and other parameter types being either the same or clear sub-classes, in all other overloaded methods. If it can find one, that method will be used; otherwise it will throw a compile-time error.
Q34. Talk about method overriding.
Ans. The new method definition while overriding must have the same method signature (i.e., method name and parameters) and return type. Only parameter types and return type are chosen as criteria for matching method signature. So if a subclass has its method parameters as final it doesn’t really matter for method overriding scenarios as it still holds true. The new method definition cannot narrow the accessibility of the method, but it can widen it.
The new method definition can only specify all or none, or a subset of the exception classes (including their subclasses) specified in the throws clause of the overridden method in the super class.
Q35. Can we override variables?
Ans. Yes, but variables when overridden shadows the super class variable.
Q36. How can I prevent a class/method from being extended/overridden?
Ans:
To prevent a class from being extended -> Making it final
To prevent a method from being overridden -> Making it final, private or static
The new method definition can only specify all or none, or a subset of the exception classes (including their subclasses) specified in the throws clause of the overridden method in the super class.
Q35. Can we override variables?
Ans. Yes, but variables when overridden shadows the super class variable.
Q36. How can I prevent a class/method from being extended/overridden?
Ans:
To prevent a class from being extended -> Making it final
To prevent a method from being overridden -> Making it final, private or static
Overriding: Re-defining an instance (non-static) method.
Hiding: Re-defining a class (static) method.
The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the super-class or the subclass.
If a super-class object contains reference to a sub-class object, then on invoking hidden method, method from super class will get invoked. And on invoking overridden method, method from sub-class will get invoked.
The following table summarizes what happens when you define a method with the same signature as a method in a superclass.
SubclassMethod/SuperClass Method
(Same Signature)
|
Superclass Instance
Method
|
Superclass Static Method
|
Subclass Instance Method
|
Overrides
|
Generates a compile-time error
|
Subclass Static Method
|
Generates a compile-time error
|
Hides
|
Q38. How can I find the inherited attributes of a class?
Ans: It is possible to deduce the inherited fields and methods of a Java class using reflection through a recursive process that uses the Class method getSuperclass(). The Class method getFields() returns an array of Field objects for public fields only. The getDeclaredFields() returns an array of all declared fields in the current class, including private fields, but not the inherited fields. The getMethods() and getDeclaredMethods() methods return equivalent arrays of Method objects.
To obtain a list of all inherited fields or methods, a program would need to get the superclass of the object in question, store the return value for its getDeclaredFields() method then process each of its superclasses in turn.
Q39. What is virtual method invocation?
To obtain a list of all inherited fields or methods, a program would need to get the superclass of the object in question, store the return value for its getDeclaredFields() method then process each of its superclasses in turn.
Q39. What is virtual method invocation?
Ans. The Java virtual machine (JVM) calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.
Q40. What is co-variant return type?
Q40. What is co-variant return type?
Ans. When a super-class method is over-ridden in subclass, it bears the same signature as super class method, i.e. number of parameters, type of parameters and return-type are same. However, if sub-class method returns a sub-type of the type returned by over-ridden method, it is called co-variant return type.
Q41. What are static factory methods?
Q41. What are static factory methods?
Ans. Some of the above mentioned features like searching, sorting, shuffling, immutability etc are achieved with java.util.Collections class and java.util.Arrays utility classes. The great majority of these implementations are provided via static factory methods in a single, non-instantiable (i.e. private constructor) class. Speaking of static factory methods, they are an alternative to creating objects through constructors. Unlike constructors, static factory methods are not required to create a new object (i.e. a duplicate object) each time they are invoked (e.g. immutable instances can be cached) and also they have a more meaningful names like valueOf, instanceOf, asList etc.
For example: Instead of:
String[] myArray = {"Java", "J2EE", "XML", "JNDI"};
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
You can use:
String[] myArray = {"Java", "J2EE", "XML", "JNDI"};
System.out.println(Arrays.asList(myArray)); //factory method Arrays.asList(…)
Another instance, following static factory method (an alternative to a constructor) example converts a boolean primitive value to a Boolean wrapper object.
String[] myArray = {"Java", "J2EE", "XML", "JNDI"};
System.out.println(Arrays.asList(myArray)); //factory method Arrays.asList(…)
Another instance, following static factory method (an alternative to a constructor) example converts a boolean primitive value to a Boolean wrapper object.
public static Boolean valueOf(boolean b) {
return (b ? Boolean.TRUE : Boolean.FALSE)
}
Q42. Use of an initializer block and alternative to it.
Ans. When constructors have a large part of code in common and you want to prevent code duplication, that code can be kept in initializer blocks. Alternatively, one can private/final instance method in place of block, which can have other advantages as well. Initializer block is a problem, in case subclass need to have the code from block but don't need the code from base class constructor. Normally, what we do is call the base class constructor, which in case will execute the code of initializer block in base class as well as code in constructor. However, if block is replaced by an instance method, subclass can call that method explicitly without calling base class constructor.
Another advantage of instance method is that, it can be called from any other method to re-set the instance variables and all.
Q43. What is diamond problem?
}
Q42. Use of an initializer block and alternative to it.
Ans. When constructors have a large part of code in common and you want to prevent code duplication, that code can be kept in initializer blocks. Alternatively, one can private/final instance method in place of block, which can have other advantages as well. Initializer block is a problem, in case subclass need to have the code from block but don't need the code from base class constructor. Normally, what we do is call the base class constructor, which in case will execute the code of initializer block in base class as well as code in constructor. However, if block is replaced by an instance method, subclass can call that method explicitly without calling base class constructor.
Another advantage of instance method is that, it can be called from any other method to re-set the instance variables and all.
Q43. What is diamond problem?
Ans. This is traditional multiple inheritance
Q44. What is the difference between aggregation and composition?
Q44. What is the difference between aggregation and composition?
Ans.
Aggregation is an association in which one class belongs to a collection. This is a part of a whole relationship where a part can exist without a whole. It has a weaker relationship.
Ex: A line item is a whole and product is a part. If a line item is deleted then corresponding product need not be deleted.
Composition is an association in which one class belongs to a collection. This is a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted. It has a stronger relationship.
Ex: An order is a whole and line items are parts. If an order is deleted then all corresponding line items for that order should be deleted.
Aggregation vs Composition
● Aggregation represents a "has-a" relationship whereas Composition represents a "contains-a" OR "whole-part" relationship.
● In case of Aggregation, both the entities will continue to have their independent existence whereas in case of Composition the lifetime of the entity representing 'part' of the "whole-part" is governed by the entity representing 'whole'.
● Aggregation represents a loose form of relationship as compared to that represented by Composition which depicts a stronger relationship.
● In UML notation, an Aggregation relationship is depicted by an unfilled diamond and a solid line whereas a Composition relationship is depicted by a filled diamond and a solid line.
● A 'part' of a Composition relationship can have only one 'whole' at a time i.e., a multiplicity of 1 whereas an Aggregation relationship can have any multiplicity 0..* at the aggregate end.
Q45. Composition and inheritance.
Describe adding method to superclass that has same name but different semantics as subclass. Also the problem of just inheriting an added method signature that you don't want in the subclass. Class extension is like strapping on a backpack in which your instances carry around not only their own instance variables and everything they refer to in a graph of objects, but also those of all their superclasses. If you don't own the superclass, owner can change superclss by adding lots of heavy instance data that gets added to your backpack and you don't have a choice but carry it around everywhere. The owner can also add a method to the superclass interface that you don't like in your subclass, but suddently its a part of your interface whether you like it there or not (or, what's the ultimate problem has, the same signature but incompatible semantics as an existing method in your subclass). In a composition relationship you could change the back-end object, delay initilization until needed, share same backend amont multiple front-ends, etc...
Q46. Explain black-box reuse and white-box reuse? Which one would you prefer?
Disadvantage of aggregation is that it increases the number of objects and relationships.
Q48. Describe the wrapper classes in Java.
Aggregation is an association in which one class belongs to a collection. This is a part of a whole relationship where a part can exist without a whole. It has a weaker relationship.
Ex: A line item is a whole and product is a part. If a line item is deleted then corresponding product need not be deleted.
Composition is an association in which one class belongs to a collection. This is a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted. It has a stronger relationship.
Ex: An order is a whole and line items are parts. If an order is deleted then all corresponding line items for that order should be deleted.
Aggregation vs Composition
● Aggregation represents a "has-a" relationship whereas Composition represents a "contains-a" OR "whole-part" relationship.
● In case of Aggregation, both the entities will continue to have their independent existence whereas in case of Composition the lifetime of the entity representing 'part' of the "whole-part" is governed by the entity representing 'whole'.
● Aggregation represents a loose form of relationship as compared to that represented by Composition which depicts a stronger relationship.
● In UML notation, an Aggregation relationship is depicted by an unfilled diamond and a solid line whereas a Composition relationship is depicted by a filled diamond and a solid line.
● A 'part' of a Composition relationship can have only one 'whole' at a time i.e., a multiplicity of 1 whereas an Aggregation relationship can have any multiplicity 0..* at the aggregate end.
Q45. Composition and inheritance.
Ans.
Agenda
● Use concrete classes to say "What objects are."
● Use composition to enlist the help of other objects.
● Use class extension to model permanent IS-A relationships.
● Understand the difference between inheritance and composition.
Using Composition
● Guideline: Use composition to enlist the help of other objects.
● A "front-end" object enlists the help of "back-end" objects
● Front-end object holds references to back-end objects in instance variables
● Front-end object delegates to back-end objects via explicit method invocations
Using Inheritance
● Guideline: Use class extension to model permanent IS-A relationships.
● Subclasses inherit the interface and, by default, the implementation of their superclass.
● A subclass should have some kind of specialized behavior (it should provide the same service as the superclass, only differently)
● A subclass may also offer new services not offered by the superclass
● IS-A means "Is a specialized kind of," so watch out for:
○ Bootsie IS-A Dog
○ Car IS-AN Automobile
How do You Decide?
● To accomodate a likely vector of change by making it possible to plug in new subclasses in the future
● To define a tight, close-knit family, such as the StampMachine.State family
● To communicate important concepts in the design, where each subclass is about one concept
● To form a vocabulary for programmers: If there's an account in the problem domain, there should likely be an Account in the solution.
● Be unsurprising: Square IS-A Rectangle?
Why IS-A?
● Inheritance gives you code reuse. (OO Claim: promotes code reuse)
● Inheritance gives you polymorphism:
● Account a = new OverdraftAccount(50000);
● Don't use inheritance to get at code reuse or polymorphism without IS-A
● Why? Because that's what inheritance means
Inheritance vs. Composition
Inheritance Yields (Slightly) Better Performance:
● Composition's method forwarding/delegation will often be slower than inheritance's dynamic binding
● Composition results in more objects getting instantiated, which can incur a performance cost at allocation, <init>(), and GC time
Composition Yields Better Flexibility:
● Interfaces of classes involved in a composition relationship need not be compatible, so it's easier to change the interfaces
● Composition allows you to delay creation of back-end objects until (and unless) you need them
● Composition allows you to change back-end objects throughout the lifetime of the front-end object
● Composition allows front-end objects to share the same back-end objects.
But:
● Composition's method forwarding/delegation results in more code that has to be written, debugged, and maintained.
● Easier to add new subclasses than new front-end classes, unless you use composition with interfaces
Inheritance
|
Composition
|
Attaching responsibilities to classes at compile time using subclassing.
|
Attaching responsibilities to objects at runtime using a decorator design pattern.
|
Inheritance (aka subclassing) attaches responsibilities to classes at compile time. When you extend a class, each individual changes you make to child class will affect all instances of the child classes. Defining many classes using inheritance to have all possible combinations is problematic and inflexible.
|
By attaching responsibilities to objects at runtime, you can apply changes to each individual object you want to change.
File file = new File(“c:/temp”);
FileInputStream fis = new
FileInputStream(file);
BufferedInputStream bis = new
BufferedInputStream(fis);
|
Q46. Explain black-box reuse and white-box reuse? Which one would you prefer?
Ans.
Black-Box reuse: This is known as composition. It is defined dynamically or at runtime via object references. Since only interfaces are used, it has the advantage of maintaining the integrity (i.e. encapsulation).
Disadvantage of aggregation is that it increases the number of objects and relationships.
White-Box reuse: This is known as Inheritance. Inheritance is defined statically or at compile time. Inheritance allows an easy way to modify implementation for re-usability.
A disadvantage of inheritance is that it breaks encapsulation, which implies implementation dependency. This means when you want to carry out the redesign where the super class (i.e. parent class) has to be modified or replaced, which is more likely to affect the subclasses as well. In general it will affect the whole inheritance hierarchy.
A disadvantage of inheritance is that it breaks encapsulation, which implies implementation dependency. This means when you want to carry out the redesign where the super class (i.e. parent class) has to be modified or replaced, which is more likely to affect the subclasses as well. In general it will affect the whole inheritance hierarchy.
Verdict: So the tendency is to favour composition over inheritance
Q47. Name primitive Java types.
Ans. The 8 primitive types are byte, char, short, int, long, float, double, and boolean.Q47. Name primitive Java types.
Q48. Describe the wrapper classes in Java.
Ans: Wrapper class is a wrapper around a primitive data type which allows it to be accessed as object. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.Following table lists the primitive types and the corresponding wrapper classes:
Primitive Wrapper
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
Q49. Can a Byte object be cast to a double value?
Ans. No, an object cannot be cast to a primitive value.
Q50. What happens if you assign an int to byte?
Q53. What all classes are final in Java?
Primitive Wrapper
boolean java.lang.Boolean
byte java.lang.Byte
char java.lang.Character
double java.lang.Double
float java.lang.Float
int java.lang.Integer
long java.lang.Long
short java.lang.Short
Q49. Can a Byte object be cast to a double value?
Ans. No, an object cannot be cast to a primitive value.
Q50. What happens if you assign an int to byte?
Ans. Byte range is -128 to 127 (i.e signed) or 255 (unsigned).
First of all, it considers only 8 bits and ignores after that.
Ex: 256 is 1 0000 0000 -> here 1 (9th bit) is ignored and only remaining bits are considered and thus answer is 0.
400 is 1 1001 0000 -> Ignore 9th bit, thus remaining is 1001 000, now since 8th bit is 1, this means number is negative and thus take 2's complement of same, which is - (0110 1111 + 1) = -(0111 0000) = -112
Similarly 128 is 1000 0000 -> 2's complement of same is
Ex: 256 is 1 0000 0000 -> here 1 (9th bit) is ignored and only remaining bits are considered and thus answer is 0.
400 is 1 1001 0000 -> Ignore 9th bit, thus remaining is 1001 000, now since 8th bit is 1, this means number is negative and thus take 2's complement of same, which is - (0110 1111 + 1) = -(0111 0000) = -112
Similarly 128 is 1000 0000 -> 2's complement of same is
- ( 0111 1111 + 1) = -(1000 0000) = -128
Q51. Is there any conversion that works in each and every case?
Ans. ‘b’ conversion(conversion to byte) works for each variable above. Although it’s valid for any argument type, it might not behave as you’d expect
Ex: For boolean primitives or Boolean objects, the result will be true or false, accordingly.
However, for any other argument, as long as the argument type is not null the result is always true. Even numeric value of zero, which is synonymous with false mostly, conversion will produce true.
Q52. Is it possible to for equals and compare method to show inconsistent behaviour. Ex: equals say true but compare doesn't say so?
Q52. Is it possible to for equals and compare method to show inconsistent behaviour. Ex: equals say true but compare doesn't say so?
Ans. Generally, if a.equals(b) is true, then a.compareTo(b) == 0 should also be true. Curiously, BigDecimal violates this. In BigDecimal, equals() checks if the BigDecimal objects are exactly the same in every aspect. compareTo() "only" compares their numeric value.
Ex:
BigDecimal x = new BigDecimal("1");
Ex:
BigDecimal x = new BigDecimal("1");
BigDecimal y = new BigDecimal("1.00");
System.out.println(x.equals(y)); //returns false
System.out.println(x.compareTo(y) == 0 ? "true": "false"); // returns true.
Ans. Some of default final classes in java
1) String
2) Boolean
3) Double
4) Integer (Wrapper classes)
5) Math
6) MathContext
7) Void
8) UUID
9) URL, URI and UID
and so on
Q54. What is the purpose of Void class?
Q54. What is the purpose of Void class?
Ans. Void class is a un-instantiable placeholder class to hold a reference to the Class object representing the primitive Java type void. It also contains Void.TYPE, useful for testing return type with reflection:
Q55. What is default implementation of toString() method.
if (getClass().getMethod("foo").getReturnType() == Void.TYPE)
Ans.
object: className@hashcode.
list, array, set: comma separated list of elements in square brackets
map, hashmap: comma separated list of elements i.e key=value in curly brackets
Q56. What is the issue with the following code?
Ans.
public String toString() {
return " InfiniteRecursion address: " + this + "\n";
}
The compiler sees a String followed by a ’+’ and something that’s not a String, so it tries to convert this to a String. It does this conversion by calling toString(), which produces a recursive call. If you really do want to print the address of the object, the solution is to call the Object toString() method. So instead of saying this, you’d say super.toString().
Q57. What is the difference b/w JVM, JRE and JDK?
object: className@hashcode.
list, array, set: comma separated list of elements in square brackets
map, hashmap: comma separated list of elements i.e key=value in curly brackets
Q56. What is the issue with the following code?
Ans.
public String toString() {
return " InfiniteRecursion address: " + this + "\n";
}
The compiler sees a String followed by a ’+’ and something that’s not a String, so it tries to convert this to a String. It does this conversion by calling toString(), which produces a recursive call. If you really do want to print the address of the object, the solution is to call the Object toString() method. So instead of saying this, you’d say super.toString().
Q57. What is the difference b/w JVM, JRE and JDK?
Ans.
JDK or Java Development Kit: Set of a Java compiler, a Java interpreter, developer tools, Java API libraries, documentation etc.
JRE or the Java Runtime Environment: Minimum set that includes a Java interpreter, Java API libraries, Java browser plug-in, which makes up the minimum environment to execute Java-based applications. If you want to run any java program, you need to have JRE installed in the system.
JVM or Java Virtual Machine: Core of the Java platform. Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE.
JRE = JVM + Packages
JDK = JRE + Developer tools
Q58. Is JVM a compiler or an interpreter?
Ex: Surreptitious behavior and interface modification of some of Java’s core classes in their own implementation of Java. Programmers who do not recognize these undocumented changes can build their applications expecting them to run anywhere that Java can be found, only to discover that their code works only on Microsoft’s own Virtual Machine, which is only available on Microsoft’s own operating systems.
Q60. java.lang.UnsupportedClassVersionError: When is it thrown by a JVM & how to resolve it?
Notes:
12. public static final int B; // note that it is not public static final int B = null;
// note that since B is final, it can be initialized only once.
13. PIE which stands for Polymorphism, Inheritance and Encapsulation are the 3 pillars of OOP.
14. In interfaces all the inner classes are implicitly public and static like Entry in Map.
Q58. Is JVM a compiler or an interpreter?
Ans. Interpreter
Q59. Java says "write once, run anywhere". What are some ways this isn't true?
Q59. Java says "write once, run anywhere". What are some ways this isn't true?
Ans. As long as all implementations of java are certified by sun as 100% pure java this promise of "Write once, Run everywhere" will hold true. But as soon as various java core implementations start digressing from each other, this won’t be true anymore.
Q60. java.lang.UnsupportedClassVersionError: When is it thrown by a JVM & how to resolve it?
Ans. UnsupportedClassVersionError is a descendant of Error class in Java. This error is thrown in the cases when the JVM (Java Virtual Machine) attempts to read a class file and finds that the major and minor version numbers in the particular class file are not supported. This happens in the cases when a higher version of Java Compiler is used to generate the class file than the JVM version which is used to execute that class file. However, it is not true vice-versa which means you can comfortably use a higher version of JVM to run a class file compiled using an earlier version of Java Compiler.
The minor and major version numbers are represented by the major_version and minor_version items respectively in a Java Class File structure. A combination of these two unsigned integers (both of length 2 bytes each) determines the particular version of the class file format. If a class file has major version number M and minor version number m, we denote the version of its class file format as M.m.
As per Java VM Spec, “A Java virtual machine implementation can support a class file format of version v if and only if v lies in some contiguous range Mi.0 v Mj.m. Only Sun can specify what range of versions a Java virtual machine implementation conforming to a certain release level of the Java platform may support.
Ex: Implementations of version 1.2 of the Java 2 platform can support class file formats of versions in the range 45.0 through 46.0 inclusive.
Q61. Java default heap size and how to change this.
The minor and major version numbers are represented by the major_version and minor_version items respectively in a Java Class File structure. A combination of these two unsigned integers (both of length 2 bytes each) determines the particular version of the class file format. If a class file has major version number M and minor version number m, we denote the version of its class file format as M.m.
As per Java VM Spec, “A Java virtual machine implementation can support a class file format of version v if and only if v lies in some contiguous range Mi.0 v Mj.m. Only Sun can specify what range of versions a Java virtual machine implementation conforming to a certain release level of the Java platform may support.
Ex: Implementations of version 1.2 of the Java 2 platform can support class file formats of versions in the range 45.0 through 46.0 inclusive.
Q61. Java default heap size and how to change this.
Ans. Java's default heap size is dependent on OS. If you need more than this, you should use the -Xms and -Xmx command line arguments when launching your program:
$> java -Xms –Xmx
Sometimes it will show error if you are using above option. In that case use -mx256m. Stack space can be increased with the –Xss option.
$> java -Xms –Xmx
Sometimes it will show error if you are using above option. In that case use -mx256m. Stack space can be increased with the –Xss option.
Notes:
1. Default access modifier of classes and interface is package-private.
2. Default access modifier of methods in classes is package-private and in interface is public.
3. Each variable in interface must be assigned a constant value, since each variable is public, static and final implicitly.
4. Default access modifier of constants in classes and in interface is public, static and final.
5. Unlike interfaces, abstract classes can contain fields that are not static and final.
6. You can’t assign a primitive type to an object, but you can assign any other object to an object.
7. In generics, type <T> can’t be of a primitive type.
8. By convention, ranges are inclusive of beginning index and exclusive of end index
9. It is illegal to include the size of an array in the array declaration. You can only specify the size when you create a declared array.
10. IdentityHashMap has different performance because it uses == rather than equals() for comparisons.
11. min() and max() work with Collection objects and not with Lists.2. Default access modifier of methods in classes is package-private and in interface is public.
3. Each variable in interface must be assigned a constant value, since each variable is public, static and final implicitly.
4. Default access modifier of constants in classes and in interface is public, static and final.
5. Unlike interfaces, abstract classes can contain fields that are not static and final.
6. You can’t assign a primitive type to an object, but you can assign any other object to an object.
7. In generics, type <T> can’t be of a primitive type.
8. By convention, ranges are inclusive of beginning index and exclusive of end index
9. It is illegal to include the size of an array in the array declaration. You can only specify the size when you create a declared array.
10. IdentityHashMap has different performance because it uses == rather than equals() for comparisons.
12. public static final int B; // note that it is not public static final int B = null;
// note that since B is final, it can be initialized only once.
13. PIE which stands for Polymorphism, Inheritance and Encapsulation are the 3 pillars of OOP.
14. In interfaces all the inner classes are implicitly public and static like Entry in Map.
No comments:
Post a Comment