Core Java Flashcards

1
Q

The wrapper classes

A

The wrapper classes are predefined classes in Java
used to wrap the primitive data types to introduce them as objects and vice versa

Byte, Short, Integer, Long, Character, Boolean, Float, Double

Data Structures in a collection framework can store only objects and not primitive data types

The primitive values are not objects and the developer needs to write many boilerplate codes to convert them to each other and using them in collections

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

What is polymorphism

A

The ability for some code structure in an OOP language to treated different structures at runtime

Polymorphism
Overloading is a part of compile time polymorphism
Overriding is a part of run time polymorphism.

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

ways we can create an object in java.

A
1- created using the new operator on the class calling one of  its constructors. 
MyClass o = new MyClass(); 

2- We can invoke clone method on an object to create a duplicate object.
MyClass o = new MyClass();
MyClass b = (MyClass)o.clone();

3- We can create an object using the Java reflection API - Class.newInstance() if the class has a default constructor.
 MyClass o = MyClass.class.newInstance();
 If the class has multiple constructors that take parameters, we can get the corresponding constructor using Class.getConstructor() method and invoke that to create a new object. 
MyClass o = MyClass.class.newInstance(); 
MyClass o = MyClass.class 
MyClass o = MyClass.class.newInstance(); 
MyClass o = MyClass.class.getConstructor(int.class) .newInstance(10);  
4-If a state of that object is available in a serialized form, we can deserialize it to create a new object having the same state. 
ObjectInputStream is = new ObjectInputStream(anIStream); MyClass o = (MyClass) is.readObject();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Static binding or compilation time polymorphism (overloading)
Dynamic binding or runtime polymorphism (overriding)

A
Static polymorphism --time of compilation
static polymorphism is achieved through method overloading
static polymorphism decides which method needs to be invoked at the time of compilation and bind the method invocation with the call.
// First addition function
    public static int add(int a, int b) {  return a + b};
    // Second addition function
    public static double add (double a, double b) { return a + b; }
    // Driver code
    public static void main(String args[])
    {
        // Here, the first addition
        // function is called
        System.out.println(add(2, 3));
    // Here, the second addition
    // function is called
    System.out.println(add(2.0, 3.0));
} } -------------------------------------------------------------- Dynamic binding or runtime polymorphism Dynamic polymorphism is achieved through method overriding As we know, a parent class reference can point to a parent object as well as a child object.  Now, if there is a method which exists in both the parent class and override on the child class  so if we invoke the method from parent class reference, the compiler cannot decide which method to bind with the call.
If the reference is pointing to a parent object, then the method in the parent class will be invoked. parent p = new parent()
If the pointed object is an instance of the Child class, then the child-class implementation is invoked. parent p = new child()  // up casting
// object of type parent
        Parent a = new Parent();
        // object of type Child
        Child c = new Child();
        // obtain a reference of type Parent
        Parent ref;    // null
        // ref refers to an Parent object
        ref = a;
        // calling Parent's version of m1()
        ref.m1();
        // now ref refers to a Child object
        ref = c;   //up casting
        // calling Child's version of m1()
        ref.m1();

(i.e)
In Java, we can override methods only, not the variables(data members), so runtime polymorphism cannot be achieved by data members.

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

StringBuffer and StringBuilder

A

StringBuffer is thread-safe which means it can be used as a shared object among multiple threads.

On the other hand,

StringBuilder is not thread-safe and should not be allowed to be modified by multiple threads without proper synchronization techniques.

That’s why StringBuilder is faster than StringBuffer

we prefer StringBuilder over StringBuffer when we need to build a String object local to a method or local to a particular thread,

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

Checked Exception vs Unchecked Exception

A

The exceptions which are checked during compile time are called checked exceptions.

When method throws checked exceptions, they must either be handled by the try-catch block or must declare the exception using the throws keyword. In case of violation, it will show a compile time error. It is a subclass of Exception class

Unchecked exceptions are the exceptions that are not checked during compile time.
as (NullPointerException)
If the code throws an unchecked exception and even if it is not handled, it will not generate a compile time error. 
This is dangerous as unchecked exceptions generally generate runtime errors. 
It is the subclass of RuntimeException class

Finally
A checked exception must be handled either by re-throwing or with a try catch block, a runtime isn’t required to be handled. An unchecked exception is a programming error and are fatal, whereas a checked exception is an exception condition within your codes logic and can be recovered or retried from.

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

When we use abstract and Interface

A

Since the abstract class has concrete methods and abstract methods so if you have any requirements where a few sets of the functionalities common across all the subclasses and a few functionalities vary from subclasses

We use abstract class when the different implementations have 
most of the behaviors common and defined by the abstract class. 
So, abstract classes can be used to combine and share functionality,
An interface is preferred while exposing a public API to the client code and
 if a class can behave differently in different context. and if we don't have to inherrit default behavior
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

what do you understand by a Static member(variable)

A

Static methods and fields are shared between all the objects of a class and can be accessed from any of them

We declare a member(variable) as static if it doesn’t depend on any instance of the class, 
Static fields are initialized through a static block which is executed when a class is loaded by the class loader
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

ArrayList and LinkedList

A

ArrayList and LinkedList both represent a list of numbers
but differ in their internal implementation.

ArrayList
It gives constant time access to add and get an element,
but for deletion, it gives linear time complexity
as it needs to shift its elements to the left

LinkedList
It gives constant time access to add and delete an element,
but for get an element in linear time
use linked nodes internally for storing the elements.

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

HashMap and Hashtable

A

HashMap and Hashtable

  • both store key-value pairs
  • HashMap is fast than Hashtable

HashMap

  • is non synchronized. It is not-thread safe and can’t be shared between many threads without proper synchronization code.
  • allows one Null key and multiple Null values.
  • Multiple threads can operate

HashTable

  • is synchronized. It is thread-safe and can be shared with many threads.
  • doesn’t allow Null keys or values
  • At a time only one thread is allowed to operate
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

public static void main(String args[])

A

It is the entry point of any Java Program
public: This is the access specifier/access modifier of the main method.
static: At the start of the runtime, the class is devoid of any object .
the main method needs to be static so that the Java Virtual Machine can set the class to the memory and call the main method.
void: It is the return type of the main method.
main: It is the name of the main method.
String args[] : The main method can accept a single argument which is of the String type.

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

Local Variable and Instance Variables

A

Local Variable is a variable declared in a method body or a constructor or a block
The scope of the local variables starts from its declaration and ends when the block or method body or the constructor ends

Instance Variables Each object can create its own copy of the instance variable and access it separately.
The scope of the instance variable is created and destroyed when the objects are created and destroyed respectively.

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

differences between abstract classes and interfaces

A

Abstract class and Interface both are used for abstraction which is hiding the background details and representing only the essential features. But there are major differences between abstract classes and interfaces.

Abstract
Can have instance variables of any kind
Can have any visibility: public, private or protected
Can have both abstract as well as non-abstract methods
Can have constructors
Can be extended by using keywords ‘extends’
A Java class can extend only one abstract class
Can provide complete code

Interfaces
Cannot have instance variables
variable must be( public static final)
Have either public visibility or no visibility
Only have abstract methods
Cannot have constructors
Can be implemented by using keyword ‘implements’
A Java class can implement multiple interfaces
Just provide the signature/prototype

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

Overloading and Overriding

A
In Method Overloading, 
the names of the methods in the same class are same but the arguments (type and/or number) are different.

In Method Overriding,
the names and arguments of the methods are same
but one of the methods is in the super class while the other is in the sub class.

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

Usage of Final keyword in Java

A

The final keyword is a non-access modifier in Java.
It can only be applied to a variable, method or a class. which makes them non-changeable

Class that are final cannot be extended.

Methods that are final cannot be used for method overriding in child class.

The final variables have constant value which are not changeable throughout the program.
This means they need to be initialized along with their declaration, otherwise they would be blank final variables, which can be later initialized only once.
If a final variable is used as a reference to an object, it cannot be used as a reference to another object.

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

Thread Life Cycle in Java

A

The 5 states in a thread life cycle are:

New
When an instance of the thread class has been created but the start() method is not invoked, then the thread is in the new state.

Runnable
When the start() method has been invoked but the thread scheduler has not selected the thread for execution, then the thread is in the runnable state.

Running
If the thread scheduler has selected a thread and it is currently running, then it is in the running state.

Blocked (Non-runnable)
When a thread is not eligible to run but still alive, then it is in the blocked state.

Terminated (destroy)
When the run() method of a thread exits, then it is in the terminated state.

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

Java equals() method vs == operator

A

The equals() method and the == operator in Java are both used to find if two objects are equal.
equals() is a method,
== is an operator.

Also, equals() compares the object values
while == checks if the objects point to the same memory location.

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

What does “static” mean in public static void main(String args[])?

A

The static keyword acts as an access modifier. When the Java Virtual Machine calls out to the main method, it has no object to call to. Hence, we use static to permit its call from the class.

If we do not use static in public static void main(String args[]), then the compiler will give an error message.

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

Access Modifiers in Java

A

helps to restrict the scope of a class, constructor, variable, method, or data member. There are four types of access modifiers available in java:

Default – No keyword required
Private
Protected
Public

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

What type of parameter passing does Java support?

A

Pass by value
it means that when a method is called, a copy of the parameters is sent to the memory

When we are using the parameters inside the method or the block, the actual arguments aren’t used but the copy of those arguments (formal parameters) are worked with. There is no change in the actual parameters.
In Java, arguments are always passed by value irrespective of their original variable type. Each time a method is called, a copy is created in the stack memory and its version is passed to the method.

Pass by reference
it means that the changes in the parameters will be reflected in the original value .

This occurs because the method receives the memory address of the parameters.

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

How to make a class Singleton

A
Singleton class is a class which has only a single object. 
This means you can instantiate the class only once.
When we declare the constructor of the class as private, it will limit the scope of the creation of the object
If we return an instance of the object to a static method, we can handle the object creation inside the class itself.
 private static Example obj;
   static
   {
       obj = new Example(); // creation of object in a static block
   }
   private Example() { }   // declaring the constructor as private
   public static Example getObject()
   {
       return obj;     
   }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Lambda Expression

A

A lambda expression is an instance of a functional interface
Used to override a function interface

The most important feature of Lambda Expressions is that
they execute in the context of their appearance

minimize coupling (minimize relation between classes) and 
increase cohesion  (increase the relation between methods and properties in class )

Lambda is an anonymous and passed (mostly) to other functions as parameters

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

Comparable interface

It is inside the same class

A

A comparable interface is used to order the objects of the user-defined class.

contains only one method named compareTo (Object)

public int compareTo(Student st)

It provides a single sorting sequence only,
you can sort the elements on the basis of a single data member only

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

Java Generic (parameterized types)

A
Enable programmers to specify, with a single method declaration, a set of related methods, or
 Enable programmers to specify, with a single class declaration, a set of related types, respectively.

Generics are mostly used by collection like HashSet or HashMap.

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

Advantages of using generics

A

1- Java Generics helps the programmer to reuse the code for whatever type he/she wishes.
2 - Individual typecasting isn’t required. The programmer defines the initial type and then lets the code do its job.

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

Annotations

A

Is a form of syntactic metadata that can be added to Java code.
Classes, interfaces, methods, variables, parameters and Java packages may be annotated.
annotation can have elements like an attribute or parameter
@Entity(tableName = “vehicles”, primaryKey = “id”)

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

Threads

A

Threads allows a program to do multiple complicated tasks at the same time at the background
without interrupting the main program uesing the same program memory
2 ways to do the Threads
1 - by Extends Thread class –> run method
2 - by Inplement Runnable interface –>run method
————————————————————-
.start(); to actually begin thread execution after instantiation
.sleep();
.yeild()
.joine(); to wait for the thread to finish execution
.getId();
.setName();
.setPeriority(); from 1 to 10 —> 5, default
.currentThread();
interrupt(); to explicitly interrupt the thread
isAlive(); , is Interrupted, isDaemon() to test the state of the thread

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

JUnit

A

JUnit 5 is most widely used testing framework for java applications
JUnit Jupiter
It includes new programming and extension models for writing tests.
It has all new junit annotations and TestEngine implementation to run tests written with these annotations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q
Comparator interface
It is outside the class in another class
A

It is used to order the objects of a user-defined class.
This interface is found in java.util package and contains 2 methods
compare(Object obj1,Object obj2) and equals(Object element).
It provides multiple sorting sequences
from another class Implements Comparator
public class ComparStusent implements Comparator

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

Serialization and Deserialization

A

Is a mechanism of writing the state of an object into a byte-stream.
It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization
where byte-stream is converted into an object.
The serialization and deserialization process is platform-independent,
it means you can serialize an object on one platform and deserialize it on a different platform.

For Serializing is writing the state of an object into a byte-stream.
Write to file.txt
1- FileOutputStream fss = new FileOutputStream(“MyBook.txt”);
2- ObjectOutputStream ooss = new ObjectOutputStream(inpt);
3- ooss.writeObject(serial);
4- ooss.close();

For Deserialization is writing the state of a byte-stream into an object
Read from file.txt
1- FileInputStream fiss = new FileInputStream(“MyBook.txt”);
2- ObjectInputStream oiss = new ObjectInputStream(oupt);
3- Serialization seriall = (Serialization) oiss.readObject();
4- oiss.close();

i.e - We must have to implement the Serializable interface for serializing the object.

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

Logging API

A

is an API that provides the ability to trace out the errors of the applications.

When an application generates
1- the logging call,
2- the Logger records the event in the LogRecord.
3- The appenders format that logRecord by using the formatter or layouts.
4- it sends to the corresponding handlers or appenders. (console or file)

Need for Logging
It provides the complete tracing information of the application.
It records the critical failure if any occur in an application.

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

Maven

A

Maven is a powerful project management tool that is based on
POM (project object model).

It is used for projects build, dependency and documentation.

What it does?
It makes a project easy to build
It provides uniform build process (maven project can be shared by all the maven projects)
It provides project information (log document, cross referenced sources, mailing list, dependency list, unit test reports etc.)
It is easy to migrate for new features of Maven

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

File I/O

A
To Write on file
FileWriter inp = new FileWriter("sample.txt");
inp.write(s);
inp.flush();
To read From File
FileReader outp= new FileReader("sample.txt");
char [] data = new char[100];
outp.read(data);
String s = new String(data);
System.out.println(s);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What are the main concepts of OOPs in Java?

A
Inheritance (IS-A):  
is a process where one class can reuse the properties of another class. 
1.	Parent class (Super or Base class)
2.	Child class (Subclass or Derived class

Encapsulation:
is a mechanism of wrapping up the data and code together as a single unit.

Abstraction:
is the process of hiding certain details and showing only essential information to the user.
1. Abstract Classes (0-100% of abstraction can be achieved)
2. Interfaces (100% of abstraction can be achieved)

Polymorphism:
means “many forms”, it occurs when we have many classes that are related to each other by inheritance.
There are two types of polymorphism:
1 Compile time polymorphism (is method overloading ) static binding
2 Run time polymorphism (is using inheritance and interface) dynamic binding

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

What is sealed?

A

Class cannot be inherited

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

What is virtual?

A

Identifier a method in a parent class that can be overidded in a child class

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

What is loop Statement

A

Execute a statement or block of statements repeatedly until a condition is meet

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

What do you mean by an interface in Java?

A

Is a blueprint of a class or it is a collection of abstract methods and static constants.

is a group of related methods with empty bodies each method is public and no constructor

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

What is a constructor overloading in Java?

A

is a technique of adding any number of constructors to a class each having a different parameter list.

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

What is Object Oriented Programming?

A

Braking the normal procedural code into structures called object
so we can creating relationship between these objects

Is a programming model where the programs are organized around objects rather than logic and functions

better use in large and complex codes which easy to updated or maintained.

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

What is an object in Java and how is it created?

A

An object is an instance of a class in memory and is created using the ‘new’ keyword

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

Define a Java Class

A

blueprint contains variables and methods to describe the behavior of an object and use to instantiate object.

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

Differentiate between the constructors and methods in Java?

A

Methods

  1. Used to represent the behavior of an object
  2. Must have a return type
  3. Needs to be invoked explicitly
  4. No default method is provided by the compiler
  5. Method name may or may not be same as class name

Constructors

  1. Used to initialize the state of an object
  2. Do not have any return type
  3. Is invoked implicitly
  4. A default constructor is provided by the compiler if the class has none
  5. Constructor name must always be the same as the class name
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What are constructors in Java?

A

constructor is a block of code which is used to initialize instance variables

There are two types of constructors:

Default Constructor:
- assign the default value to the objects.
- no argument constructors
- created by default in case you no other constructor is defined by the user.
Its main purpose is to initialize the instance variables with the default values

Parameterized Constructor:
constructor which is capable of initializing the instance variables with the provided values
Its main purpose is to initialize the instance variables with the provided values

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

What is the Exceptions?

A

An event that occurs during the execution of a program that damage the normal flow of instructions

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

What is the difference between Error and Exception?

A

Exceptions are conditions that occur because of bad input or human mistake
FileNotFoundException will be thrown if the specified file does not exist. Or
NullPointerException will take place if you try using a null reference

Error is an irrecoverable condition occurring at runtime Such as OutOfMemory error

47
Q

What is composition in Java

A

Composition( Has-A) is a specialized form of Aggregation and we can call it a “death relationship”.

Child object contains parent object so Child object does not have their lifecycle and if parent object deletes all child object will also be deleted.

Example :
A 'Human' class is a composition of Heart and lungs. When the human object dies, nobody parts exist.

In more specific words composition is a way of describing reference between two or more classes using instance variable and an instance should be created before it is used.

48
Q

How can you handle Java exceptions?

A

There are five keywords used to handle exceptions in Java:

  1. try
  2. catch
  3. finally
  4. throw
  5. throws
49
Q

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

A

this –> keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name

super() and this(), both are special keywords that are used to call the constructor.

50
Q

What is Casting class in Java

A

Type casting
Is the process of storing a reference to an object in memory inside a reference variable of a type different than the object it self or the last type of reference variable used

Sometimes you’ll have a value in your Java class that isn’t the right type for what you need. It might be the wrong class or the wrong data type, such as a float when you need an int. In these situations, you can use a process called casting to convert a value from one type to another.

Widening Type Casting
Java automatically converts one data type to another data type.

Narrowing Type Casting
we manually convert one data type into another

Upcasting
Casting from a subclass to a superclass is called upcasting.
Down casting
casting from a superclass to a subclass.
51
Q

What is collection class in Java?

A

collection is a framework that acts as an architecture use for searching, sorting, insertion, manipulation, a group of objects.

Java collection framework includes the following:
• Interfaces
• Classes
• Methods

52
Q

What is Data Structure? Explain.

A

The data structure is a way that specifies how to organize and manipulate the data.
It also defines the relationship between them.

53
Q

Describe the types of Data Structures?

A

Linear Data Structure: == sequential order
called linear if all of its elements are arranged in the sequential order.
In linear data structures, the elements are stored in a non-hierarchical way where each item has the successors and predecessors except the first and last element.

Non-Linear Data Structure: == not on sequential order
does not form a sequence a non-linear arrangement
i.e. each item or element is connected with two or more other items in a non-linear arrangement. The data elements are not arranged in the sequential structure.

54
Q

-. What is the Static method

A

it can be accessed without creating the instance of a Class

It is called using the class (className.methodName)

55
Q

What is the difference between an array and an array list?

A

Array

  • Cannot contain values of different data types
  • Size must be defined at the time of declaration
  • Need to specify the index in order to add data
  • Arrays are not type parameterized
  • Arrays can contain primitive data types as well as objects

ArrayList

  • Can contain values of different data types.
  • Size can be dynamically changed
  • No need to specify the index
  • Arraylists are type parameterized
  • Arraylists can contain only objects, no primitive data types are allowed
56
Q

Autoboxing and Unboxing

A
Autoboxing or in boxing :
 Converting a primitive value into an object of the corresponding wrapper class is called autoboxing.

Unboxing or out boxing :
Converting an object of a wrapper type to its corresponding primitive value is called unboxing.

57
Q

Different ways use polymorphism in java

A

compile-time polymorphism

runtime polymorphism

58
Q

Concept of encapsulation

A

Is how you restrict access to your code by using an access modifier

59
Q

How is a java program executed?

A
60
Q

Serialization in Java

A

Serialization in Java allows us to convert an Object to byte stream that we can send over the network or save it as file or store in DB for later usage.

Deserialization is the process of converting byte stream to actual Java Object to be used in our program.

It is mainly used in Hibernate, JPA, technologies.

61
Q

Reference variable

A

A variable that points to an object of a given class and lets you access the value of an object

62
Q

Non Access Modifiers

A

Non Access Modifiers are the keywords introduced in Java 7 to notify JVM about a class’s behavior, methods or variables, etc.

  • Static
  • Final
  • Abstract
  • Synchronized
    (This modifier is used to control the access of a particular method or a block by multiple threads)
  • Transient
    (A variable which is declared as transient will used to avoid serialization)
  • Strictfp
    ( used to ensure that floating points operations give the same result on any platform As floating points precision may vary from one platform to another. strictfp keyword ensures the consistency across the platforms.
  • Volatile
    (volatile modifier is used in multi threaded programming)
63
Q

Differences between JDK, JRE and JVM

A

Java Development Kit (JDK)
is a Kit that provides the environment to develop and execute(run) the Java program

JRE (Java Runtime Environment)
is an installation package that provides an environment to only run the java program onto your machine.

JVM (Java Virtual Machine) It converts Java bytecode into machines language JVM is a part of JRE
is a very important part of both JDK and JRE because it is contained or inbuilt in both.
JVM is responsible for executing the java program line by line, hence it is also known as an interpreter.

64
Q

What is AJAX?

A

AJAX is a developer’s dream, because you can:

Read data from a web server - after a web page has loaded
Update a web page without reloading the page
Send data to a web server - in the background

AJAX = Asynchronous JavaScript And XML.

AJAX is not a programming language.

AJAX just uses a combination of:

A browser built-in XMLHttpRequest object (to request data from a web server)
JavaScript and HTML DOM (to display or use the data)
AJAX is a misleading name. AJAX applications might use XML to transport data, but it is equally common to transport data as plain text or JSON text.

AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

65
Q

What is singleton Pattern, What is the purpose of the Singleton pattern?

A
The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance.
The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes.
66
Q

Why string Immutable

A

Immutable simply means unmodifiable or unchangeable,
Once String object is created its data or state can’t be changed but a new String object is created.

The key benefits of keeping this class as immutable are 
caching, 
security, 
synchronization, 
performance.
67
Q

What is the difference between uncheck an check in java

A

There are two types of exceptions: checked exception and unchecked exception. The main difference between checked and unchecked exception is that the

  • checked exceptions are checked at compile-time while
  • unchecked exceptions are checked at runtime.
68
Q

What is the Exception Root class

A

The Throwable class,

69
Q

What is the collection Root class

A

Collection interface.

70
Q

Synchronous (Sync) and asynchronous (Async) programming

A

Synchronous (Sync) and asynchronous (Async) programming can be done in one or multiple threads.
The main difference between the two is when using synchronous programming we can execute one task at a time, but when using asynchronous programming we can execute multiple tasks at the same time.

71
Q

What is Java synchronized?

A

Synchronization in java is the capability to control the access of multiple threads to any shared resource.

72
Q

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

A
non-static Method are owned by objects of the class and have object-level scope 
and to call non-static method from static block (same like from static main method) an object of the class need to be created first
73
Q

Why do we need data structures?

A

A data structure is a unique way of storing or organizing the data in computer memory in order to perform various operations on it.
For example, perform searching, sorting or looping operations.

74
Q

What is meant by an average O(1) constant time

A

O(1) does not necessarily mean “quickly”. It means that the time it takes is constant, and not based on the size of the input to the function. Constant could be fast or slow.

O(n) means that the time the function takes will change in direct proportion to the size of the input to the function, denoted by n.

Again, it could be fast or slow, but it will get slower as the size of n increases.

75
Q

Linear Data Structures and Non-Linear Data Structures:

A

Linear Data Structures: (single level )
In a linear data structure all the elements are arranged in the linear or sequential order. The linear data structure is a single level data structure.
(ex. array, linkedList, Stack, Queue)

Non-Linear Data Structures: (multilevel)
The non-linear data structure does not arrange the data in a sequential manner as in linear data structures.
Non-linear data structures are the multilevel data structure.
(ex. Tree, Graph)

76
Q

BufferedReader & BufferedWriter

A

Both BufferedReader and BufferedWriter in java are classified as buffered I/O streams.
Buffered input streams read data from a memory area known as a buffer
Similarly, buffered output streams write data to a buffer

BufferedReader
used to read the stream of characters from the specified source (character-input stream). The buffer size may be specified.

BufferedWriter is a sub class of java. io. Writer class. BufferedWriter writes text to character output stream, buffering characters

77
Q

Reflection in java

A
78
Q

Marker interface (also known as tag or ability interface)

A

if the interface can not contain any method or fields and by implementing this interface
our object get some ability such type of interfaces are called as market interface

Marker interface is used as a tag to inform a message to the compiler so that it can add specific behavior to the class implementing it 
Example: Serializable, cloneable,
79
Q

What is variable scope

A
Member Variables (Class Level Scope) instance variables, static
Local Variables (Method Level Scope)
Loop Variables (Block Scope)
80
Q

What is stream in Java and how many types of streams

A

A stream is a sequence of objects that supports various methods
which can be pipelined to produce the desired result.

There are two basic types of stream defined by Java, called
byte stream and character stream.

1- The byte stream classes provide a convenient means for handling input and output of bytes.
2- The character streams provide a convenient means for handling input and output of characters,

map() used to returns a stream consisting of the results
filter() used to select elements as per the Predicate passed as argument.
sorted() used to sort the stream
collect() to return the result of the intermediate operations performed on the stream.
reduce() used to reduce the elements of a stream to a single value
forEach used to iterate through every element of the stream.

81
Q

final , Finally() , Finalize()

A

final: three implementations “unchangeable”
o Final class: No subclasses can extend from this class.
o Final method: Can’t be overridden
o Final variable: Can’t be modified after initialization.
 Finally, is used in a try/catch block which handles exceptions/errors.

Finally() : is used in try/catch block which handles exceptions/errors it will always run no matter if an exception is caught or not

Finalize() : is the method that will be run before an object is removed from memory (ie garbage collected)

82
Q

Functional interface

A

Has one abstract method that allows you to use Lambda expressions and
the number of default methods or in static methods.

83
Q

What are collection and collections in Java?

A

Collection is the interface where you group objects into a single unit.
Collection does not have all static methods in it, but Collections consist of methods that are all static.

Collections framework is a utility class  that contains many useful static methods that has some set of operations you perform on Collection. 
There are two categories: iterable types and map types. The iterable types are sub-interfaces and implementing classes of java.util.Iterable. Note that java.util.Collection is a sub-interface of java.util.Iterable. The map types are sub-interfaces and implementing classes of java.util.Map.

Collection does not have all static methods in it, but Collections consist of methods that are all static.

84
Q

What are parameterized types?

A

Parameterized types = Generics
types that take other types as parameters.

A parameterized type is an instantiation of a generic type with actual type arguments. … The type parameter E is a place holder that will later be replaced by a type argument when the generic type is instantiated and used. The instantiation of a generic type with actual type arguments is called a parameterized type .

85
Q

What is access modifier

A

Access modifiers are object-oriented programming that is used to set the accessibility of classes, interfaces, variables, methods, constructors, data members, and the setter methods.

86
Q

Difference Between a collection and Data Structure

A

Data structures are ways to organize and store data in memory.
A collection is how it can be accessed these data.

A data structure is a generic term for an object that represents some sort of data, so a linked list, array, etc are all data structures. A collection in the Java sense refers to any class that implements the Collection interface. A collection in a generic sense is just a group of objects.

87
Q

Java 8 Method References

A

A method reference can be identified by a double colon separating ( :: )a class or object name, and the name of the method. It has different variations, such as constructor reference:

88
Q

Q1. What New Features Were Added in Java 8?

A

Lambda Expressions :− a new language feature allowing us to treat actions as objects

StringJoiner:- used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.

Method References :− enable us to define Lambda Expressions by referring to methods directly using their names

Optional :− special wrapper class used to represent optional values that either exist or do not exist.

Functional Interface :– an interface with maximum one abstract method; implementation can be provided using a Lambda Expression.

Default methods :− give us the ability to add full implementations in interfaces besides abstract methods

Nashorn, JavaScript Engine :− Java-based engine for executing and evaluating JavaScript code

Stream API :− a special iterator class that allows us to process collections of objects in a functional manner

Date API :− an improved, immutable JodaTime-inspired Date API

89
Q

What Is a Stream? How Does It Differ From a Collection?

A

In simple terms, a stream is an iterator whose role is to accept a set of actions to apply on each of the elements it contains.

Stream can be created from Collections, Lists, Sets, int, Longs, doubles, arrays, lines of a file

90
Q

Internal iterator and external iterator

Imperative ) and (declarative

A

Internal iterator , While, Iterator (Imperative ) for(int i : array)
External iterator forEach(i - > { } ) , stream API (declarative )

91
Q

Pass by value
pass by reference
pass by method

A

Pass by value (parameter)
pass by reference
pass by method (method reference :: )

92
Q

What is Arrays.asList () in Java? and What is the difference between arrays asList and ArrayList?

A

The asList() method of java. util. Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection. toArray().

asList method returns a type of ArrayList that is different from java. util. ArrayList. The main difference is that the returned ArrayList only wraps an existing array — it doesn’t implement the add and remove methods.

93
Q

What is the different ways to create an optional object

A

Optional.empty()
Optional.of()
Optional.ofNullable()

94
Q

Parallel streams and Sequential stream

A
95
Q

what is map

A

used to transform one object into other by applying a function

96
Q

distinct() (unique)

A

distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get unique elements.

distinct() performs stateful intermediate operation

97
Q

what are arrays

A

A series of reserved memory addresses for a fixed number of variables and located next to each other in memory

98
Q

Red-Black Tree

A
99
Q

Hash Collision Handling

A

Two basic methods are used to handle collisions.

Separate Chaining
uses an additional data structure, preferrably linked list for dynamic allocation, into buckets.
To find an item we first go to the bucket and then compare keys

Open Addressing
Open addressing does not introduce any new data structure. If a collision occurs then we look for availability in the next spot generated by an algorithm. Open Addressing is generally used where storage space is a restricted,
Methods for Open Addressing

[Linear Probing
Quadratic Probing
Double Hashing

100
Q

What is Hash function or hash algorithm

A

Hash function or hash algorithm creates a unique digital fingerprint numerical value of data called digest or message digest or simple hash
and use for comparison purpose not for encryption

101
Q

HashCode

A

HashCode is a numerical value which represents internal address of object
Hashcode is used to store , remove ,search in set and map collections (hashset and hashmap)
To retrieve hashcode of an object use hashcode()
By default java generate it but to generate hashCode of object we need to override hashcode method in object class
Hash code used to produce the key to a numerical value and this numerical value used as index to store the value in hashMap

102
Q

What kinds of Interfaces are there in Java?

A

1 - Functional Interface.
Functional Interface is an interface that has only pure one abstract method.
It can have any number of static and default methods and also even public methods of java.lang.Object classes

2 - Marker interface
Marker interface is used as a tag to inform a message to the Java compiler so that it can add special behaviour to the class implementing it. Java marker interface has no members in it.
The Serializable , Remote and the Cloneable interfaces are examples of Marker interfaces.

From java 1.5, the need for marker interface is eliminated by the introduction of the java annotation feature. So, it is wise to use java annotations than the marker interface. It has more feature and advantages than the java marker interface.

103
Q

What is the record in Java?

A

A Java Record is a new way to declare a type in the Java language.
Records were introduced to the Java language to reduce the boilerplate (repetitive code) associated with Plain Old Java Objects (POJO).
When creating a good POJO, a developer must implement a constructor, accessors, equals method, a toString method, and the corresponding getters. From POJO to POJO, the implementations are exactly the same, the only thing that changes is the name of the properties for the type.
Although IDEs and projects like Lombok have created features which auto generate this boilerplate code, having all of this boilerplate can get in the way of understanding what the POJO represents.

It’s ideal for “plain data carriers,” classes that contain data not meant to be altered and only the most fundamental methods such as constructors and accessors.

A record class declares a sequence of fields, and then the appropriate accessors, constructors, equals , hashCode , and toString methods are created automatically.
you can't add any instanse variables but you can add only static variables
final class Rectangle implements Shape {
    final double length;
    final double width;
    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }
    double length() { return length; }
    double width() { return width; }
}

You can represent this class with a record:

record Rectangle(float length, float width) { }

104
Q

What is Reactive Programming?

A

Reactive Programming is a programming language with asynchronous data stream.Once an event will raise it will react with responsive and non-blocking manner that’s why it named it as reactive programming.

In a Reactive Programming context, “Everything is a Stream and acts in a non-blocking manner when there is data in the stream.”

105
Q

is Java Type safe Language

A

Yes

106
Q

What is Local variable type interface

A

This new feature will allow you to declare and initialise local variables with var, rather than specifying a type.

String greeting = "Hello World";
ArrayList messages = new ArrayList();
messages.add(greeting);
Stream stream = messages.stream();

But in Java 10 you can do this:

var greeting = "Hello World";
var messages = new ArrayList();
messages.add(greeting);
var stream = messages.stream();

Where you can use it:
local variables with initialisers
indexes in for each loops
locals in for loops

107
Q

Explain and give an example of [pillar of OOP].

A

Inheritance : When one class (subclass) can reused property of another class (super-class)

Encapsulation: Is how you restrict access to your code by using an access modifier
hiding data as passwoed and information by making the variable as private and expose the property to access the private data which would be public.

Polymorphism: means “many forms” The ability for some code structure in an OOP language to treated different structures at runtime
polymorphism allows us to perform a single action in different ways. Like a man at the same time is a father, a husband, an employee. So the same person possesses different behavior in different situations.

Abstraction: is the principle of using simple things to represent complex things
For example to open your TV we only have a power button, It is not required to understand how infra-red waves are getting generated in TV remote control.

108
Q

What is JSON

A

JavaScript object Notation is a Syntax for storing and exchanging data

109
Q

What is http

A

Hypertext Transfer Protocol ( POST , GET, PUT, DELETE)
SQL (INSERT, SELECT, UPDATE, DELETE)
CRUD (CREATE, READ, UPDATE, DELETE)

110
Q

Status code

A
1xx  informational
2xx  success
3xx  redirection
4xx  client error
5xx  server error
111
Q

Where does Java store variables?

A

Local variables and a reference variable of objects are stored on the stack (short life ).
Instance and static variables are stored on the heap (Long life ).

112
Q

can we inherit a static class in java

A
Static methods in Java are inherited, but can not be overridden.
 If you declare the same method in a subclass, you hide the superclass method instead of overriding it.
113
Q

Differences between SOAP and Rest

A

SOAP – Simple Object Access Protocol
- xml message protocol
- use only WSDL to send and receive data
- invokes services by calling RPC method
- return unreadable human result
- Transfer over HTTP, SMTP, FTP protocols
- difficult for JavaScript to implement
- High security
- less performance comparer to REST
—————————————————————————-
REST – Representational State Transfer
- uses xml or JSON to send and receive data
- Simply call services URL path
- return human readable result JSON or XML
- Transfer over HTTP only
- Easy to call from JavaScript
- Hight performance comparer to SOAP