Crack the Code: IT Interview Questions and Answers - Programming Language Institute

Programming practice questions and answer

Java Programming Language

 
1

Question- Explain JDK, JRE and JVM?



Answer-

JDK: It stands for Java Development Kit.It is the tool necessary to compile, document and package Java programs.It contains JRE + development tools.

JRE:It stands for Java Runtime Environment.JRE refers to a runtime environment in which Java bytecode can be executed.It’s an implementation of the JVM which physically exists.

JVM:It stands for Java Virtual Machine.It is an abstract machine. It is a specification that provides a run-time environment in which Java bytecode can be executed.JVM follows three notations: Specification, Implementation, and Runtime Instance.

2

Question- Explain public static void main(String args[]) in Java.



Answer-

main() in Java is the entry point for any Java program. It is always written as public static void main(String[] args).

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. main() is made static in Java so that it can be accessed without creating the instance of a Class. In case, main is not made static then the compiler will throw an error as main() is called by the JVM before any objects are made and only static methods can be directly invoked via the 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.

3

Question- Why Java is platform independent?



Answer- Java is called platform independent because of its byte codes which can run on any system irrespective of its underlying operating system.

4

Question- Why Java is not 100% Object-oriented?



Answer- 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.

5

Question- What are constructors in Java?



Answer-

In Java, constructor refers to a block of code which is used to initialize an object. It must have the same name as that of the class. Also, it has no return type and it is automatically called when an object is created.

There are two types of constructors:

1. Default Constructor: In Java, a default constructor is the one which does not take any inputs. In other words, default constructors are the no argument constructors which will be 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. Also, it is majorly used for object creation. 
2. Parameterized Constructor: The parameterized constructor in Java, is the constructor which is capable of initializing the instance variables with the provided values. In other words, the constructors which take the arguments are called parameterized constructors.

6

Question- What is singleton class in Java and how can we make a class singleton?



Answer- Singleton class is a class whose only one instance can be created at any given time, in one JVM. A class can be made singleton by making its constructor private.

7

Question- What is the difference between Array list and vector in Java?



Answer-

ArrayList:Array List is not synchronized.It is fast as it’s non-synchronized.If an element is inserted into the Array List, it increases its Array size by 50%.Array List does not define the increment size.Array List can only use Iterator for traversing an Array List.

vector: Vector is synchronized.Vector is slow as it is thread safe.It defaults to doubling size of its array.Vector defines the increment size.Vector can use both Enumeration and Iterator for traversing.

8

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



Answer-

Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic.

“==” or equality operator in Java is a binary operator provided by Java programming language and used to compare primitives and objects. public boolean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. For example: method can be overridden like String class. equals() method is used to compare the values of two objects.

9

Question- What is a package in Java? List down various advantages of packages.



Answer-

Packages in Java, are the collection of related classes and interfaces which are bundled together. By using packages, developers can easily modularize the code and optimize its reuse. Also, the code within the packages can be imported by other classes and reused. Below I have listed down a few of its advantages:

  • Packages help in avoiding name clashes
  • They provide easier access control on the code
  • Packages can also contain hidden classes which are not visible to the outer classes and only used within the package
  • Creates a proper hierarchical structure which makes it easier to locate the related classes

10

Question- Why pointers are not used in Java?



Answer- Java doesn’t use pointers because they are unsafe and increases the complexity of the program. Since, Java is known for its simplicity of code, adding the concept of pointers will be contradicting. Moreover, since JVM is responsible for implicit memory allocation, thus in order to avoid direct access to memory by the user,  pointers are discouraged in Java.

11

Question- What is JIT compiler in Java?



Answer- JIT stands for Just-In-Time compiler in Java. It is a program that helps in converting the Java bytecode into instructions that are sent directly to the processor. By default, the JIT compiler is enabled in Java and is activated whenever a Java method is invoked. The JIT compiler then compiles the bytecode of the invoked method into native machine code, compiling it “just in time” to execute. Once the method has been compiled, the JVM summons the compiled code of that method directly rather than interpreting it. This is why it is often responsible for the performance optimization of Java applications at the run time.

12

Question- What are access modifiers in Java?



Answer-

In Java, access modifiers are special keywords which are used to restrict the access of a class, constructor, data member and method in another class. Java supports four types of access modifiers:

1. Default
2. Private
3. Protected
4. Public

13

Question- Define a Java Class.



Answer-

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. Let’s have a look at the syntax of a class.

 class Abc 
 {
 member variables // class body
 methods

 }

14

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



Answer-

An object is a real-world entity that has a state and behavior. An object has three characteristics:

  • State
  • Behavior
  • Identity
An object is created using the ‘new’ keyword. For example:

ClassName obj = new ClassName();

15

Question- What is Object Oriented Programming?



Answer- Object-oriented programming or popularly known as OOPs is a programming model or approach where the programs are organized around objects rather than logic and functions. In other words, OOP mainly focuses on the objects that are required to be manipulated instead of logic. This approach is ideal for the programs large and complex codes and needs to be actively updated or maintained.

16

Question- What are the main concepts of OOPs in Java?



Answer-

Object-Oriented Programming or OOPs is a programming style that is associated with concepts like:

Inheritance: Inheritance is a process where one class acquires the properties of another.

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

Abstraction: Abstraction is the methodology of hiding the implementation details from the user and only providing the functionality to the users. 

Polymorphism: Polymorphism is the ability of a variable, function or object to take multiple forms.

17

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



Answer-

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.

Example

if(x > 100)
{
String test = "CSDT";
}
 

Whereas, an instance variable in Java, is a variable which is bounded to its object itself. These variables are declared within a class, but outside a method. Every object of that class will create it’s 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.

class Test{
public String EmpName;
public int empAge;
}


18

Question- What is JAVA Programming language?



Answer-

About Java Language:


  1. Java is a powerful general-purpose, object oriented  programming language. 
  2. Object-oriented: Everything is considered to be an “object” which possess some state, behavior and all the operations are performed using these objects.
  3. According to Oracle, the company that owns Java, Java runs on 3 billion devices worldwide, which makes Java one of the most popular programming languages.
  4. Secured: All the code is converted in bytecode after compilation, which is not readable by a human. and java does not use an explicit pointer and run the programs inside the sandbox to prevent any activities from untrusted sources. It enables to develop virus-free, tamper-free systems/applications.
  5. It is an object-oriented language similar to C++, but with advanced and simplified features.This language is free to access and can run on all platforms.


History of JAVA Language 

Java is a programming language developed by James Gosling with other team members named Mike Sheridan and Patrick Naughton also called as Green Team in 1995 for Sun Microsystems for digital devices such as set-top boxes, televisions etc. 


Java Programming Applications

Some of the applications are listed below:

  • Banking: To deal with transaction management.
  • Retail: Billing applications that you see in a store/restaurant are completely written in Java.
  • Information Technology: Java is designed to solve implementation dependencies.
  • Android: Applications are either written in Java or use Java API.
  • Financial services: It is used in server-side applications.
  • Stock market: To write algorithms as to which company they should invest in.  
  • Big Data: Hadoop MapReduce framework is written using Java.
  • Scientific and Research Community: To deal with huge amount of data.

19

Question- What is JDK(JAVA Development Kit), JRE(Java Runtime Environment) and JVM(Java Virtual Machine) in Java Language ?



Answer-

What is JVM?

JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a Java program.

When you run the Java program, Java compiler first compiles your Java code to bytecode. Then, the JVM translates bytecode into native machine code (set of instructions that a computer's CPU executes directly).

Java is a platform-independent language. It's because when you write Java code, it's ultimately written for JVM but not your physical machine (computer). Since JVM executes the Java bytecode which is platform-independent, Java is platform-independent.


What is JRE?

JRE (Java Runtime Environment) is a software package that provides Java class libraries, Java Virtual Machine (JVM), and other components that are required to run Java applications. JRE is the superset of JVM.


What is JDK?

JDK (Java Development Kit) is a software development kit required to develop applications in Java. When you download JDK, JRE is also downloaded with it.

In addition to JRE, JDK also contains a number of development tools (compilers, JavaDoc, Java Debugger, etc).



20

Question- What is for each loop?



Answer- the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.

for-each Loop Sytnax

The syntax of the Java for-each loop

for(dataType item : array) 

{

    ...

}


Here,

  • array - an array or a collection
  • item - each item of array/collection is assigned to this variable
  • dataType - the data type of the array/collection

// print array elements 


class Main {

  public static void main(String[] args) {

      

    // create an array

    int[] numbers = {3, 9, 5, -5};

    

    // for each loop 

    for (int number: numbers) {

      System.out.println(number);

    }

  }

}

21

Question- Why we use Java continue Statement?



Answer- While working with loops, sometimes you might want to skip some statements or terminate the loop. In such cases, break and continue statements are used.

Java continue

The continue statement skips the current iteration of a loop (forwhiledo...while, etc).

After the continue statement, the program moves to the end of the loop. And, test expression is evaluated (update statement is evaluated in case of the for loop).

class Main {

  public static void main(String[] args) {


    // for loop

    for (int i = 1; i <= 10; ++i) {


      // if value of i is between 4 and 9

      // continue is executed

      if (i > 4 && i < 9) {

        continue;

      }

      System.out.println(i);

    }

  }

}

22

Question- What is the use of Java break Statement?



Answer-

While working with loops, it is sometimes desirable to skip some statements inside the loop or terminate the loop immediately without checking the test expression.

In such cases, break and continue statements are used. 

The break statement in Java terminates the loop immediately, and the control of the program moves to the next statement following the loop.

It is almost always used with decision-making statements.

class Test {

    public static void main(String[] args) {

      

        // for loop

        for (int i = 1; i <= 10; ++i) {


            // if the value of i is 5 the loop terminates  

            if (i == 5) {

                break;

            }      

            System.out.println(i);

        }   

    }

}

23

Question- What is Java Copy Arrays?



Answer- In Java, we can copy one array into another. There are several techniques you can use to copy arrays in Java.

class Main {

    public static void main(String[] args) {

       

        int [] numbers = {1, 2, 3, 4, 5, 6};

        int [] positiveNumbers = numbers;    // copying arrays


        for (int number: positiveNumbers) {

            System.out.print(number + ", ");

        }

    }

}

24

Question- What is Java Recursion?



Answer-

In Java, a method that calls itself is known as a recursive method. And, this process is known as recursion.

A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.

Factorial of a Number Using Recursion

class Factorial {


    static int factorial( int n ) {

        if (n != 0)  // termination condition

            return n * factorial(n-1); // recursive call

        else

            return 1;

    }


    public static void main(String[] args) {

        int number = 4, result;

        result = factorial(number);

        System.out.println(number + " factorial = " + result);

    }

}

25

Question- What is java instaceof Operator?



Answer- The instanceof operator in Java is used to check whether an object is an instance of a particular class or not.
Syntax:

objectName instanceOf className;


Here, if objectName is an instance of className, the operator returns true. Otherwise, it returns false.

Example: Java instanceof


class Main {


  public static void main(String[] args) {


    // create a variable of string type

    String name = "CSDT";

    

    // checks if name is instance of String

    boolean result1 = name instanceof String;

    System.out.println("name is an instance of String: " + result1);


    // create an object of Main

    Main obj = new Main();


    // checks if obj is an instance of Main

    boolean result2 = obj instanceof Main;

    System.out.println("obj is an instance of Main: " + result2);

  }

}


output:

name is an instance of String: true

obj is an instance of Main: true