Basic Flashcards
Name the 4 OOP principles.
Abstraction
Polymorphism
Inheritance
Encapsulation
What is Polymorphism?
Polymorphism is the
- provision of single interface which can be implemented by different classes to provide their customized implementation
or - use of single symbol to represent multiple different types
Polymorphism has two types: static (Compile time) and dynamic (runtime).
Explain the types of Polymorphism.
- Compile-time/static
The implementation to call is determined at compile-time. This is divided into two types:
(i) Function Overloading: multiple functions, same name but different number/types of parameters
(ii) Operator overloading: Using â+â to add two numbers and also to concatenate two strings
2. Run-time/dynamic The implementation to call is determined at run-time. There is only one type: (i) Function overriding: parent and child class have methods is exact same signature.
Can we overload static/final/private methods in same class?
Yes we can.
We cannot âoverrideâ static/final/private methods anywhere.
Can we override static/final/private methods of parent class?
No.
It is possible to override parent classâs static methods as in we can have methods with exact same signatures in both parent and child class, but Java doesnât call it overriding, as static methods are tied to the class as a whole and inheritance deals with providing customized behaviors for objects.
Final declaration by default does not allow overriding anywhere.
Private methods of parent class will not be visible outside and cannot be overridden.
Explain output.
class Animal { protected void getData() { System.out.println("Inside Animal"); } } class Dog extends Animal { protected void getData() { System.out.println("Inside Dog"); } }
public class Test { public static void main(String[] args) { Animal animal = new Dog(); animal.getData(); } }
Can we write this:
Dog dog = new Animal ( );
Reference variable of parent class Animal is pointing to object of child class Dog, hence the method implementation by class Dog will be called.
===========================================
We cannot write Dog dog = new Animal ( ); as it will give compiler error âType mismatch: cannot convert from Animal to Dogâ
With ânew Dog( )â we are assigning the Dog object type to Animal type, which is valid as Dog IS-A Animal.
With ânew Animal( )â we are assigning Animal object type to Dog type, which is not valid for inheritance (IS-A relationship).
Explain output.
class Employee { void foo ( ) { System.out.println("Employee"); } }
class Manager extends Employee { void foo ( ) { System.out.println("Manager"); }
public static void main(String [ ] args) { Manager john = new Employee( ); john.foo ( ); } }
Compilation error (type mismatch) --------------------------- The object john is of type Employee (superclass) but referes to Manager (subclass), which violates the IS-A relationship.
Explain output.
class Animal { protected void run ( ) { System.out.println("Animal runs"); } } class Dog extends Animal { protected void eat ( ) { System.out.println("Dog eats"); }
protected void leap() { System.out.println("Dog leaps"); } }
public class Test { public static void main(String [ ] args) { Animal animal = new Dog(); animal.leap ( ); } }
Although the reference variable of parent class is pointing to object of child class, the method leap ( ) does not exist for parent class.
Explain output.
interface Animal { void run ( ); void leap ( ); }
abstract class Dog implements Animal { void eat ( ) { System.out.println (" Dog eats "); } }
public class Corgi extends Dog { public void run ( ) { System.out.println("Corgi runs"); } public void leap ( ) { System.out.println("Corgi leaps"); }
public static void main ( String [ ] args) { Dog dog = new Corgi ( ); dog.leap ( ); } }
Dog implements Animal interface, hence all the methods in Animal replicate for class Dog.
As the reference variable of parent class Dog points to object of child class Corgi, child classâs method implementation will be called.
Can we overload main() method?
Yes, we can overload main() method by passing different number/types of arguments to it. The JVM will call public static void main (String[] args) as its main method even though we overload it.
Why is method overloading not possible by changing only the return type of method?
Two otherwise similar methods having int and double as their respective return types will confuse JVM at the time of method calling and hence we cannot have only return type as a way of method overloading.
Explain output.
class Demo{ void test ( ) { System.out.println("No parameter"); }
void test (int a, int b) { System.out.println("a and b: "+a+" and "+b); }
void test (double a) { System.out.println("a: "+a); }
public static void main(String[] args){ test(); test(10,20); test(88); test(12.3); } }
No parameter a and b: 10 and 20 a: 88 a: 12.3 ----------------------------- When the test() method has only one input (88) and there is no exact match for this int parameter, Java will automatically type convert and call the test(double a) method.
What is upcasting?
When reference variable is of parent class and object is of child class, it is called upcasting. ParentClass var = new ChildClass();
Vice versa is not possible.
What is Inheritance?
It is the process by which one object (child) acquires properties of another object (parent).
The class which provides basic attributes to be inherited is called Parent Class/Superclass/Base Class.
The class which inherits the above class is called Child Class/Subclass/Derived Class.
Inheritance makes it possible for subclass to define only the unique qualities, as general attributes can be inherited from superclass.
How many superclasses can one subclass have?
Only one
Can a subclass act as a superclass to other classes?
Yes
Can a class be superclass of itself?
No
Can a subclass access private member of its superclass?
No
Is this valid?
class Super{ //class body }
class Sub extends Super{ //class body }
class Test{
public static void main (String[] args){ Super sup = new Super(); Sub sub = new Sub(); sup=sub; // 1 sub=sup; //2 } }
1 is valid, 2 will give compile-time type mismatch error
What can you access with below objects?
- Superclass sup = new Superclass();
- Superclass sup = new Subclass();
- Subclass sub = new Subclass();
- Subclass sub = new Superclass();
- Objects defined by Superclass only
- Objects defined by Superclass only
- All the objects defined by Superclass and Subclass except Superclassâs private objects
- Compilation error (type mismatch: cannot convert from Superclass to Subclass)
How to access method of a superclass?
Using super.methodName()
Where should call to superclassâs constructor be placed?
On the first line inside subclassâs constructor
Explain output.
class A{ void show () { System.out.println("Inside A"); }
class B extends A{ void show (String msg) { System.out.println(msg); }
class Test{ public static void main(String[] args){ B obj = new B(); obj.show("Inside B"); obj.show(); } }
Inside B
Inside A
âââââ
The methods are not overridden here, as method overridding needs methods with exact same signature in parent and child class. This is simply method overloading.
How JVM determines which overridden method to be called at runtime?
From the type of object (not the type of reference variable)
Why do we use the keyword super()?
- To call superclassâs consructor because constructors are not members and hence not automatically inherited.
- To call superclassâs non-private member which is hidden by member of subclass
What happens when we do not explicitly call superclassâs parameterless constructor?
JVM will implicitly call superclassâs parameterless constructor
Explain output.
class A{ A(){ System.out.println("Inside A's constructor"); } }
class B extends A{ B(){ System.out.println("Inside B's constructor"); } }
class C extends B{ C(){ System.out.println("Inside C's constructor"); } }
class Test{ public static void main(String[] args){ C obj = new C(); } }
Inside A's constructor Inside B's constructor Inside C's constructor ---------------------------------- Whether or not super() is used, constructors are always executed from starting from superclass to subclass.
Why isnât multiple inheritance not supported by Java?
If two parent classes having methods with same signature are inherited by a child class, which in turn acts as a parent class to another classes, then calling super.methodName() will be ambiguos as which method from which parent class to be invoked cannot be decided.
What is a literal?
A literal is a source code representation of a fixed value, be it an Integer or String.
Literals are represented in the code directly, without any computation.
Why do we need to write L or F for long/float numbers ?
Java considers a number as int by default unless stated otherwise.
Writing long num=123 will not give an error as 123 is treated as int and is well within the range of int.
Writing logn num=123456789789456 will give an error because the integer literal is not within the range of Integer and to tell Java that its a long data type, we need to write L.
Why does array indexing start with zero?
When an array is declared, the variable contains the reference to the memory location where the array is stored.
If the array is of size 10, and the first element is stored at memory location 2000, then the 10 elements will be placed contiguously as arrays are continguous data structures. The array declaration variable will then contain the memory address 2000 at which first element is stored.
Next element will be then stored at 2000+1st location, which means the first element is stored at 2000+0th location. Hence the array indexing starts with 0.
Why are strings in Java immutable?
Strings in Java get limited space for storing, called String pool. When a string is created, the JVM first checks if the same string literal exists in the String pool.
If it does, then the newly created String variable starts referring to the existing String literal. If not, new String literal is created.
When a String literal is being referenced by multiple references, modifying the literal for any one of them would change values for all. Hence Strings are immutable.
Why is String class in Java declared final?
As Strings are immutable, a String once created cannot be modified. But the modification can be done if String class can be inherited, then the String object from parent class will be available for modification by child class.
To avoid this, String class is declared final.
Explain the difference between
- String s=âHello Worldâ
and
- String s= new String(âHello Worldâ)
With (1), we are first checking if the String literal âHello Worldâ exists and assigning the variable âsâ to it if it does.
With (2), we are forcefully creating the string literal even if it already exists.
What is the difference between count++ and ++count?
Both the expressions will add 1 to the count and the difference will only be seen when count is passed as a parameter to some method or assigned to some variable.
count++ (called postincrement) will first pass the old value to method and then increment it.
For eg. x=i++ given i=5 will make x=5 and i=6.
++count (called preincrement) will first increment the value and pass the modified value to the method.
For eg. x=++i given i=5 will make x=6 and i=6.
What is the difference between logical AND (&&) and bitwise AND (&) operators?
Logical AND operator compares the values of two operands and returns true iff both the operands are true.
Bitwise AND operator when used with numeric operands performs the bitwise AND operation and returns the result.
For eg. int a=6, b=5, then a & b= 4
Bitwise AND operator when used with boolean operands compares both the operands and returns true iff both the operands are true.
Logical AND will short circuit the expression, i.e., if the first operand is false, it will not evaluate second operator. Bitwise AND (in boolean context) will evaluate both the operands in all conditions.
Logical AND in numeric context will produce compilation error.
Why does code (1) give compilation error but not code (2)?
- int val=50;
if (val=60) System.out.println(âYay!â); - boolean flag=false;
if (flag=true) System.out.println(âYay!â);
Because in code (2) the expression inside âifâ returns a boolean value eventually, which is accepted by the compiler.
What will be the output of given program?
public String foo (String s){
return âStringâ;
}
public String foo (Object o){
return âObjectâ;
}
foo (null) ;
String
As the compiler will pick the most specific method implementation, which here is the one accepting String parameter.
Why are the outputs of below two lines different?
long num1 = 1000606024365L; //31536000000
long num2 = 1000606024365; //1471228928
num1 is explicitly created as âlongâ with using L suffix, due to which compiler treats it as a long variable and the multiplication is within the range of long.
num2 is treated as an int by compiler and as the multiplication is out of intâs range, it is truncated by removing the MSBs to contain within int.
What will be the output of given program?
public String foo (String s){
return âStringâ;
}
public String foo (String[] str){
return âArrayâ;
}
foo (null) ;
Compilation error (The method foo(String) is ambiguous)
What will be the output of given program?
public String foo (String s){
return âStringâ;
}
public String foo (String[] str){
return âArrayâ;
}
foo (âHelloâ) ;
String
Define Object.
A Java object is a combination of state and behaviour. State is given by the field in class and behaviour is provided by methods.
Define Class.
A Java class is a blueprint/template from which objects are created.
Define Interface.
A Java interface is a group of related methods with empty bodies.
They only define the behaviour informally but do not provide the exact description.
What is JVM?
Java Virtual Machine (JVM) is the virtual machine that enables a system to run
- Java programs as well as
- programs written in other languages compiled to Java bytecode
JVM compiles a Java code to bytecode and is platform dependent (different platforms will have different implementation of JVM).
What is JRE?
Java Runtime Environment (JRE) is
- JVM
- Java class library
- java command and
- other infrastructure
bundeled together in a package which can be used to compile and execute Java code.
What is JDK?
Java Development Kit (JDK) is the software development kit used for developing and executing Java applications. It contains
- JRE
- java loader (Java)
- java compiler (javac)
- java archive (jar)
- java documentation generator (javadoc)
- other tools needed for Java application development
What is the difference between JVM, JRE and JDK?
- JVM is the specification where working of Java is specified.
- JRE= JVM + Java class library JRE is the implementation of JVM where we can execute (not develop) Java programs
- JDK = JRE + development tools
JDK is the development kit providing all the tools required to develop, compile, debug and execute a Java program.
Why is JVM called virtual machine? Whats the difference between JVM and VMWare?
JVM is called virtual because it does not exist physically, it is a software package that converts Java sourcecode to bytecode.
It is the software implementation of an abstract machine which is more like virtualized processor.
VMWare virtualizes the hardware of the machine on which it is running. It is also a software package installed on a machine so that different guest OSs can sit on top of it.
What is JIT?
Just In Time (JIT) is a way of executing code that involves compilation during execution of a program- at runtime- rather than compiling prior to execution.
The JIT compiler exists within JVM.
In JIT, not all code is converted to machine code. The source code is first converted to bytecode and as and when the code is needed, it is converted to machine code on the fly.
What makes Java platform independent?
Java code is converted to bytecode by JVM, which is platform dependent.
JVM is created different for different OSs, which can convert the Java code to bytecode which can run on that machine. Hence Java is platform independent if the JVM is already installed and running on the system.
Is Java 100% object oriented?
No. Java utilizes the 8 primitive data types (byte, short, int, long, float, double, char and boolean) which are not objects.
What is constructor in Java?
Constructor is a special type of method in a class which instantiates the class by creating its object.
Constructors must have same name as the class, must not have any return type and are called with ânewâ keyword.
Can a constructor be final/abstract/static/private?
Constructor can never be
- final: when a method is set as final, it means that it cannot be overridden by other method. But according to Java Language Specification, constructors are not members and are never inherited hence are not subject to hiding/overriding.
- abstract: when a method is set as abstract, it means that it cannot have a body and that the body should be provided by child classâs overriding method. But the constructor is called implicitly when ânewâ keyword is used and hence cannot lack body.
- static: when a method is declared static, it means that the method belongs to the class as a whole, not to the object. But the purpose of constructor is to create objects and it must have access to the class fields which are not static.
Constructor can be private to prevent instantiation outside of class (singleton pattern) or that the construction happens only internally (factory pattern).
Explain the access modifiers.
How a class member (fields and methods) and a class itself can be accessed by rest of the Java code is determined by the access modifiers attached to the class/field/method declaration.
There are 4 types of access modifiers- private, default (no access modifier specified in the declaration), protected and public.
private: member can be accessed in same class only
default: member can be accessed in same class and package only
protected: applies when inheritance is involved. The member can be accessed in same package and subclasses from different packages
public: member can be accessed by any other code
What is a wrapper class?
Many of the standard data structures of Java such as ArrayList operate on objects and passing them primitive values such as int does not work.
To handle this, Java provides type wrappers, which are classes that encapsulate the primitive type within an object.
There are total 8 wrapper classes (one per primitive type): Byte, Short, Integer, Long, Float, Double, Character and Boolean.
What is autoboxing and auto-unboxing in Java?
Collections in Java are used to hold objects of same type and we cannot store primitive values in them as they are.
Autoboxing is a process by which a primitive data type is automatically encapsulated (boxed) into its equivalent type wrapper whenever an object of that type is needed. There is no need to explicitly create an object.
Auto-unboxing is the process by which the value of a boxed object is automatically extracted (unboxed) from a type wrapper when its value is needed.
Integer iOb = 100; //autoboxing
int i = iOb; //auto-unboxing
What is abstract class?
The abstract class is the template to define a superclass and declares only the structure of the methods, letting subclasses implement their own implementation. Abstract class can have concrete methods as well.
Any class that contains one or more abstract methods must also be declared abstract. Any subclass of the abstract class must implement all of the abstract methods or be declared abstract itself.
Abstract class cannot be instantiated as it is not fully defined but they can be used to create object references because Javaâs approach to runtime polymorphism is implemented through the use of superclass references.
If we have a class Figure which is abstract and it is subclassed by another class Rectangle, then
Figure f = new Figure(); // is invalid
but
Figure f = new Rectangle (); // is valid
What is the difference between machine code and byte code?
Machine code is the set of instructions in machine language/binary which can be directly executed by CPU whereas byte code is an intermediate code generated by compiling a source code which can be executed by virtual machine.
What is Pass-by-value and Pass-by-reference? Which one of these is Java?
When a parameter is passed by reference, the caller and the callee are referring to the same variable. If the callee modifies the parameter, the effect is visible to callerâs variable.
When a parameter is passed by value, the caller and the callee are referring to two independent variables. If the callee modifies the parameter, the effect is not visible to callerâs variable.
Java only supports pass by value. As the values of variables can only be primitives or references, it seems like Java passes objects by reference, but that is not true.
What are the differences between == and equals method?
== is an operator and equals( ) is a method.
== compares references and equals( ) compares the contents. It means == checks if both the objects point to same location in memory whereas equals( ) checks the values of those objects.
equals( ) can throw NPE is first parameter is null.
What does ⊠in method parameter
public void foo (String ⊠s)
mean?
The three dots are called ellipsis and the feature is called varargs which was introduced in Java 5. It means that the function can receive multiple parameters of that type.
The method can respond to any calls from:
foo (âappleâ)
foo (âappleâ, âbananaâ)
foo (new String[ ] {âappleâ, âbananaâ, âpearâ})