You are on page 1of 16

Core Java Interview Questions:

=======================
0) Why Java is secure?
Java programs run inside a virtual machine which is known as a sandbox. Java
does not support explicit pointer.
Byte-code verifier checks the code fragments for illegal code that can violate
access right to object.
===================================================================================
=====================

1) what is Java?
Java is a widely used Object-Oriented Programming Language and Simple
Language. We run the same code on
multiple platforms. Java achieves this using JVM and Byte code.
===================================================================================
=====================

2) Why java is platform independent?


Java is platform-independent because it uses a virtual machine. This means
that once your code is written,
you may run it anywhere, on any platform that has the necessary environment. The
code is executed via the
Java Virtual Machine (JVM).
===================================================================================
=====================

3) What is Open Source?


Open source is a term that originally referred to open source software (OSS).
Open source software is code
that is designed to be publicly accessible—anyone can see, modify, and distribute
the code as they want.
===================================================================================
=====================

4) why did we go for Java?


Java has the ability to easily move across platforms and can be run on
different systems. This critical nature of
being platform-independent at the source and binary levels makes Java an essential
language for developers.
===================================================================================
=====================

5) Difference between JDK,JRE,JVM?


*JDK = JRE + JVM
=> JDK - Java Development Kit.
--> Whenever I want to run or develop a program in Java JDK is
essential.
=> JRE - Java Runtime Environment.
--> It contains predefined files and a library.
=>JVM - Java Virtual Machine.
--> It is used for memory allocation.
===================================================================================
=====================

6) Features of Java?
Java is a versatile and popular programming language known for its simplicity,
portability, and robustness. I know some key features of Java:
* Simple.
* Interpreted.
* Multi-Threaded.
* Object-Oriented Programming Language.
* Open Source
* Platform independent.
* Portable.
* Robust.
* Secure.

===================================================================================
=====================

7) What type of tool you are using in your project to execute Java?
I execute my Java projects using Eclipse.
===================================================================================
=====================

8) What are the IDE tools?


IDE - Integrated Development Environment.
tools:
* Eclipse.
* Intelli J.
* Netbeans.
* J developers -- Oracle.
* RAD -- IBM.
===================================================================================
=====================

9) What is Compiler?
A compiler is a special program that translates a programming language's
source code into machine code,
bytecode or another programming language.
===================================================================================
=====================

10) Difference between class, method, and object?


The program must be a collection of classes, methods, and objects.
* Object: Memory used for your program to execute a method.
* Method: Action performed inside a class.
* Class: Collections of methods and objects.
* Package: Collections of Classes.
* Project: Collections of Packages.
===================================================================================
=====================

11) Where object stored in Java?


The heap is a part of the memory which is dedicated to storing objects in
Java.
===================================================================================
=====================

12) How to access one class method into another package in a different package?
Use the java import keyword which is used to access the package and its
classes into the java program.
===================================================================================
=====================

13) Coding standard to create project, class, method, package, and object?
Two types of Coding standards:
(i) Pascal notation:
Every word's first letter should start with Upper Case.
eg. GreensTechTrichy.
=> Project and Class.
(ii) Camel Notation:
For first words, the First letter should be lower case, and the remaining
words should start in Upper Case.
eg. greenTechTrichy.
=> method, object, and variable.
(iii) Package:
All letters should be in Lower case. => org. or com.
=> org.greenstechtrichy.
===================================================================================
=====================

14) What gives Java its "write once and run anywhere" nature?
Java's "write once, run anywhere" nature is mainly due to its bytecode
architecture and the Java Virtual Machine (JVM).
===================================================================================
=====================

15) Difference between c++ and java?

C++
JAVA
(i) Compiled Programming language Compiled Programming
Language.
(ii) Supports Operator overloading Does not support Operator
Overloading.
(iii) C++ program is a fast compiling Java Program
compiler a bit slower than C++.
language.

===================================================================================
=====================

16) Explain the Same Package and Different Packages?


(i) Same Package Different Class:
* Creating a method in a class and calling an object in another class within a
package.
* In this creation the calling object in another class, that calling method
will be in public to access.
(ii) Different Package Different Class:
* Calling class and methods of one package into another package.
* In this creation the calling object in another class, that calling method
will be in public to access and the calling package will be imported.
===================================================================================
=====================

17) What is a variable in Java?


A variable is used to store data values. A variable is assigned with a data
type. A variable is the name of the memory location.
Variable Declaration:
===============
> datatype varname = value;
| |
lowercase camel notation
===================================================================================
=====================
18) Define Datatypes?
Datatypes will define the type and size of a variable. There are two types of
data types in Java:
=> Primitive Data Types:
================
A primitive datatype is defined by the language and is named by a reserved
keyword. Primitive data types are supported by the Java Programming Language.

(i) byte ---> -128 to 127 ---> 1 Byte.


(ii) short ---> -32768 to 32767 ---> 2 Bytes.//4 digits good.
(iii) int ---> upto 8 digits ---> 4 Bytes.
(iv) long ---> upto 16 digits ---> 8 Bytes.//In last L is
must.
(v) float ---> upto 7 decimals ---> 4 Bytes.//In last F is
must.
(vi) double ---> upto 15 decimals ---> 8 Bytes.
(vii) char ---> Single Character ('S') ---> 2 Bytes.//Must in single
coat.
(viii) boolean ---> true/false ---> 1 Byte.

=> Non-Primitive Datatypes:


===================
Non-Primitive datatypes are all pre-defined and user(Programmer) defined
classes and interfaces.

(i) Strings.
(ii) Arrays.
(iii) Interfaces.
(iv) Classes.

* String empName = "Joyel Greens Tech"; //within double coats.


===================================================================================
=====================

19) What is meant by inheritance?


Inheritance is a mechanism in which one class acquires the properties of
another class. For example,
a child inherits the traits of his/her parents. With inheritance, we can reuse the
fields and methods of the existing class.
===================================================================================
=====================

20) Types of inheritance and explain all types?


=> Single Inheritance:
Combinations of one parent class and one child class.
A ----> B
=> Multi-level Inheritance:
More than one parent class accessing the child class in a tree-level
structure or Chaining inheritance. (Level by level)
A <--- B <---C
=> Hierarchical Inheritance:
Combination of one parent and more than one child.
B ---> A <--- C
=>Multiple Inheritance:
More than one parent class accesses the child class parallelly at a time.
A <--- C ---> B
=> Hybrid Inheritance:
Combination of Single and multiple Inheritance.
* Multiple Inheritance and Hybrid Inheritance is not possible in Java by using
class.
Reasons:
======
=> Priority Issue.
=> System error(By using extends keyword we can't access two classes Parallely.)
===================================================================================
=====================

21) Difference between hybrid and hierarchical inheritance?


In a hierarchy, the combination of one parent and more than one child class.
In a hybrid, a combination of single and multiple inheritances.
===================================================================================
=====================

22) How will achieve multiple inheritance in Java, write a code for that.
Java does not support multiple inheritance. This means that a class cannot
extend more than one class parallely,
but we can still achieve the result using the keyword 'extends'.
===================================================================================
=====================

23) What is the difference b/w Print and Println?


* The print method simply prints text on the console and does not add a new
line.
* The printing method adds a new line after printing text on the console.
===================================================================================
=====================

24) What is meant by Polymorphism?


One method that can be executed in many ways is called polymorphism.
(or)
Executing methods in more than one form. ( Poly - Many, morphism - Forms )

Two types of polymorphism:


* Method Overloading (or) compile time polymorphism.
* Method Overriding (or) Run time polymorphism.
===================================================================================
=====================

25) Difference between method overloading and method overriding?


* Method Overloading:
Method overloading allows a class to have more than one method with the same
name but different arguments or parameters.
=> Same Classname.
=> Same Methodname.
=> Different Arguments.

* Method Overriding:
When we are not satisfied with the parent class logics, we can create the
same method in our child class and we can write our
required business logic.
=> Different Classname.
=> Same Method name.
=> Same Arguments.
===================================================================================
=====================

26) What is the use of scanner class?


It is a predefined class in Java. util package which is used to get input
from the console. Thus means, Scanner is mostly used to
receive user input and parse them into primitive data types such as int, double or
default String.
Package java.until:
=============
Contains the collections of the framework, legacy collection classes, event model,
date and time facilities, internationalization, and miscellaneous
utility classes (a string tokenizer, a random-number generator, and a bit array).
===================================================================================
=====================

27) What is the Syntax for the Scanner?


//object creation:
============
=>> Scanner obj = new Scanner(System.in);

//variable declaration in Scanner:


=========================
=>> datatype var = obj.nextDatatype( );
===================================================================================
=====================

28) What are the different methods available in the Scanner class?
* nextByte( );
* nextShort( );
* nextInt( );
* nextFloat( );
* nextLong( );
* nextDouble( );
* nextBoolean( );
* next ( );
* nextLine( ); ---->String
* next( ).charAt(0);
===================================================================================
=====================

29) Scanner class is under which package?


The scanner class is under Java. util.*; Package.
===================================================================================
=====================

30) Difference between next( ) and nextLine( )?


nextLine() returns every character in a line of text right up until the
carriage return, while next() splits the line up into individual
words, returning individual text Strings one at a time.
===================================================================================
=====================

31) What is the Scanner Syntax?


=> object creation:
= Scanner obj = new Scanner(System.in);
=> variable declaration:
= datatype var = obj.nextDatatype( );
===================================================================================
=====================

32) What is the use of access specifiers and types?


Access Specifiers in a class decide the accessibility of the class members,
like variables or methods in other classes.
It will specify the extent of access.
Types:
=====
* Private --> Class level access specifier.
* Default --> Package level access specifier.
* Protected --> Package level access specifier but by inheriting.
* Public --> Global level access specifier.
===================================================================================
=====================

33) What is meant by Wrapper class?


A Wrapper class is a class that contains the primitive data types (int, char,
short, byte, etc). In other words, wrapper classes
provide a way to use primitive data types (int, char, short, byte, etc) as
objects. These wrapper classes come under Java. util package.
===================================================================================
=====================

34) What is the default value of String?


The default value of String is null.
===================================================================================
=====================

35) What is the superclass of all Java classes?


Object.
===================================================================================
=====================

36) What is meant by Abstraction in Java?


Abstraction is a process of hiding the implementation details of a method
and showing only functionality to the users.
===================================================================================
=====================

37) Difference between Abstract class and interface?


An abstract class can be inherited using extends keyword. The interface can
only be implemented using the implements keyword.
An abstract class can have any type of method private, or public. The interface can
only have public methods.
===================================================================================
=====================

38) What is meant by the abstract method?


Abstract classes cannot be instantiated, but they can be subclassed. An
abstract method is a method that is declared without an
implementation (without braces, and followed by a semicolon).
===================================================================================
=====================

39) Can we create the object for the abstract class?


We cannot create objects of an abstract class. If you want to create an
object, create a child class and call the methods in the child class only.
===================================================================================
=====================

40) How will achieve multiple inheritances in Java, write a code for that.
Using the interface, we can achieve multiple inheritances in Java.
===================================================================================
=====================

41) what are the types of Abstraction?


=> Abstract methods: Methods without the body.
=> Non-abstract methods: Methods with the body. A non-abstract class can't
have abstract methods.
===================================================================================
=====================

42) What is meant by a string?


The string is a predefined class in Java.lang package which is used to define
the group of characters. It's an index-based
storage position in a variable and it ranges o to length -1.
===================================================================================
=====================

43) How to find the length of the string?


Using length( ); method.
===================================================================================
=====================

44) How to find a particular character in the string?


Using charAt( ); method.
===================================================================================
=====================

45) How to split the string?


Using split( ); method.
===================================================================================
=====================

46) What is difference between charAt() and contains() method?


charAt( ) --> To find a character at a particular index.
contains( ) ---> To check whether a particular character is present in the
string.
===================================================================================
=====================

47) What is the difference between literal String and non-literal string?
* A literal String is a sequence of characters from the source character set
used by Java programmers to populate string
objects or to display text to a user. It is used to store inside the String pool
as a part of heap memory. In case of a duplicate, it
will share the memory.
* A non-literal String is also a sequence of characters from the source
character set, it is used to be stored directly in a
heap memory. In case of duplicate also it will store or share the different memory
locations.
===================================================================================
=====================

48) What is a mutable and immutable string?


* A string is an immutable object which means we cannot change them after
creating the objects. Whenever we change
any string, a new instance is created.
* Mutable strings are those strings whose content can be changed without
creating a new object. StringBuffer and
StringBuilder are mutable versions of String in Java.
===================================================================================
=====================

49) Difference between string builder and StringBuffer?


String Buffer --> * Before JDK 1.0.
* Synchronous (Sequential Execution).
* Thread Safe.
* Slower.

String Builder --> * After JDK 1.5.


* Asynchronous(Parallel Execution).
* Non - Thread safe.
* Fastly.
===================================================================================
=====================

50) Method name to identify memory location?


The hashCode() method is one of the common methods for all Java objects.
===================================================================================
=====================

51) What are the string functions available in Java?


* length( );
* isEmpty( );
* charAt( );
* indexOf( );
* lastindexOf( );
* toUpperCase( );
* toLowerCase( );
* startsWith( );
* endsWith( );
* contains( );
* equals( );
* equalsIgnoreCase( );
* concat( );
* replace( );
* replaceAll( );
* trim( );
* split( );
* subString( );
* compareTo( );
These are just some of the commonly used string functions in Java. There are
many more string functions available in
Java that can be used depending on the specific requirements of the program.
===================================================================================
=====================

52) What is the return type of compareTo( );?


The method returns 0 if the string is equal to the other string.
===================================================================================
=====================

53) What is meant by static keyword in Java?


The static keyword is used to declare a variable or method as a class-level
entity. When a variable or method is declared
static, it belongs to the class rather than any instance of the class. This means
that there is only one copy of the static variable or
method in memory, which is shared by all instances of the class.
===================================================================================
=====================
54) Can we override the static method in Java?
No, we can't override static methods since method overriding relies on
dynamic binding at runtime, but static methods
are bonded at compile time with static binding. As a result, we are unable to
override static methods.
===================================================================================
=====================

55) Can we overload the static method in Java?


Yes, we can overload static methods, we can have two or more static methods
with the same name but with different
parameters.
===================================================================================
=====================

56) What is meant by static variable?


When a variable is declared as static it'll take memory from static memory
for initialization and so it doesn't need any object.
===================================================================================
=====================

57) What is meant by the static method?


When a variable is declared as static it'll take memory from static memory
for execution and so it doesn't need
any object for evoking the method.
===================================================================================
=====================

58) What is meant by the final keyword and what's happened when we declare the
final as in class, method, variable?
The final keyword restricts the access of the user to modify the data.
* Class = We can't inherit.
* Method = We can't override.
* Variable = We can't change the value.
===================================================================================
=====================

59) What is the difference between the final and finalize keywords?
Each of these keywords has a different functionality. The basic difference
between final, finally, and finalize is that the final is an
access modifier finally is the block in Exception Handling, and finalize is the
method of the object class.
===================================================================================
=====================

60) Where are local, static, and class variables stored in JVM?
It's all stored in Heap memory.
===================================================================================
=====================

61) What is meant by control statements and types?


Control statements are the statements that change the flow of execution of
statements.
* Conditional Statements:
- if statements.
- if else statements.
- else-if ladder statements.
- switch cases.
* Looping Statements:
- for loop.
- nested for loop.
- while loop.
- do while loop.

* Breaking Statements:
- break;
- continue;
- System.exit(0);
===================================================================================
=====================

62) What is OOPs?


OOPs is an Object Oriented Programming Structure. OOPs in Java is to improve
code reusability and redability by defining a Java Program
efficiently. The main Principles of OOPs:
* Inheritance
* Polymorphism
* Abstraction
* Encapsulation.
===================================================================================
=====================

63) what is the difference between multithreading and multitasking?


Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU.
Multitasking can be achieved in two ways:
* Process-based Multitasking (Multiprocessing).
* Thread-based Multitasking (Multithreading).
Multiprocessing uses two or more CPUs to increase computing power, whereas
multithreading uses a
single process with multiple code segments to increase computing power.
Multithreading focuses on generating computing threads
from a single process, whereas multiprocessing increases computing power by adding
CPUs.

===================================================================================
=====================

64) What is mean by for loop?


for loop is a control flow statement for specifying iteration. Specifically,
a for loop functions by running a section of code repeatedly
until a certain condition has been satisfied.
===================================================================================
=====================

65) Can you explain about for loop execution process?


* Initialization.
* Condition Checking.
* Loop body execution.
* Increment/Decrement.
* Condition Checking(again).
===================================================================================
=====================

66) What is a nested loop?


A nested loop is a (inner) loop that appears in the loop body of another
(outer) loop. The inner or outer loop
can be any type: while, do while, or for. For example, the inner loop can be a
while loop and the outer loop can be a for loop.
===================================================================================
=====================

67) Difference between for and while loop?


Both for loop and while loop is used to execute the statements repeatedly
while the program runs. The major difference between
for loop and the while loop is that for loop is used when the number of iterations
is known, whereas execution is done in the while
loop until the statement in the program is proved wrong.
===================================================================================
=====================

68) What is difference between while and do-while?


The difference between while and do while loop is that in the while loop the
condition is checked prior to executing any statements.
In the case of do while loop, statements are run at least once, and then the
condition is verified.
===================================================================================
=====================

69) What is difference between break and continue?


Break statement stops the entire process of the loop. Continue statement only
stops the current iteration of the loop.
Break also terminates the remaining iterations. Continue doesn't terminate the next
iterations; it resumes with the successive iterations.
===================================================================================
=====================

70) What is the use of default keyword in switch?


The default statement is executed if no case constant-expression value is
equal to the value of expression.
===================================================================================
=====================

71) Whether we can use continue statement in switch?


The continue statement can only be used on loops and not on switches.
===================================================================================
=====================

72) What do you mean by an array and How to create an Array?


An array is a collection of elements of the same type placed in contiguous
memory locations that can be individually referenced
by using an index to a unique identifier.

Syntax:
======
datatype varName[]= new datatype[];
===================================================================================
=====================

73) Can you change size of array once created?


You can't change the size of the array after it's constructed. However, you
can change the number of elements in an
ArrayList whenever you want.
===================================================================================
=====================
74) Can we change the size of an array at run time?
You can't change the size of the array after it's constructed.
===================================================================================
=====================

75) Can you declare an array without assigning the size of an array?
Yes. We can declare an array without size but before using it needs to be
initialized.
===================================================================================
=====================

76) What is the default value of Array?


Since no values are passed during initialization, all elements of the array
are set to their default value of 0.
===================================================================================
=====================

77) Is it legal to initialize an array int i[] = {1, 2, 3, 4, 5}


Yes, it is perfectly legal. You can create and initialize array in same line
in Java.
===================================================================================
=====================

78) How to print element of Array?


To print the elements of an array, you can iterate over the array and print
each element individually.
===================================================================================
=====================

79) How to compare Two Arrays?


A simple way is to run a loop and compare elements one by one. Java provides
a direct method Arrays.equals() to compare two arrays.
===================================================================================
=====================

80) How to sort an Array?


Using sort() method.
===================================================================================
=====================

81) Can we declare array size as a negative number?


No, you cannot declare an array size as a negative number in Java. The size
of an array must be a non-negative integer.
If you attempt to declare an array with a negative size, it will result in a
compilation error.
===================================================================================
=====================

82) Can we add or delete an element after assigning an array?


To add or remove elements, you have to create a new array.
===================================================================================
=====================

83) Advantages and disadvantages of Array?


Advantages of Arrays:
- Arrays provide fast and direct access to elements through indexing.
- They allow for fast retrieval and manipulation of data.
- They allow for efficient iteration over elements.
- Arrays have a fixed size, which can provide predictability and memory
efficiency.

Disadvantages of Arrays:
- Arrays have a fixed size, making it difficult to add or remove
elements dynamically.
- Inserting or deleting elements in the middle of an array can be
inefficient.
- Arrays require contiguous memory, which can be a limitation in memory
allocation.
- Arrays generally lack dynamic resizing capabilities, requiring manual
reallocation and copying of elements.
===================================================================================
=====================

84) what is collection and explain about types?


A collection refers to a framework that provides an organized way to store
and manipulate groups of objects. It allows you to
perform various operations such as adding, removing, and retrieving elements from
the collection. The Java Collections Framework
provides several interfaces and classes that define different types of collections.
Here are some commonly used collection types in Java:
* List
* Set
* Map
* Queue

===================================================================================
=====================

85) What is the difference between ArrayList and Vector?


The main difference between ArrayList and Vector in Java is that ArrayList is
not synchronized, while Vector is synchronized.

This means that ArrayList is not thread-safe and may lead to issues in concurrent
environments if multiple threads try to modify
the list simultaneously. On the other hand, Vector is thread-safe, ensuring that
multiple threads can safely access and modify the
vector concurrently without causing data corruption.

Due to the synchronization overhead, Vector operations can be slower compared to


ArrayList. If thread safety is not a requirement,
ArrayList is generally preferred because it offers better performance.

In summary:

* ArrayList is not synchronized and provides better performance.


* Vector is synchronized and ensures thread safety.
===================================================================================
=====================

86) What is the difference between ArrayList and LinkedList?


ArrayList: It internally uses an array to store elements and provides fast
random access to elements based on their index.
Elements in an ArrayList are stored in contiguous memory locations, allowing for
efficient element retrieval using index-based operations
like get() and set(). However, inserting or removing elements in the middle of an
ArrayList can be slower, as it requires shifting subsequent
elements to accommodate the change.
LinkedList: It stores elements as a series of nodes, where each node holds a
reference to the next node in the sequence. LinkedList
provides efficient insertion and removal of elements, especially at the beginning
or end of the list, as it only requires updating the references of
adjacent nodes. However, accessing elements by index is slower compared to
ArrayList, as it requires traversing the list sequentially from
the beginning or end until the desired element is reached.
===================================================================================
=====================

87) Array vs List in java?


Array: An array is a fixed-size data structure that stores elements of the
same type in contiguous memory locations.
It provides direct access to elements based on their index and allows efficient
random access and modification. However, the size of
an array is fixed once it is created, and it cannot dynamically grow or shrink.

List: A list is a dynamic data structure that stores elements of any type and
can grow or shrink in size as needed. It provides more
flexibility compared to arrays as it allows for dynamic resizing and provides
convenient methods for adding, removing, and accessing
elements. Lists are implemented through various classes in Java's java.util
package, such as ArrayList, LinkedList, etc.
===================================================================================
=====================

You might also like