interview deck 1 Flashcards
What are the important differences between C++ and Java?
- Java is platform independent. C++ is not platform independent.
- Java & C++ are both NOT pure Object Oriented Languages. However, Java is more purer Object
Oriented Language (except for primitive variables). In C++, one can write structural programs
without using objects. - C++ has pointers (access to internal memory). Java has no concept called pointers.
- In C++, programmer has to handle memory management. A programmer has to write code to
remove an object from memory. In Java, JVM takes care of removing objects from memory
using a process called Garbage Collection. - C++ supports Multiple Inheritance. Java does not support Multiple Inheritance.
What is the role of a ClassLoader in Java?
A Java program is made up of a number of custom classes (written by programmers like us) and core
classes (which come pre-packaged with Java). When a program is executed, JVM needs to load the
content of all the needed classes. JVM uses a ClassLoader to find the classes.
What are wrapper classes?
A brief description is provided below.
A primitive wrapper class in the Java programming language is one of eight classes provided in the
java.lang package to provide object methods for the eight primitive types. All of the primitive wrapper
classes in Java are immutable.
Wrapper: Boolean, Byte, Character, Double, Float, Integer,Long, Short
Primitive: boolean, byte,char, double, float, int, long, short
Why do we need Wrapper Classes in Java?
A wrapper class wraps (encloses) around a data type and gives it an object appearance.
Reasons Why We Need Wrapper Classes
* null is a possible value
* use it in a Collection
* Methods that support Object creation from other types.. like String
What are the different ways of creating Wrapper Class Instances?
Two ways of creating Wrapper Class Instances are described below.
Using a Wrapper Class Constructor
Integer number = new Integer(55);//int
Integer number2 = new Integer(“55”);//String
Float number3 = new Float(55.0);//double argument
Float number4 = new Float(55.0f);//float argument
Float number5 = new Float(“55.0f”);//String
Java Interview Questions and Answers – www.in28Minutes.com 15
Character c1 = new Character(‘C’);//Only char constructor
//Character c2 = new Character(124);//COMPILER ERROR
Boolean b = new Boolean(true);
//”true” “True” “tRUe” - all String Values give True
//Anything else gives false
Boolean b1 = new Boolean(“true”);//value stored - true
Boolean b2 = new Boolean(“True”);//value stored - true
Boolean b3 = new Boolean(“False”);//value stored - false
Boolean b4 = new Boolean(“SomeString”);//value stored - false
What is Auto Boxing?
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and
their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a
Double, and so on. If the conversion goes the other way, this is called unboxing.
Example 1
Integer nineC = 9;
Example 2
Integer ten = new Integer(10);
ten++; //allowed. Java does the hard work behind the screen for us
What is Implicit Casting?
Implicit Casting is done by the compiler.
Good examples of implicit casting are all the automatic widening
conversions i.e. storing smaller values in larger variable types.
int value = 100;
long number = value; //Implicit Casting
float f = 100; //Implicit Casting
What is Explicit Casting?
Explicit Casting is done through code. Good examples of explicit casting are the narrowing conversions.
Storing larger values into smaller variable types;
long number1 = 25678;
int number2 = (int)number1;//Explicit Casting
//int x = 35.35;//COMPILER ERROR
int x = (int)35.35;//Explicit Casting
Explicit casting would cause truncation of value if the
int bigValue = 280;
byte small = (byte) bigValue;
System.out.println(small);//output 24. Only 8 bits remain.
Are all String’s immutable?
Value of a String Object once created cannot be modified. Any modification on a String object creates a
new String object.
String str3 = “value1”;
str3.concat(“value2”);
System.out.println(str3); //value1
Note that the value of str3 is not modified in the above example. The result should be assigned to a new reference variable (or the same variable can be reused).
All wrapper class instances are immutable too!
String concat = str3.concat(“value2”);
System.out.println(concat); //value1value2
What are the differences between String and StringBuffer?
- Objects of type String are immutable. StringBuffer is used to represent values that can be
modified. - In situations where values are modified a number to times, StringBuffer yields significant performance benefits.
- Both String and StringBuffer are thread-safe.
- StringBuffer is implemented by using synchronized keywords on all methods.
What is a Class?
A class is a Template. In above example, Class CricketScorer is the template for creating multiple
objects. A class defines state and behavior that an object can exhibit.
What is an Object?
An instance of a class. In the above example, we create an object using the new CricketScorer(). The
reference of the created object is stored in the scorer variable. We can create multiple objects of the same
class.
What is the superclass of every class in Java?
Every class in Java is a subclass of the class Object. When we create a class we inherit all the methods
and properties of Object class.
What is the hashCode method used for in Java?
Hashcodes are used in hashing to decide which group (or bucket) an object should be placed into. A
group of objects might share the same hashcode.
The implementation of hash code decides the effectiveness of hash. A good hashing function evenly
distributes objects into different groups (or buckets).
A good hashCode method should have the following properties
* If obj1.equals(obj2) is true, then obj1.hashCode() should be equal to obj2.hashCode()
- obj.hashCode() should return the same value when run multiple times, if the values of obj used in equals() have not changed.
- If obj1.equals(obj2) is false, it is NOT required that obj1.hashCode() is not equal to obj2.hashCode(). Two unequal objects MIGHT have the same hashCode.
What is Method Overloading?
A method having the same name as another method (in the same class or a sub-class) but having a different
parameters is called an Overloaded Method.
What is Method Overriding?
Creating a Sub Class Method with the same signature as that of a method in SuperClass is called Method Overriding.
Is Multiple Inheritance allowed in Java?
Multiple Inheritance results in a number of complexities. Java does not support Multiple Inheritance.
What is an Interface?
- An interface defines a contract for responsibilities (methods) of a class.
- An interface is a contract: the guy writing the interface says, “hey, I accept things looking that way”
- Interface represents common actions between Multiple Classes.
- Example in Java api: Map interface, Collection interface.
How do you define an Interface?
An interface is declared by using the keyword interface. Look at the example below: Flyable is an
interface.
How do you implement an interface?
We can define a class implementing the interface by using the implements keyword. Let us look at a
couple of examples:
Example 1
Class Aeroplane implements Flyable and implements the abstract method fly().
public class Aeroplane implements Flyable{
@Override
public void fly() {
System.out.println(“Aeroplane is flying”);
}
}
Example 2
public class Bird implements Flyable{
@Override
public void fly() {
System.out.println(“Bird is flying”);
}
}
Variables in an interface are always public, static, final. Variables in an interface cannot be declared
private.
Can a class extend multiple interfaces?
A class can implement multiple interfaces. It should implement all the method declared in all Interfaces
being implemented.
An example of a class in the JDK that implements several interfaces is HashMap, which implements the
interfaces Serializable, Cloneable, and Map. By reading this list of interfaces, you can infer that an
instance of HashMap (regardless of the developer or company who implemented the class) can be
cloned, is serializable (which means that it can be converted into a byte stream; see the section
Serializable Objects), and has the functionality of a map.
What is an Abstract Class?
An abstract class is a class that cannot be instantiated, but must be inherited from. An abstract class may
be fully implemented, but is more usually partially implemented or not implemented at all, thereby
encapsulating common functionality for inherited classes.
When do you use an Abstract Class?
component, use an abstract class. Abstract classes allow you to partially implement your class.
* An example of an abstract class in the JDK is AbstractMap, which is part of the Collections
Framework. Its subclasses (which include HashMap, TreeMap, and ConcurrentHashMap) share
many methods (including get, put, isEmpty, containsKey, and containsValue) that AbstractMap
defines.
o example abstract method : public abstract Set> entrySet();
How do you define an abstract method?
An Abstract method does not contain a body. An abstract method does not have any implementation. The implementation of an abstract method should be provided in an over-riding method in a sub-class.
//Abstract Class can contain 0 or more abstract methods
//Abstract method does not have a body
abstract void abstractMethod1();
abstract void abstractMethod2();
Compare Abstract Class vs Interface?
Syntactical Differences
* Methods and members of an abstract class can have any visibility. All methods of an interface
must be public.
* A concrete child class of an Abstract Class must define all the abstract methods. An Abstract
child class can have abstract methods. An interface extending another interface need not provide
default implementation for methods inherited from the parent interface.
* A child class can only extend a single class. An interface can extend multiple interfaces. A class
can implement multiple interfaces.
* A child class can define abstract methods with the same or less restrictive visibility, whereas a
class implementing an interface must define all interface methods as public
What is a Constructor?
Constructoris invoked whenever we create an instance(object) of a Class. We cannot create an object
without a constructor.
Constructor has the same name as the class and no return type. It can accept any number of parameters.
What is a Default Constructor?
Default Constructor is the constructor that is provided by the compiler. It has no arguments. In the
example below, there are no Constructors defined in the Animal class. Compiler provides us with a
default constructor, which helps us create an instance of animal class.
public class Animal {
String name;
public static void main(String[] args) {
// Compiler provides this class with a default no-argument
//constructor.
// This allows us to create an instance of Animal class.
Animal animal = new Animal();
}
}
Will this code compile?
class Animal {
String name;
public Animal() {
this.name = “Default Name”;
}
// This is called a one argument constructor.
public Animal(String name) {
this.name = name;
}
public static void main(String[] args) {
Animal animal = new Animal();
}
}
The answer is no. Since we provided a constructor, the compiler does not provide a default constructor
Is a super class constructor called even when there is no explicit call from a sub class constructor?
If a super class constructor is not explicitly called from a sub class constructor, super class (no argument)
constructor is automatically invoked (as first line) from a sub-class constructor.
What is Polymorphism?
Polymorphism is defined as “Same Code” giving “Different Behavior”. Let’s look at an example.
Let’s define an Animal class with a method shout.
public class Animal {
public String shout() {
return “Don’t Know!”;
}
}
Let’s create two new sub-classes of Animal overriding the existing shout method in Animal.
class Cat extends Animal {
public String shout() {
return “Meow Meow”;
}
}
class Dog extends Animal {
public String shout() {
return “BOW BOW”;
}
public void run(){
}
}