Java Interview Questions Part 1

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What is Java Class?

A class in Java is a blueprint for object which includes all your data. A class contains fields (variables) and methods to describe the behavior of an object. Based on the class description we create the objects

Define Class in Java.

A class in Java is a blueprint which includes all your data. A class contains fields (variables) and methods to describe the behavior of an object.Classes are located Java package. Java have some built in classes which we can use.(For example: String). And we can also create our own classes to write code in it.

Why we use List interface? What are classes implementing List interface?

A java ​List ​is a "ordered" collection of elements. This ordering is a zero based index. It does not care about duplicates. Apart from methods defined in Collection interface, it does have its own methods also which helps to manipulate the collection based on index location of element. The classes implementing List interface are: ​Stack, Vector, ArrayList ​and ​LinkedList.

What is the difference between break and continue statements?

A ​continue​ statement skips the current executing loop and MOVES TO the next loop whereas ​break​ MOVES OUT of the loop and executes the next statement after the loop.

How would you convert an ArrayList to Array and an Array to ArrayList?

An Array can be converted into an ArrayList by making use of the ​asList() method provided by the Array class. It is a static method that accepts List objects as a parameter. int[] num={1,2,3,4,5}; Arrays.​asList(num)​; Whereas an ArrayList can be converted into an Array using the ​toArray() method of the ArrayList class. List<Integer> list=new ArrayList<>(); int[] arr=list.​toArray()​;

What is your approach to handle the following situation? You are working a customer service application. If multiple calls accepted at the same time, your application should put the received calls into the order based on the time call received then direct them to the next available representative. The earlier received call will be directed first.

Answer: Queue should be used to maintain order of the calls. Since Queue works based on first in first out principle, the first received call will be the first to be directed to the next available representative.

What is literal in java?

Any constant value which can be assigned to the variable is called as literal. For example: String name="Tom" , int count=8; Here Tom and 8 are literals.

What is difference between ArrayList and LinkedList?

ArrayList and LinkedList both implement List interface but there are some differences between them. 1. ArrayList is an index based data structure that's why it is faster to get element with index number. 2. Insertion, addition or removal of an element is ​faster ​in LinkedList compared to ArrayList because there is no concept of resizing array or updating index when element is added in the middle. 3. LinkedList consumes more memory than ArrayList because every node in LinkedList stores reference of previous and next elements.

Is there a way to increase the size of an array after its declaration?

Arrays are static and once we have specified its size, we can't change it. If we should use collections instead of arrays where we may require a change of size

What is difference between Array and ArrayList? When will you use Array over ArrayList?

Arrays can contain primitive or Objects types whereas ArrayList can contain only Objects. Arrays are fixed-size whereas ArrayList size is dynamic. Arrays don't provide a lot of features like ArrayList, such as addAll, removeAll, iterator, etc. Although ArrayList is the obvious choice when we work on the list, there are a few times when an array is good to use. - If the size of the given list is fixed and mostly used to store and traverse them. - If you are working with primitive data types, it is easier to use array - If you are working on fixed multi-dimensional situation, using [][] is far more easier than List<List<>>

What are similarities and difference between ArrayList and Vector?

Both ArrayList and Vector implement List interface and both are index based and accept duplicate values. On the other hand Vector is synchronized which is thread safe but ​ArrayList is not synchronized

What is difference between HashSet and TreeSet?

Both HashSet and TreeSet implements Set interface and both don't accept duplicate elements however they have the following differences: 1. HashSet returns elements in any random order, but TreeSet sorts elements in ascending order. 2. Hashset allows one null value whereas TreeSet doesn't accept any null values. Otherwise it will throw NullPointerException

What is difference between TreeSet and LinkedHashSet?

Both LinkedHashSet and TreeSet implements Set interface and both don't accept duplicate elements however they have the following differences: 1. LinkedHashSet maintains the insertion order elements, but TreeSet sorts elements in ascending order. 2. LinkedHashSet allows one null value whereas TreeSet doesn't accept any null values. Otherwise it will throw NullPointerException

What is Queue and Stack, list their differences?

Both Queue and Stack are used to store data before processing them. java.util.Queue is an interface whose implementation classes are present in java concurrent package. Queue allows retrieval of element in First-In-First-Out (FIFO) order. There is also Deque interface that allows elements to be retrieved from both end of the queue. The Stack is similar to Queue except that it allows elements to be retrieved in Last-In-First-Out (LIFO) order. Stack is a class that extends Vector whereas Queue is an interface.

What is the difference between "&&" and "||" operators?

Both are logical operators and mainly used in conditional statements. "&&" means ​AND​ but "||" has OR meaning. "&&" returns true only both sides of condition are ​TRUE​ otherwise it returns ​FALSE "||" ​returns false only both sides of condition are ​FALSE. ​In all other cases it returns TRUE

What is the difference between peek(), poll() and remove() method of the Queue interface?

Both ​poll() and ​remove() methods are used to remove the head object of the Queue. The main difference lies when the Queue is empty. If the Queue is empty then the ​poll() method will return null. While in similar case, remove()​ method will throw ​NoSuchElementException​ . peek() method retrieves but does not remove the head of the Queue. If the queue is empty then the peek() method also returns null.

Where can break and continue statements be used?

Break ​statement can be used in switch statement and loops Continue ​statement​ ​is used only in loops

What are the basic interfaces of Java Collections Framework?

Collection​ ​is the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Java platform doesn't provide any direct implementations of this interface. Set​ ​is a collection that cannot contain duplicate elements. Elements don't have index . List​ ​is an ordered collection and can contain duplicate elements. You can access any element from its index. The list is more like an array with dynamic length. Map​ ​is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Some other interfaces are​ ​Queue​, ​Dequeue​.

What's the difference between constructors and methods?

Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

How to remove repeated elements from ArrayList?

First we need to copy all the elements of ArrayList to LinkedHashSet. Why we choose LinkedHashSet? Because it removes ​duplicates ​and maintains the ​insertion ​order. Then we make the ArrayList empty by using ​clear()​ method. Then copying all the elements of LinkedHashSet (non-duplicate elements) to the ArrayList by using ​addAll()​ method.

What Are The Different Ways To Sort A List Of Objects?

Following methods can be applied to perform sorting. ● To sort an array of objects, you can use ​Arrays.sort()​ method. ● When you need to sort a collection of objects, then use ​Collections.sort()​ method.

What is the difference between HashMap and Hashtable?

HashMap and Hashtable both implements Map interface and looks similar, however, there is the following difference between HashMap and Hashtable. 1. HashMap allows one null key and multiple null values whereas Hashtable doesn't allow any null key or null value. 2. HashMap is not synchronized but Hashtable is synchronized .

What is the difference between HashMap and TreeMap?

HashMap and TreeMap both implements Map interface and looks similar, however, there is the following difference between HashMap and TreeMap. 1. HashMap allows one null key whereas TreeMap doesn't allow any null key. But both can have multiple null values 2.HashMap maintains no order but TreeMap maintains ascending order ofelements.

What is the difference between Hashtable and TreeMap?

Hashtable ​and TreeMap both implements Map interface and looks similar, however, there is the following difference between HashMap and TreeMap. TreeMap can have multiple null values but Hashtable cannot have any null values. Both Hashtable and TreeMap cannot have any null key. TreeMap ​is not synchronized but Hashtable is synchronized .

How do you decide when to use ArrayList and LinkedList?

If you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList should be used. If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList should be used.

What Are The Primary Interfaces In The Java Collections Framework?

Java Collections Framework comprises of five primary interfaces. - Collection Interface ​- Most of the collections in Java inherit from the Collection interface. It is the core of the collections framework and stays at the root of Collection's hierarchy. - Set Interface​ - It is a mathematical interpretation of Set which doesn't allow duplicate entries. Also, a set doesn't define an order for the elements and hence doesn't support the index-based search. - Queue Interface​ - This interface follows the principles of a queue and stores elements in the same order as they enter. Operations like addition will take place at the rear and removal from the front. - List Interface ​- A list is an extended form of an array. Lists are ordered and can also contain duplicate elements. Not only it allows the index-based search, but insertion can also be done independently of the position. - Map Interface​ - Map is a two-dimensional data structure which stores data in the form of Key-Value pair. The map is necessarily a set and can't have duplicate elements.

What is the Stack class in Java and what are the methods provided by Stack class?

Java Stack class is an important part of the Java Collection framework and is based on the basic principle of ​last-in-first-out​. In other words, the elements are added as well as removed from the rear end. The action of adding an element to a stack is called ​push ​while removing an element is referred to as ​pop​. Following methods are specific for Stack class: empty() - checks if the stack is empty push() - puts an item to the top of the stack pop() - removes an item from the stack peek() - looks at the object of a stack without removing search() - searches item in the stack to get its index

Can we override final method in Java?

No, you cannot override final method in Java. Trying to override final method in subclass will result in compile time error. Actually making a method final is signal to all developer that this method is not for inheritance and it should be used in its present form. You generally make a method final due to security reasons.

Can we call a non-static method from inside a static method?

Non-Static methods are owned by objects of a class and have object level scope and in order to call the non-Static methods from a static block (like from a static main method), an object of the class needs to be created first. Then using object reference, these methods can be invoked​.

Where and how can you use a private constructor​?

Private constructor is used if you do not want other classes to instantiate the object and to prevent subclassing.

There are two classes named classA and classB. Both classes are in the same package. Can a private member of classA can be accessed by an object of classB?

Private members of a class aren't accessible outside the scope of that class and any other class even in the same package can't access them.

Compare Queue and Stack

Queue works based on FIFO (​First-In-First-Out​) principle but Stack works based on LIFO (​Last-In-First-Out​) principle In Queue insertion and deletion takes place from two opposite ends but In Stack Insertion and deletion takes place the same end. Queue is an Interface and used with LinkedList or PriorityQueue classes but Stack itself is a class and extends to Vector class

Can you overload or override main method in Java?

Since main() is a static method in Java, it follows rules associated with static method, which means you can overload main method but you cannot override it. By the way, even if you overload a main method, JVM will always call the standard public static void main(String args[]) method to start your program. If you want to call your overloaded method you need to do it explicitly in your code.

What is the output of following code? for ( ; ; ) { System.out.println("Hello World"); }

Since this for loop has no condition, it's an infinite loop, it'll keep printing Hello World.

Is String a data type in Java?

String is not a primitive data type in Java. When a string is created in java, it's actually an object of Java.Lang.String class that gets created. After creation of this string object, all built-in methods of String class can be used on the string object.

Why Map doesn't extend the Collection Interface?

The Map interface in Java follows a key/value pair structure whereas the Collection interface is a collection of objects which are stored in a structured manner with a specified access mechanism. The main reason Map doesn't extend the Collection interface is that the add(​element​) method of the Collection interface doesn't support the key-value pair like Map interface's ​put(​Key, Value​) method. It might not extend the Collection interface but still is an integral part of the Java Collections framework.

Difference between Set and List?

The most noticeable differences are : ● Set is unordered collection whereas List is ordered collection based on zero based index. ● List allow duplicate elements but Set does not allow duplicates. ● List does not prevent inserting null elements (as many you like), but Set will allow only one null element.

What is ​identifier ​in Java?

The names of variables, methods or classes are called identifiers in Java.

What is ​super ​keyword In Java?

The super keyword in java is a reference variable that is used to refer to immediate parent class object. Whenever you create the instance of subclass, an instance of the parent class is created implicitly i.e. referred by super reference variable. Super keyword has three purposes: - super. is used to refer to immediate parent class instance variable. - super() is used to invoke immediate parent class constructor. - super is used to invoke immediate parent class method.

Which one you will prefer between Array and ArrayList for storing object and why?

Though ​ArrayList ​is also backed up by array, it offers some usability advantage over array in Java. ​Array ​is fixed length data structure, once created you can not change it's length.On the other hand, ArrayList is dynamic, it automatically allocate a new array and copies content of old array, when it resizes. Another reason of using ArrayList over Array is support of Generics. Array doesn't support Generics, and if you store an Integer object on a String array, you will only going to know about it at runtime, when it throws ArrayStoreException. On the other hand, if you use ArrayList, compiler and IDE will catch those errors on the spot. So if you know the size in advance and you don't need re-sizing than use array, otherwise use ArrayList.

How variables are named in Java?

Variable name can contain letters, numbers, _ and $. It can start with letter, $, and _ but cannot start with a number. It cannot contain white spaces. If variable name is one word, it starts with lower case but if it is multiple words it is written with camel case.

What is the difference between ArrayList and HashMap?

We can compare ArrayList and HashMap from following perspectives: - ​Implementation:​ ArrayList implements List Interface while HashMap is an implementation of Map interface. List and Map are two entirely different collection interfaces. - Memory consumption​: ArrayList stores the element's value alone and internally maintains the indexes for each element. ArrayList​<​String​> arraylist = ​new​ ​ArrayList​<​String​>(); //String value is stored in array list arraylist.add(​"Test String"​); HashMap stores key & value pair. For each value there must be a key associated in HashMap. That clearly shows that memory consumption is high in HashMap compared to the ArrayList. HashMap​<​Integer​, ​String​> hmap= ​new​ ​HashMap​<​Integer​, ​String​>(); //String value stored along with the key value in hash map hmap.put(​123​, ​"Test String"​); - Order: ArrayList maintains the insertion order while HashMap doesn't. Which means ArrayList returns the list items in the same order in which they got inserted into the list. On the other hand HashMap doesn't maintain any order, the returned key-value pairs are not sorted in any kind of order. - Duplicates​: ArrayList allows duplicate elements but HashMap doesn't allow duplicate keys - Nulls​: ArrayList can have any number of null elements. HashMap allows one null key and any number of null values. - Get method​: In ArrayList we can get the element by specifying the index of it. In HashMap the elements is being fetched by key.

Can we have two methods in a class with the same name?

We can define two methods in a class with the same name but with different number/type of parameters. Which method is to get invoked will depend upon the parameters passed.This concept is called Overloading In Java.

Which operator should be used instead of dots(...) to make all statements correct? false ... false = false; false ... true = true; true ... false =true; true ... true = false;

We have to use exclusive OR( ^ ) instead of dots because exclusive OR( ^ ) returns ​false ​when both sides of expression are the same: like both side are ​true​ or ​false​ . If one side of expression is ​true​ and the other side is ​false​ it will return TRUE.

Difference between Set, List and Map Collection classes?

java.util.Set​, ​java.util.List and ​java.util.Map defines three of the most popular data structure support in Java. Set provides guarantee that it doesn't store duplicate elements, but it's not ordered. On the other hand List is an ordered Collection and also allows duplicates. Map is based key and value structure. Objects are retrieved with key from Map. Popular implementation of Set is ​HashSet, TreeSet​, ​LinkedHashSet ​of List is ​ArrayList ​and LinkedList​, and of Map are ​HashMap, TreeMap ​and ​Hashtable​. Another key difference between Set, List and Map are that Map doesn't implement Collection interface, while the other two does.

What is the difference between this() and super() in Java?

this()​ is used to call constructor of the same class from another constructor but ​super()​ is used to call the parent class constructor.

What is method hiding in Java?

Since the static method cannot be overridden in Java, but if you declare the same static method in subclass then that would hide the method from the superclass. It means, if you call that method from subclass then the one in the subclass will be invoked but if you call the same method from superclass then the one in superclass will be invoked. This is known as method hiding in Java.

What are Wrapper classes?

These are classes that allow primitive types to be accessed as objects. Example: Integer, Character, Double, Boolean, Long etc.

Can a variable be local and static at the same time?

No a variable can't be static as well as local at the same time. Defining a local variable as static gives compilation error​.

Which are the primitive data types in Java?

The eight primitive types are byte, char, short, int, long, float, double, and boolean.

Explain the usage of ​this ​and ​this()​ in Java?

this ​keyword refers to instance variable of a class. We can not create two instances/local variables with the same name. However, it is legal to create one instance variable & one local variable with the same name and we can use ​this ​keyword to refer instance variable. this()​ is used to refer to the constructor of the class. When we need to call a constructor inside of another constructor, we can call ​this() ​instead of calling constructor with its name

Difference between Arrays and ArrayList in Java?

- Array is a part of core Java programming and has special syntax ArrayList is part of collection framework and implement List interface - Major difference is that; Array is a fixed length data structure, so we ​cannot ​change the length of Array once it was created, but ArrayList is resizable. - The other major one is that Array can contain both primitives and objects. ArrayList can only contain objects. It cannot contain primitive types. - Also, we can compare Array and ArrayList on how to calculate the length of Array or size of ArrayList. We use length for an Array, we use size() method for an ArrayList.

Which data types we can use to declare variable k to make code compile and why? ... k=5; int m=6; int total = k+m;

Since variable ​total​ is int, then we can use ​byte​, ​short​ and ​int​ to declare variable k. Because if you add any of these data types with integer result will be integer.

What's the purpose of Static methods and static variables?

When there is a requirement to share a method or a variable between multiple objects of a class instead of creating separate copies for each object, we use static keyword to make a method or variable shared for all objects. We can reach a static method or variable by using class name of that method or variable.

Which data types can be used with variables in a switch statement?

Variables used in a switch statement can only be a string, enum, byte, short, int, or char.

How can you find greatest number inside an integer array?

We have to use loop and if (or ternary operator) condition to handle this problem. First we compare the first two elements inside the array and find the greater one then compare the next element with it. By this way we compare all elements and find the greatest one.

How to check if an integer array has duplicate element or not?

We should use loop for it. First we compare the first element of array with the other elements, then the second element, then the third element. By this way we compare all elements with each other to find if array has duplicate element or not.

What is the difference between = and == ?

We use = to assign a value to a variable or a variable to another variable but == is used to check whether two values or objects are equals to each other

What is an infinite loop in Java?

When loop condition is programmed to never becomes false, it results in an infinite loop. That means it will keep running the loop statement code infinitely.

Difference between Object and Class?

- Class is a blueprint or template which you can create as many objects as you like. Object is a member or instance of a class - Class is declared using ​class ​keyword, Object is created through ​new ​keyword mainly. A class is a template for objects. A class defines object properties including a valid range of values, and a default value. A class also describes object behavior. An object is a member or an "instance" of a class and has states and behaviors in which all of its properties have values that you either explicitly define or that are defined by default settings. Class - A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support. If we compare them there are many differences but let me tell you some of them which are important to know; - There are many ways to create object in java such as ​new ​keyword, ​newInstance​() method, clone​() method, ​factory​() method and deserialization. There is only one way to define class in java using class keyword. - Object is created many times as per requirement. Class is declared once. - Object is an instance of a class. Class is a blueprint or template from which objects are created. - Object is a physical entity. Class is a logical entity. For Example: Class: Human --Object: Man, Woman Class: Fruit -- Object: Apple, Banana, Mango, Guava Class: Food -- Object: Pizza, Burger, Samosa

What is encapsulation and how did you use it?

- Encapsulation is data hiding by making variables private and providing public getter and setter methods. Since variables are private, they cannot be accessed from other classes. So in order to use them, user needs to use getter and setter methods. In my project I created multiple POJO/BEAN classes in order to manage test data and actual data. EX: I take JSON from API response and convert to object of my POJO class all variables are private with getters and setters.

Difference between method Overloading and method Overriding?

- First and most important difference between overloading and overriding is that, in case of overloading , method name must be the same, but the parameters must be different; - in case of overriding , method name and parameters must be the same - Second major difference between method overloading and overriding is that; o We can overload method in the same class but method overriding occurs in two classes that have inheritance relationship. - We cannot override static, final and private method in Java, but we can overload static, final and private method in Java. - In method overloading , return type can be same or different. In method overriding , return type must be the same type​. - In method overloading access modifier of that method does not play any role, but in overriding, access modifier of child method should be same or larger than parent version of that method. For Example: If parent method is public, child method can only be public, cannot be protected, default or private.

What is Polymorphism?

- Polymorphism is a very important concept in OOP because; - it enables to change the behavior of the applications in the run time based on the object on which the invocation happens. By Polymorphism; one object can have different forms Two types →​ Compile Time​ which is Static and ​Run Time​ Polymorphism which is related with child and parent class. Polymorphism is implemented using the concept of Method overloading and method overriding. This can only happen when the classes are under the parent and child relationship using inheritance.

You have two integer variables(int a=3 and int b=5). How can you swap their values without using another variables. ​(result should be like: int a=5 and int b=3)

1st step: a=a+b; >>>> result of it : a=8, b=5 2nd step: b=a-b; >>>> b=8-5 and b grabs new value which is 3; but a is still 8; 3rd step: a=a-b; >>>> a=8-3 and a takes new value which is 5​.

What is method in Java?

A method is a set of code to perform an operation. A methods is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name. Think of a method as a subprogram that acts on data and often returns a value. Each method has its own name, return type, access modifier.

What are the restriction imposed on a static method or a static block of code?

A static method should not refer to instance variables without creating an instance and cannot use "this" operator to refer the instance.

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. Non-static variables take on unique values with each object instance. To reach non-static variable from another class we need to create an object of the class which the non-static variable belongs to. But we can reach static variable from another class by using class name of static variable

List the three steps for creating an Object for a class?

An Object is first ​declared​, then ​instantiated ​and then it is ​initialized​.

What is Array?

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. Each item in an array is called an element, and each element is accessed by its numerical index. Index numbering begins with 0. For example: 9th element in an array is at index 8. Advantage of Java Array: Code Optimization: It makes the code optimized, we can retrieve or sort the data easily. Random access: We can get any data located at any index position. Disadvantage of Java Array: Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.

Do you know typecasting? What is casting?

Auto-boxing → is converting a primitive value into an object of the corresponding wrapper class int i=10; Integer n=i; Integer num=200; Un-boxing → is a process when you take Wrapper class object and convert to primitive. Integer num2=new Integer(400); int i=num2; Assigning a value of one type to a variable of another type is known as Type Casting. double price=19.99; int a=(int)price;

What is the difference between equals() and == in Java?

Both equals() and "==" operator in Java is used to compare objects to check equality but the main difference is equals() is a method but the == is an operator. Another notable difference is that == operator is used to compare both primitive and objects while equals() method is only used for objects comparison When we compare two objects with == operator, it compares reference or memory location of objects in the heap, whether they point to the same location or not. If the point same location in heap, it returns true, otherwise it returns false. When we compare two non-primitive data types with == operator, it checks their value.If both have the same value, it will return true, otherwise it returns false. If we compare two objects with equals() method, it checks their contents. If both have the same contents, it returns true, otherwise it returns false. We cannot use equals() method to compare non-primitive data types.

What is the difference between "&&" and "&" operators?

Both have 'AND' meaning. "&&" is logical operator but "&" is bitwise operator. The logical "&&" operator doesn't check second condition if first condition is false. It checks second condition only if first one is true, but the bitwise "&" operator always checks both conditions whether first condition is true or false.

What's the purpose of using ​Break i​n each case of Switch Statement?

Break is used after each case in a switch so that code breaks after the valid case and doesn't flow in the proceeding cases too. If break isn't used after each case, all cases after the valid case also get executed resulting in wrong results.

How do you restrict a member of a class from inheriting to its sub classes?

By declaring that member as a private. Because, private members are not inherited to sub classes.

Explain me what happens when code is compiled in Java?

Compile means source code in ​*​.java ​file converted into byte codes and stored in ​*​.class ​file with the same name as .java file For example: when ​cars.java​ file is compiled, source code is converted to byte codes and stored in ​cars.class​ file.

What is constant variables in Java?

Constant variables are the ones whose value cannot change once it has been assigned. To define a variable as a constant, we just need to add the keyword "​final​" in front of the variable declaration. For example: ​final​ String name="Yoll Academy";

Can we call the constructor of a class more than once for an object?

Constructor is called automatically when we create an object using ​new k​eyword. It's called only once for an object at the time of object creation and hence, we can't invoke the constructor again for an object after its creation.

What's the default access specifier for variables and methods of a class?

Default access specifier for variables and method means variables and methods are accessible from any other classes in the same package, classes in other packages cannot access those variables and methods.

What is the difference between ​while ​and ​do while​ loops?

Do-while​ loop will run at least once even though​ ​condition is ​false , but in ​while loop, it first checks condition, it only runs if condition is ​true​.

What is the difference between "else if" and "else"?

ELSE IF​ is a conditional statement performed after an if statement to add extra conditions to the code. And we can use multiple ​ELSE IF​ condition in the same if-else block. ​ELSE IF​ condition is executed when ​IF​ statement is ​false. ELSE​ statement is used after ​IF​ and ​ELSE IF​ statements and only executes ​IF​ and all existed ​ELSE IF​ statements are false. Both ​ELSE​ and ​ELSE IF​ are optional.

What is Encapsulation?

Encapsulation is a concept in Object Oriented Programming and ​it is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. Therefore encapsulation is also referred to as data hiding.

How objects of a class are created if no constructor is defined in the class?

Even if no explicit constructor is defined in a java class, objects get created successfully as a default constructor is implicitly used for object creation. This constructor has no parameters.

What is the difference between expression and statement in Java?

Expressions consist of variables, operators that evaluates to a single value. Statements are everything that make up a complete unit of execution. A Statement consists of expressions.For Example: b + 1 is an expression while a = b + 1; is a statement.

What is Heap and Stack in Java?

Heap ​is a section of memory which contains Objects and may also contain reference variables​. Instance variables are created in the heap. Stack ​in java is also section of memory which contains methods, local variables, and reference variables. They contain method specific values which are short-lived. This is the temporary memory where variable values are stored when their methods are invoked. After the method is finished, the memory containing those values is cleared to make room for new methods.

I have multiple constructors defined in a class. Is it possible to call a constructor from another constructor's body?

If a class has multiple constructors, it's possible to call one constructor from the body of another one using ​this()​.

When ​super ​keyword is used?

If the method overrides one of its superclass's methods, overridden method can be invoked through the use of the keyword super. It can be also used to refer to a hidden field.

What is the difference between a local variable and an instance variable?

In Java, a ​local ​variable is typically used inside a method, constructor, or a block and has only local scope. Thus, this variable can be used only within the scope of a block. The best benefit of having a local variable is that other methods in the class won't be even aware of that variable. Whereas, an ​instance ​variable in Java, is a variable which is bonded to its object itself. These variables are declared within a class, but outside a method. Every object of that class will create its own copy of the variable while using it. Thus, any changes made to the variable won't reflect in any other instances of that class and will be bound to that particular instance only.

Difference between Public, Private and Protected modifier in Java?

In Java, access modifier which specifies accessibility of classes, methods and variables. There are four access modifiers in Java namely ​Public, Private, Protected​ and ​Default​. The difference between these access-modifies is that; Access modifiers define the level of accessibility. - Public ​is accessible to anywhere - Private ​is only accessible in the same class which is declared - Default ​is accessible only inside the same package - Protected ​is accessible inside the same package and also outside the package but only the child classes. We cannot use private or protected modifier with a top--level class. We should also keep in mind that local ​variables cannot be public, private or protected in Java.

What are the various access modifiers for Java classes?

In Java, access modifiers are the keywords used before a class/method/variable name which defines the access scope. The types of access modifiers for classes are: ​Public ​: Class,Method,Field is accessible from anywhere. Protected​:Method,Field can be accessed from the same class to which they belong or from the sub-classes, and from the class of same package, but not from outside. Default​: Method,Field,class can be accessed only from the same package and not from outside of its native package. Private​: Method,Field can be accessed from the same class to which they belong.

What is getter and setter (get & set) methods in Java and why they are used?

In Java, getter and setter are two conventional methods that are used for retrieving and updating the value of a variable. They are especially used for private variables.Private variables cannot be accessed by other classes. To control the access to a variable, programmers use getter and setter methods to assign a value or get the value of variables.

Define Packages in Java and why we use packages?

In Java, package is a collection of related types classes and interfaces which are bundled together as they are related to each other. Use of packages helps developers/testers to modularize the code and group the code for proper re-use. Packages are used in Java in order to prevent naming conflicts, to control access, to group the classes, to make searching/locating and usage of classes, interfaces easier. Once code has been packaged in Packages, it can be imported in other classes and used.

What is the final variable?

In Java, the final variable is used to restrict the user from updating it. If we initialize the final variable, we can't change its value. In other words, we can say that the final variable once assigned to a value, can never be changed after that. The final variable which is not assigned to any value can only be assigned through the class constructor.

What is default switch case?

In a switch statement, default case is executed when no other switch condition matches. Default case is an optional case .It is coded at the end : - after all switch cases but can also be written between cases. But execution still happens after all cases checked

How garbage collection works in Java?

In java, Garbage Collection is a process of destroying unused objects to free up space in heap memory. When an object is not referenced any more, garbage collection takes place and the object is destroyed automatically. For automatic garbage collection java calls either System.gc() method or Runtime.gc() method.It is automatically in Java, which means you don't have to worry about unused memory. Garbage collection is run by JVM and we don't know when it runs. We can also request JVM to run Garbage Collector by using: System.gc(); It may or may not run we cannot force it.

Why Strings in Java are called as Immutable?

In java, string objects are called immutable as once value has been assigned to a string, it can't be changed and if changed, a new object is created.In below example, reference str refers to a string object having value "Value one"​. String str="Value One"; When a new value is assigned to it, a new String object gets created and the reference is moved to the new object​. str="New Value";

What is Inheritance in Java?

Inheritance is an Object oriented feature which allows a class to inherit behavior and data from other class. For example, a class Car can extend basic feature of Vehicle class by using Inheritance. One of the most intuitive examples of Inheritance in the real world is Father-Son relationship, where Son inherit Father's property. - Inheritance means one object gets all the properties and behaviors of parent object. - Inheritance is a compile-time mechanism. - A super-class can have any number of subclasses. But a subclass can have only one superclass. - The ​extends ​keyword indicates that you are making a new class that derives from an existing class. - The superclass and subclass have "​is-a​" relationship between them.

Difference between Polymorphism and Inheritance​?

Inheritance is used to define the relationship between two classes. It is similar to Father-Son relationship like in the real world. In Java, we have Parent class (also known as super class) and child class (also known as subclass). Similar to the real-world, Child inherits Parents qualities. - A child class can reuse all the codes written in Parent class and only write code for behavior which is different than the Parent. - Inheritance is actually meant for code reuse. On the other hand, Polymorphism is the ability of objects to behave in multiple forms. - It is classified as overloading and overriding. By the way, they are actually related to each other, because Inheritance makes Polymorphism possible. It is not possible to write polymorphic code without any relationship between two classes. - Dynamic Polymorphism → Overriding - Static Polymorphism → Overloading

Why break statement is used in switch case?

It is used to jump out of switch statement when the condition finds matching case.

Is JDK required on each machine to run a Java program?

JDK is Java Development Kit and is required ​only ​for development and JDK ​isn't ​required to run a Java program on a machine. Only JRE is required.

What are the JDK, JRE and JVM?

JDK​ (Java Development Kit) is a software development ​environment​ to develop Java applications. It contains JRE and development tools. It physically exists. JRE​ (Java Runtime Environment) is a set of software ​tools​ which are used for developing Java applications. It is used to provide the runtime environment. It physically exists. It contains a set of libraries that JVM uses at runtime. JVM ​(Java Virtual Machine) is a virtual machine because it doesn't physically exist. It is used to run Java byte code. JRE = JVM + libraries to run Java application. JDK = JRE + tools to develop Java Application.

What is Java String Pool?

Java String pool refers to a collection of Strings which are stored in heap memory. In this, whenever a new object is created, String pool first checks whether the object is already present in the pool or not. If it is present, then the same reference is returned to the variable else new object will be created in the String pool and the respective reference will be returned.

Why Java is not 100% Object-oriented?

Java is not 100% Object-oriented because it makes use of eight primitive data types such as boolean, byte, char, int, float, double, long, short which are not objects.

Can we use a default constructor of a class even if an explicit constructor(​constructor with parameters​) is defined?

Java provides a default no argument constructor if no explicit constructor is defined in a Java class. But if an explicit constructor has been defined, default constructor can't be invoked and developer can use only those constructors which are defined in the class​.

What are Loops in Java? What are four types of loops?

Looping is used in programming to execute a statement or a block of statements repeatedly. There are four types of loops in Java: 1. ​For Loops: ​For loops are used in java to execute statements repeatedly for a given number of times. For loops are used when number of times to execute the statements is known programmer. 2. ​While Loops: ​While loop is used when certain statements need to be executed repeatedly until a condition is fulfilled. In while loops, condition is checked first before execution of statements. 3. ​Do While Loops: ​Do While Loop is same as While loop with only difference that condition is checked after execution of block of statements. Hence in case of do while loop, statements are executed at least once. 4.​ For Each Loops:​ For Each loops are used to loop through arrays and lists.

What is nested if statement in java?

Nested If statement means there is another if statement inside an if statement. It first check ​outer​ if condition, if outer if condition is true then it checks inner if condition. ​ Both : - inner and outer conditions must be true, for inner statements to get executed.

What is nested loop and where do we use it?

Nested loops means we use one loop in another loop. The first loop is called outer loop, and the loop that is inside of the first loop is called inner loop. For example: We can use nested loop to get all the element of multidimensional arrays.

Can we have any other return type than void for main method?

No, Java class main method can have only ​void ​return type for the program to get successfully executed.

Can a class extends more than one class in Java?

No, a class can only extend just one more class in Java. By default, every class extends the java.lang.Object class in Java. That's why Object class considered super class of all classes.

Can we override a non-static method as static in Java?

No, it's not possible to define a non-static method of same name as a static method in the parent class, its compile time error in Java.

Can you pass the negative number in Array size?

No, we can ​not ​pass the negative number as Array size. If you pass a negative number in Array size then you will not get the compiler error. Instead, you will get the NegativeArraySizeException at run time.

Can we change argument list of overridden method?

No, you cannot change the argument list of overridden method in Java. An overriding method must have same signature as original method. If we change the list of arguments it's called overloading.

Can we override constructor in Java?

No, you cannot override constructor in Java because they are not inherited. Remember, we are talking about overriding here not overloading, you can overload construct but you cannot override them. Overriding always happens at child class and since constructor are not inherited and their name is always the same as the class name its not possible to override them in Java.

What are the rules of method overriding in Java?

Some rules of method overriding are following: - Overriding ​method cannot throw higher exception than overridden one, but that's only true for checked exception. - Overriding ​method cannot restrict access of overridden method e.g. if original method is public then overriding method must be public. But it can expand access e.g. if original method is protected than overriding method can be protected or public.

Differentiate between static and non-static methods in Java.

Static Method: 1.The static keyword must be used before the method name 2. It is called using the class (className.methodName) 3. They can't access any non-static instance variables or methods. Non-static Method: 1.No need to use the static keyword before the method name 2. It is can be called like any general method 3. It can access any static method and any static variable without creating an instance of the class

Explain the details of following Java method: public static void main(String[] args){ }

The following shows the explanation individually: public − it is the access modifier. static − it allows main to be called without instantiating a particular instance of a class. void − it is return type and means no value is returned by main. main − this method is called at the beginning of a Java program. String args[ ] − args parameter is an instance array of class String

What is the purpose of default constructor?

The java compiler creates a default constructor only if there is no constructor in the class. Default constructor does not have any parameters. If we add any custom constructor to that class we need to write default constructor​ ​as well.

What is the primary benefit of Encapsulation?

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this Encapsulation gives maintainability, flexibility and extensibility to our code. We mark variables private to keep them secure and by using getter and setter methods we assign and get value of variables

In Java, is Constructor overriding possible?

This is the most popular Java Inheritance Interview Questions asked in an interview. In Java, Constructor overriding is not possible as the constructors are not inherited as overriding is always happens on child class or subclass but constructor name is same as a class name so constructor overriding is not possible but constructor overloading is possible.

Can a class have multiple constructors for the same class?

Yes, a class can have multiple constructors with different parameters. Which constructor gets used for object creation depends on the arguments passed while creating the objects.

Can we have a constructor and a method with the same name in a class?

Yes, we can have both in a class with the same name because constructor and method are two different things. Constructors ​do not​ have return type but methods have

Can We Overload A Static Method In Java?

Yes, you can overload a static method in Java. Overloading has nothing to do with runtime but the signature of each method must be different. In Java, to change the method signature, you must change either number of arguments, type of arguments or order of arguments.

Can we pass an object of a subclass to a method expecting an object of the super class?

Yes, you can pass that because subclass and superclass are related to each other by Inheritance which provides IS-A property. I mean Banana is a Fruit so you can pass banana if somebody expect fruit.

Can you override a private or static method in Java?

You cannot override a private or static method in Java. If you create a similar method with the same return type and same method arguments in child class then it will hide the superclass method; this is known as method hiding. Similarly, you cannot override a private method in subclass because it's not accessible there. What you can do is create another private method with the same name in the child class. Let's take a look at the example below to understand it better​.

Why Java is platform independent?

​Java is platform independent because of its byte codes. Once Java code get compiled it is converted to byte code which can be executed in any platform (Windows, Linux, Mac OS). Note: That platform should have JVM to execute bytecode

What is the difference of final vs finalize vs finally ?

​final ​→ is a keyword and used to apply restrictions on class, method and variable. ● final Class CAN'T be Inherited ● final Method CAN'T be Overridden ● final Variable value CAN'T be changed. It is constant. finally ​→ is a block and used to place important code, it will be executed whether exception handled or not finalize() ​→ is a method and used to perform clean-up processing before Object is Garbage collected.


Set pelajaran terkait

MA ch 23 vital signs and measurements

View Set

10.10 Lecture 11 - The Digestive System

View Set

Chapter 8 - Plan Quality Management

View Set

Chapter 14: Functional Diversity of Bacteria

View Set

Mgt 423 Ch 04: Video Case - Organizational Justice and Ethics

View Set