Java Interview Questions Flashcards

(58 cards)

1
Q

What is the difference between Declaration and Definition in Java?

A
Declaration: If you just declare a class or method/function or variable without
mentioning anything about what that class or method/function or variable looks like is
called as declaration in Java.
Definition: If you define how a class or method/function or variable is implemented then
it is called definition in Java.

When we create an interface or abstract class, we simply declare a method/function but
not define it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a Class in Java?

A
A class can be defined as a collection of objects. It is the blueprint or template that
describes the state and behavior of an object.
1 public class MyClass{ //Class name (MyClass) 
declaration
2int a = 9; // Variable declaration
3int b = 99;
4public void myMethod(){ //Method (myMethod) declaration
5int sum=a+b;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is an Object in Java?

A

An object is an instance of a class. Objects have state (variables) and behavior
(methods).
Example: A dog is an object of Animal class. The dog has its states such as color,
name, breed, and behaviors such as barking, eating, wagging her tail.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Differences between object and class ?

A
Classes and objects are separate but related concepts. Every object belongs to a class
and every class contains one or more related objects.
A Class member is static. All of the attributes of a class are fixed before, during, and
after the execution of a program. The attributes of a class can change.
The class to which an object belongs is also (usually) static. If a particular object
belongs to a certain class at the time that it is created then it almost certainly will still
belong to that class right up until the time that it is destroyed.
An Object on the other hand has a limited lifespan. Objects are created and eventually
destroyed. Also during that lifetime, the attributes of the object may undergo significant
change.
//Murodil Answer:
Class:
- Is a template/blueprint for objects
- We can define properties and methods in it
- Class is an idea
Object;
- is always created from a class
- Cannot exist without a class
- Using objects we can use class’s methods and variables
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What’s the difference between primitives and objects?

A

Primitives:

  • Build into Java and foundation of all other types
  • Have a single value and no behaviour
  • int j=25; j=j+10; print j; j>5 etc; char ch = ‘q’;

Objects:

  • Is created from a class
  • Can have multiple values/properties and can have behaviour(methods)
  • str.trim; str.toUpperCase;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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

A

== -> is a reference comparison, i.e. both objects point to the same memory
location
.equals() -> evaluates to the comparison of values in the objects

1- Main difference between .equals() method and == operator is that one is method and
other is operator.
2- We can use == operators for reference comparison (address comparison) and
.equals() method for content comparison. In simple words, == checks if both objects
point to the same memory location whereas .equals() evaluates to the comparison of
values in the objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the difference continue and break statement?

A

Break leaves a loop, continue jumps to the next iteration.

break to terminate a for, while, or do-while loop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the 5 different types of operators?

A
Arithmetic Operator, +,-,%,/,*
Relational Operator, >=, <=
Logical Operator, && , ||
Ternary Operator and. Result = testStatement ? value1 : value2
Assignment Operator int n = 3;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is constructor and purpose of default constructor?

A

A constructor that have no parameter is known as default constructor.
Default constructor provides the default values to the object like 0, null etc. depending
on the type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Explain public static void main(String args[]). (PSVM)

A

● public : Public is an access modifier, which is used to specify who can access
this method. Public means that this Method will be accessible by any Class.
● static : It is a keyword in java which identifies it is class based i.e it can be
accessed without creating the instance of a Class.
● void : It is the return type of the method. Void defines the method which will not
return any value.

● main: It is the name of the method which is searched by JVM as a starting point
for an application with a particular signature only. It is the method where the main
execution occurs.
● String args[] : It is the parameter passed to the main method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Difference between static class ,static method and static block ?

A
Static Class
● A Class can be made static only if it is a nested Class. The nested static class
can be accessed without having an object of outer class.
Static Block
● Static block is mostly used for changing the default values of static variables.This
block gets executed when the class is loaded in the memory.
● A class can have multiple Static blocks, which will execute in the same sequence
in which they have been written into the program.
Static Methods
● Static Methods can access class variables without using object of the class. It
can access non-static methods and non-static variables by using objects. Static
methods can be accessed directly in static and non-static methods.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the purpose of toString() method?

A

It’s used to retrieve the object information in String format. This method called by
Sysout.println internally. By default toString() returns the hashcode from the Object
class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is OVERLOADING Method?

A

Definition 1: Best Answer: Must have Same Name , Must have Different parameters

Definition 2: Overloading allows different methods to have same name, but different
signatures where signature can differ by number of input parameters or type of input
parameters or both.

Definition 3: There are three ways to overload a method.
● Parameters with different data types
● Parameters with different sequence of a data types
● Different number of parameters

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is Method Signature?

A

In the ​Java​ programming language, a ​method signature​ is the ​method​ name and the
number, type and order of its parameters.
Consist of: method name, number of parameters and their types:
Public static void m1(int n, String str) {}
Above m1 method signature:
2 parameters -> 1 int, 1 string

*Return type, or other modifiers are not part of method signature

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is Java Collection?

A

Collection is a framework in java to store objects and manipulate them.
Two main “root” interfaces of Java Collection classes
The Collection Interface (java.util.Collection)
Map Interface (java.util.Map)
Not: ArrayList is part of Java Collections, that is one of the most popular q’s.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is Array And ArrayList?

A

Array:
- Array is a container object that holds a fixed number of values of a single data
type.
ArrayList:
- Dynamic array, internally it is build on Arrays.
- Part of java collections, and one of the most popular collection in use.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Difference Array and Arraylist?

A

*Array is part of core java programing and has special syntax but arraylist is part of
collection framework and implement list interface

  • Arrays are fixed size and size cannot be changed:
    int[] arr = new int[5];
    The arr size/length cannot be modified, it is fixed.
  • Arrays can accept both primitives and Objects.
    double[] d = {23.54, 23.1};
    String[] s = {“One”, “Five”};
  • Arrays can be multi dimensional
    String[][][] data = new String [5][3][2];
    String[][] matrix = new String [5][3];
  • Arrays are built into core Java
  • ArrayLists are resizable and size of elements can be modified. It can increase and
    decrease.
    ArrayList nums = new ArrayList<>();
    nums.add(200);
    nums.add(43); // keep adding. Size will increase
    nums.remove(0); // remove to decrease the size
  • ArrayList can only accept Objects. We will need to use Wrapper classes to add
    primitive types.
    ArrayList nums = new ArrayList<>();
    ArrayList strs = new ArrayList<>();
  • ArrayList cannot be multi dimensional.
  • ArrayList is a part of Collection framework and it is a type of List interface.
    Array data structure is fixed;
    Arraylist is dynamic
    Array Arraylist
    Resizable No Yes
    Primitives Yes No
    Iterating values for, for each Iterator , for each

Length length variable size method
Performance Fast Slow in comparison
Multidimensional Yes No
Add Elements Assignment operator add method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is Iterator and difference between for each loop?

A
  • Iterator works with arrayList and not array. It will help us Iterate through the elements.
  • Difference is with iterator you can make changes(remove item) to the list while
    iterating. within for each loop we can not make changes to our list
    Iterator it = list.iterator();
    while(it.hasNext()) {
    Integer n = it.next();
    System.out.println(n);
    it.remove();
    }
    System.out.println(list);
    System.out.println(“================”);
    for(Integer n : list) {
    System.out.println(n);
    //list.remove(n);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is Wrapper Classes ? Why we need wrapper classes?

A

1.To cover primitive to an object. Use some methods from it.
2.Since most data structures in Java do not support primitive types, We need
Wrapper classes instead of
Integer.parseInt() vs Integer.valueOf();

Wrapper classes:
Byte, Short, Integer, Long, Float, Double, Boolean, Character
*String is not wrapper class
Wrapper classes for primitives
How many primitive ? 8
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Can one class call another class in main method?

A
  • yes a main method can be called in another class main method
  • we can call from different package, as long as we know the method name and we
  • have to import it.
  • code will compile without main method but will not run
    -For ex: calculator is class, add is method
    (Calculator.add(1234, 400);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Implicit casting vs explicit casting?

A
- Implicit Casting: (big => small)
int i = 100;
double d = i;
- Explicit Casting: (small=> big)
int n = 12;
byte b = (byte)n;
- Auto - Boxing
Integer num = n;
- Un - Boxing
int j = Integer.valueOf(num);
DON’T WORK:
Integer i = new Integer(100);
double d = i ; // will not work
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is Thread-safe or Synchronized?

A

-StringBuffer is thread safe, so it is slower
-StringBuilder is not thread safe, so it is faster
-Both are mutable versions for Strings
-Thread unsafe all four people can go to pizza and pickup the slice at the exact same
time.
-Thread safe first person takes the slice while 2nd is waiting

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

what is thread:

A

A sequential or single threaded program has single flow

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

synchronized:

A

Means that two threads can not execute the method or access the
variables at the same time and the JVM takes care of enforcing that. it is used to
achieve thread-safety

25
StringBuilder vs StringBuffer.
StringBuilder. Strings are immutable There is only one StringBuilder object in the memory. Thread safe => first person takes the slice while 2nd is waiting. Thread Unsafe => all four ppl can go to pizza and pickup the slice at the exact same time. StringBuffer is Thread safe since only one thread can access StringBuffer at one point of time hence make application little slow. Used in scenarios where we have shared resource among multiple threads in java. make application little slow
26
What is String pool?
- String Pool in java is a pool of Strings stored in Java Heap Memory. Used to save space in memory.
27
What is append () method does in BufferedWriter? And The other Methods in BufferedWriter?
``` Concatenates the string to the end of the invoking StringBuffer object StringBuilder Methods; //append (String or primitive) //delete (index, position) //reverse () //insert (index, String) //replace (index, position, String) ```
28
What are the difference between Buffer and Builder?
Both are mutable versions for Strings StringBuffer is thread safe, so it is slower StringBuilder is not thread safe, so it is faster Thread unsafe means; it happens at the same time Thread safe means; Sequentially
29
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. Java is mainly object oriented programming language because without class and object it is impossible to write any Java program. ```
30
Name some OOPS Concepts in Java?
Java is based on Object Oriented Programming Concepts, following are some of the OOPS concepts implemented in java programming. ● Abstraction ● Encapsulation ● Polymorphism ● Inheritance https://docs.oracle.com/en/database/oracle/oracle-database/12.2/jjdev/Java-overview.html#GUID-17B81887-C338-4489-924D-FDDF2468DEA7
31
What is Constructor ?
``` //Is a special method that runs automatically when object from a class is created. //Every object will call this special method //It is normally public, no return type, and name is exact same as class name //We can have multiple constructors in same class and this is called constructor overloading ``` ``` - A constructor in java is a block of code similar to a method that s called when an instance of an object is created. Difference between constructor and method: - A constructor doesn’t have a return type - the name of the constructor must be the same as the name of the class - unlike methods constructors are not considered members of a class - a constructor is called automatically when a new instance of object is created - the purpose of a constructor is to initialize the object of a class while the purpose of a method is to perform a task by executing java code - default constructor is added if programmer did not add a constructor. Types of Java Constructor ; 1 default constructor 2 parameterized constructor ```
32
Difference between static and instance variable?
``` An instance variable is a variable that is a member of an instance of a class, whereas a class(static) variable is a member of the class itself. Every instance of a class will have its own copy of an instance variable, whereas there is only 1 of each static (or class) variable, associated with the class itself. ```
33
What is encapsulation ?
Hiding Class data by making variables PRIVATE. When an instance variable is private, it cannot be accessed from other classes. We provide access to private variables by adding public GETTER AND SETTER methods into our class. Accessor (getter) and mutators (setter) method : it means getter and setter Encapsulation is hiding(binding) the data and behaviors together in a single unit. ● Declaring the variables of a class as private. ● Providing public setter and getter methods to modify and view the variables values. ``` public class Employee { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public static void main(String[] args) { } } - 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 setter. The main benefit of encapsulation is the ability to modify the implemented code without breaking the code of others who use our code. It also provides us with maintainability, flexibility and extensibility to our code
34
What is Inheritance ?
Inheritance is a process when a sub class inherits members from super class. We have two classes namely Parent Class and Child Class. Child class is also known as Derived Class. As per the above definition, the Child class inherits the properties of the Parent Class. The main purpose of Inheritance is to obtain Code Reusability. We can achieve runtime polymorphism with inheritance. All public and protected and sometimes default members are inherited to sub class. - we will achieve code re-usability and code organization with it. also very useful for polymorphic programing. - test base is super class and other test classes are sub classes.
35
``` What is the difference between access modifiers in java? What will be inherited from a super class to sub class? What will not be inherited from a parent class to child class? ```
``` Answers are depends on access modifier: public accessible to world(all classes,subclasses in same package or different package) => all public variables and methods are always inherited. No matter the package protected accessible to classes in same package and ONLY sub-classes in different packages => all protected members(variables, methods) from superclass are always inherited to subclass ``` default (empty) => accessible to ONLY to classes and child classes in SAME PACKAGE => default members will only be inherited if both PARENT and CHILD classes are in same exact package private => accessible to the SAME class ONLY. => private members will not be inherited.
36
What is inheritance and benefits of it?
- inheritance is a process when a subclass inherits members from super class. All public and protected and sometimes default members are inherited to subclass. - we will achieve code reusability and code organization with it. Also very useful for polymorphic programing. - test base is super class and other test classes are subclasses. EX: we had a page object for one page and as another page contained same elements i used inheritance in order to reuse the elements defined in super page object class in selenium webdriver. reusability is one of the best opportunities of inheritance in terms of many line codes. extends is a keyword of passing inheritance from parent class to child class
37
What is Abstraction in Java and Purpose?
- in General using abstraction in programing we can create a base/ blueprint for our code and let subclasses implement as needed according to requirements hiding the implementation and showing only behavior abstract class can have a constructor 2 ways to achieve abstraction in JAVA: 1) Abstract Classes 2) Interfaces
38
Advantages of Abstraction
1.It reduces the complexity of viewing the things. 2.Avoids code duplication and increases reusability. 3.Helps to increase security of an application or program as only important details are provided to the user.
39
Difference between Abstract class and interface?
- difference between abstract class and interface in java - types of methods: interface can have only abstract methods. Abstract class can have abstract and non abstract methods. from java 8 it can have default and static methods also. - final variables: variables declared in java interface are by default final. an abstract class may contain non final variables - a class can implement multiple interfaces, but it can extend only Single abstract class. java does not support multiple inheritance - methods - in interface: abstract static defaults, - in abstract class: abstract non-abstract static - abstract class can have a constructor interface can not have a constructor - interface can extend other interfaces(multiple)
40
What is polymorphism?
Polymorphism allows us to perform a task in multiple ways. Let’s break the word Polymorphism and see it, ‘Poly’ means ‘Many’ and ‘Morphos’ means ‘Shapes’. Assume we have four students and we asked them to draw a shape. All the four may draw different shapes like Circle, Triangle, and Rectangle. There are two types of Polymorphism in Java 1. Compile time polymorphism (Static binding) – Method overloading 2. Runtime polymorphism (Dynamic binding) – Method overriding For more detail; https://www.softwaretestingmaterial.com/polymorphism-in-java/
41
Why is the Java main method static?
It is because the object is not required to call a static method. If it were a non-static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation.
42
When we need to "static" keyword?
1. If we need to create a constant in our program, then we declare that variable as static variable. * 2. If we want to initialize any object during the startup of the application then we can declare that object as static, because java/JVM by default * initialize any static variable at startup.
43
Why need static?
1. If we need to create a constant in our program, then we declare that variable as static variable. 2. Save memory because only one copy of a static variable is created for class, no matter how many objects we crate.
44
What is Method Overriding?
``` Declaring a method in child class which is already present in the parent class is called Method Overriding. In simple words, overriding means to override the functionality of an existing method. In this case, if we call the method with child class object, then the child class method is called. To call the parent class method we have to use super keyword. ```
45
What do you mean by platform independence of Java?
Platform independence means that you can run the same Java Program in any Operating System. For example, you can write java program in Windows and run it in Mac OS.
46
What is JVM and is it platform independent?
Java Virtual Machine (JVM) is the heart of java programming language. JVM is responsible for converting byte code into machine readable code. JVM is not platform independent, thats why you have different JVM for different operating systems. We can customize JVM with Java Options, such as allocating minimum and maximum memory to JVM. It’s called virtual because it provides an interface that doesn’t depend on the underlying OS.
47
What is the difference between JDK and JVM?
Java Development Kit (JDK) is for development purpose and JVM is a part of it to execute the java programs. JDK provides all the tools, executables and binaries required to compile, debug and execute a Java Program. The execution part is handled by JVM to provide machine independence.
48
What is the difference between JVM and JRE?
Java Runtime Environment (JRE) is the implementation of JVM. JRE consists of JVM and java binaries and other classes to execute any program successfully. JRE doesn’t contain any development tools like java compiler, debugger etc. If you want to execute any java program, you should have JRE installed.
49
Mention some features of Java?
Some of the features which play important role in the popularity of java are as follows: ● Simple: Java is easy to learn. Even Though Java is based on C++ , it was developed by eliminating poor programming practices of C++. ● Object-Oriented: Java is a object oriented programming language. Everything in Java is an Object. ● Portable: Java runtime environment uses a bytecode verification process to make sure that code loaded over the network doesn’t violate Java security constraints. ● Platform independent: Java is platform independent. Java is a write once, run anywhere language. Without any modifications, we can use a program in different platforms. ● Secured: Java is well known for its security. It delivers virus free systems. ● High Performance: Java enables high performance with the use of JIT (Just-In-Time) compilers ● Multithreaded: Java Multithreaded features allows us to write programs that can perform many tasks simultaneously. Multithreading concept of Java shares a common memory area. It doesn’t occupy memory for each thread.
50
Difference between Path and classPath?
- Path: is used to define where the executables are .exe files java.exe, javac.exe etc - Class path: is used to specify location of Java.class files - java source code -> compile (javac) -> bytecode .class extension
51
Can a super() and this() keywords be in same constructor?
- public computer(){ this(); super(); //code } - NO they both need to be in first line within constructor. Super. VS Super() - super. is used to access parent/super class members vars, methods - super() is used to call super class constructor * this. VS this() - this. this object by using this. we can access instance variables and method. to differentiate between instance and argument variable - this() call a constructor from another constructor in same class
52
What is static keyword in java?
``` - Static keyword means that the variable or method belongs to class and shared between all instances. - we can call static members by using class name or object - static methods can not call/refer Non Static members - Static can be: variables, method, block, inner class ```
53
Static block and instance initializer block?
``` - the static initializer block will be called on loading of the class and code will run only once in the begining - instance initializer block execute every time you create an object for a class. before any constructor. ```
54
Pass by value or pass by reference?
- Java is a “pass-by-value” language. This means that a copy of the variable is made and the method receives that copy. Assignments made in the method do not affect the caller.
55
final vs finally vs finalize()
- Final: - final is a keyword ``` - final is used to apply restriction on class method and variable - if a class is marked as final then this class can not be inherited by any other class ``` - finally: - finally is a block - finally is a block which is used for exception handling along with try and catch blocks - ``` Finalize: - finalize() method is protected method of java.lang.object class it is inherited to every class you create in java - finalize() methods id used to perform some clean up operations on a object before it is removed from memory ```
56
Difference between overloading and overriding?
Overloading allows different methods to have same name, but different signatures where signature can differ by number of input parameters or type of input parameters or both. Overloading is related to compile time (or static) polymorphism. 1: overloading = same method name but different parameters overloading = return type can be different 2: overriding = same type or sub type overriding = same method name and same parameters
57
Can you override a static method?
No static methods cannot be overridden, they can only be hidden.
58
What is static binding vs dynamic/runtime binding?
- Static binding is overloading and - dynamic binding is method overriding.