0% found this document useful (0 votes)
16 views26 pages

Java Interview Questions

The document contains a comprehensive list of 100 interview questions related to Java, covering fundamental concepts such as Java's features, object-oriented programming principles, data types, exception handling, and more. Key topics include platform independence, encapsulation, inheritance, polymorphism, and the differences between various Java components like JDK, JVM, and JRE. It serves as a valuable resource for individuals preparing for Java-related interviews.

Uploaded by

ksashokbhupathy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views26 pages

Java Interview Questions

The document contains a comprehensive list of 100 interview questions related to Java, covering fundamental concepts such as Java's features, object-oriented programming principles, data types, exception handling, and more. Key topics include platform independence, encapsulation, inheritance, polymorphism, and the differences between various Java components like JDK, JVM, and JRE. It serves as a valuable resource for individuals preparing for Java-related interviews.

Uploaded by

ksashokbhupathy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Java 100 Interview Questions

Q1: What is Java?

Java is a versatile, object-oriented programming language, developed by Sun


Microsystems. It has automatic memory management and a robust standard
library, supports multithreading, and excels at building scalable applications.

Q2: Why do we go for Java?

There are various reasons why you should go for Java. Some of them are:

 It is platform-independent and open-source.

 It runs multiple applications at once.

Q3: What are the main features of Java?

1. Platform independent

2. Open source

3. Multithreading

4. More secure

5. Portable

Q4: What is platform-independent?

Java has “write once, run anywhere”, which means that during the
compilation, the Java program converts into byte code. Using byte code, we
can run the application on any platform, such as Windows, Mac, Linux, etc.
This is known as being platform-independent.

Q5: What is meant by open-source?

A program in which source code is available to the general public for use
and/or modification from its original design at no cost is called open source.

Q6: What types of tools are used to execute Java?

 Notepad

 Net bean

 Eclipse

 J Developer(oracle)

1
 RAD(IBM)

Q7: What are the differences between the JDK, JVM, and JRE?

JDK:

 Java Development Kit.

 If we want to run any applications in Java, we need JDK to be installed.

 JDK versions: 1.0 to 1.10.

JRE:

 Java Runtime Environment.

 It is a predefined class file (i.e.) a library file).

JVM:

 Java Virtual Machine.

 It is mainly used to allocate memory and compile.

Q8: What is meant by OOPS?

Object-Oriented Programming Structure (OOPS) is a method of


implementation in which programs are organized as a collection of objects,
classes, and methods.

Q9: What are the coding standards used in Java?

 Pascal notation: Each and every word of the first letter should be in
capital letters. Example: GuviGeek

 Camel notation: The first word should be small, and every word of
the first letter should be capitalized. Example: guviGeek

Q10: What do you mean by class, method, or object?

Class: A class is nothing but a collection of methods or objects.

Method: A method is nothing but a set of actions to be performed.

Object: Object is the run-time memory allocation.

Using objects, we call any methods.

2
Q11: What is meant by encapsulation?

Encapsulation is one of the fundamental principles of object-oriented


programming (OOP) that refers to the bundling of data (attributes or fields)
and methods (functions or procedures) that operate on that data into a
single unit called a class.

Q12: What are the datatypes used in Java?

 byte

 short

 int

 long

 float

 double

 boolean

 char

 String

Q13: What is the byte size and range of int datatypes?

 The size of a byte is 1 byte (8-bit)

 Range formula =[-2^(n-1)] to [(2^(n-1))-1] for int n=32.

Q14: What is mean by Wrapper class?

Classes of data types are called wrapper classes and are used to convert any
data type into an object. All classes and wrapper classes’ default value is
Null.

Q15: What is the main use of the scanner class?

The main use of the scanner class is to get input from the user at runtime.

Q16: What are the methods available in the Scanner Class?

 nextByte();

 nextShort();

 nextInt();

3
 nextLong();

 nextFloat();

 nextDouble();

 next().charAt(0);

 next();

 nextLine();

 nextBoolean();

Q17: What is meant by inheritance?

Inheritance is a fundamental concept in object-oriented programming (OOP)


that allows a new class (subclass or derived class) to inherit properties and
behaviors (data fields and methods) from an existing class (superclass or
base class). Inheritance creates a hierarchical relationship between classes,
facilitating code reuse and the creation of more specialized classes based on
existing ones.

Q18: What are the ways to access the methods or data from another class?

We can access the other class methods either by creating an object or using
extends keyword.

Q19: What is meant by polymorphism?

Poly means many and morphism means forms. Polymorphism is a


fundamental concept in object-oriented programming (OOP) that allows
objects of different classes to be treated as objects of a common superclass.

Q20: What are the differences between method overloading and overriding?

Method overloading(static binding/compile time polymorphism):

 Class-same

 Method-same

 Argument-differ based on datatype, order, number

Method overriding(dynamic binding/run time polymorphism):

 Class name-differ(using extends)

 Method-same

4
 Argument-same

Q21: What are the types of inheritance?

 Single Inheritance

 Multilevel Inheritance

 Multiple Inheritances

 Hybrid Inheritance

 Hierarchical Inheritance

Q22: Why multiple inheritance is not supported in Java?

 Priority problem

 Compilation error/syntax error

(i.e) if both parent classes have the same method name it will get a priority
problem so it doesn’t work in Java.

Q23: What are the differences between Multiple and Multilevel inheritance?

Multiple inheritance:

 A combination of more than one parent class directly supported one


child class.

 It won’t work in Java due to a priority problem.

Multilevel inheritance:

 A combination of more than one parent class and child class using a
tee-level structure.

 It works in Java.

Q24: What is meant by access specifier?

In Java, access specifiers are keywords that determine the visibility or


accessibility of classes, fields (variables), methods, and constructors in
different parts of your code. There are 4 main access specifiers:

Public
Private
Protected
Default

5
Q25: What are the differences between public and protected?

Public: It is global-level access( same package + different package).


Members (classes, methods, fields) marked as public are accessible from
anywhere in the code, both within the same class and from other classes.

Protected: Inside package + outside Package (Extends). Members are


marked as protected accessible within the same class, subclasses (even if
they are in different packages), and other classes in the same package. They
are not accessible from classes in different packages that are not subclasses.

Q26: What is meant by Abstraction?

Abstraction is a core concept in object-oriented programming (OOP) that


focuses on simplifying complex reality by modeling classes based on their
essential attributes and behaviors. It involves hiding the complex
implementation details of an object while exposing a simplified and well-
defined interface for interaction.

Q27: What are the types of Abstraction?

1. Partially abstraction(abstract class).

2. Fully abstraction(interface).

Q28: Can we create an Object for the Abstract class?

No, we can’t create objects for abstract classes.

Q29: What is meant by Interface?

In Java, an interface is a reference type that serves as a contract for classes


that implement it. It defines a set of method signatures (without
implementations) that must be provided by any class that claims to
implement the interface.

Q30: What are the differences between Abstract and Interface?

Abstract class:

 It is partially abstract.

 It supports both abstract methods and non-abstract methods.

 It uses the “extends” keyword.

 Here “public abstract” have to mention.

 We can use whatever access specifier we want.

6
Interface:

 It is fully abstract.

 It supports only abstract methods.

 It uses the “implement” keyword.

 “public Abstract” is default no need to mention it.

 Here we use only public( access specifier).

Q31: What is meant by String?

Collections of characters or words enclosed with double quotes are called


String.

Example: “guvigeek”.

Q32: What are the methods available in a string?

 Equals();

 Equalsignorecase();

 contains();

 split();

 toUpperCase();

 toLowerCase();

 subString();

 isEmpty();

 identifyHashCode();

 startsWith();

 endsWith();

 CompareTo();

 charAt();

 indexOf();

 lastIndexOf();

 replace();

7
Q33: What is meant by constructor?

In Java, a constructor is a special type of method that is automatically called


when an object of a class is instantiated (created). It is used to initialize the
newly created object and set its initial state.

Q34: What are the types of constructors?

 Parameterized constructor

 Non parameterized constructor

Q35: Do constructors have any return type?

No, the constructor can’t have any return type.

Q36: Write a syntax for creating a constructor.

Access_specifier classname(){
}

Q37: What are the rules for defining a constructor?

 The class name and constructor name must be the same.

 It doesn’t have any return type.

Q38: Why a return type is not allowed for the constructor?

A constructor is not directly called by your code, it’s called by memory


allocation and object initialization in the run time. Its return value is opaque
to the user so we can’t mention it.

Q39: Can we declare the constructor as ‘private’?

Yes, we can declare the constructor as private.

Q40: Why a compiler-given constructor is called a default constructor?

If we won’t pass the constructor explicitly it will take the default constructor.

Q41: What is constructor chaining and how can it be achieved in Java?

 The process of calling one constructor from another constructor with


respect to the current object is called constructor chaining.

 By using this() we can achieve constructor chaining.

8
Q42: What are the differences between this() and super()?

 this() is used to call the class-level constructor.

 super() is used to call the constructor in the parent class.

Q43: What is the super-class of all Java?

An object is the super-class of all Java.

Q44: What are the types of variables?

 Local level variable.

 Class level variable.

 Super level variable.

Q45: What is meant by local variable, instance variable, class/static variable?

 Static Variable – It is used to share the same variable or method of a


given class.

 Local Variable – It will declare below the main method.

 Class variable- – It will access only within the class.

Q46: What is meant by static keyword in Java?

The static keyword is mainly used for memory management and is used to
share the same variable or method of a given class.

Q47: Can we override static methods in Java?

No, we can’t override the static method because it is part of a class rather
than an object.

Q48: Can we overload static methods in Java?

Yes, we can overload the static method in Java.

Q49: What is meant by static variable?

When a variable is declared as static, then a single copy of the variable is


created and shared among all objects at the class level. Static variables are
essentially, global variables. All the instances of the class share the same
static variable.

9
Q50: What is meant by static method?

Static methods in Java belong to the class(not to an object). They use no


instance variables and will usually take the input from the parameters and
perform an action on it, then return some result.

Q51: What is meant by the final keyword and what’s happened when we
declare final as in class, method, and variable?

 Final is a non-access modifier applicable only to a variable, a method,


or a class.

 When a variable is declared with the final keyword, its value cant be
modified essentially a constant.

 When a method is declared as final we can prevent method overriding.

 When a class is declared as final we can prevent inheritance.

Q52: What is the difference between the final and finally keyword?

Final:

 Final variable can’t be modified.

 Final method can’t be overridden.

 Final class can’t be inherited.

Finally:

Finally part will execute the important code whether the exception is handled
or not.

Q53: Where do local, static, and class variables stored in JVM?

 Static variables are stored in the permGen section of heap memory.

 Local variables are stored in the stack.

 Class variables are stored in heap memory.

Q54: What is an Exception?

In Java, an exception is an event that occurs during the execution of a


program and disrupts the normal flow of instructions. It is an instance of a
class that is derived from the Throwable class (or its subclasses).

10
Q55: What are the types of Exceptions?

 Unchecked exception(Run time exception)

 Checked exception(Compile time exception)

Q56: What are the differences between checked exceptions and unchecked
exceptions?

Unchecked exception: It will occur at the Run time exception.


Checked exception: Checked exception will occur at the Compile time
exception.

Q57: What is the super-class for Exception and Error?

Throwable Exception.

Q58: Can we have a try block without a catch block?

No, we haven’t a try block without catch block.

Q59: Can we write multiple catch blocks under a single try block?

Yes, we write multiple catch blocks under the single try block.

Q60: How to write user-defined exceptions or custom exceptions in Java?

Access_specifier method_name throws customException { throw new


customException();
}

Q61: What are the different ways to print exception messages on the
console?

ref.printStackTrace() method is used to print the exception message from the


console.

Q62: What are the differences between final finally and finalize in Java?

Final:

 A final class variable whose value cannot be changed.

 A final is declared as class level, they cannot be inherited.

 If the final is declared as method level, they cannot be overridden.

11
Finally:

 It’s a block of statements that definitely executes after the try-catch


block.

 If the try block fails means, the final block will execute once.

Finalize:

It will clean up processing memory space.

Q63: What are the differences between throw and throws?

Throw:

 Throw is a keyword, we can through any exception inside the method.

 At a time we can throw only one exception.

Throws:

 Throws is a keyword, it is used to declare the exception (at the method


level).

 At a time we can declare more than one exception.

Q64: Explain Java Exception Hierarchy.

Exception

1. Unchecked exception(Run time exception)

 ArithmaticException

 NullPointException

 InputMismatchException

 ArrayIndexOutOfBoundExcepion

 StringIndexOutOfBoundExcepion

 IndexOutOfBoundExcepion

 NumberFormatException

2. Checked exception(Compile time exception)

 IOException

 SQLException

12
 FileNotFoundException

 ClassNotFoundException

Q65: What is meant by throw and throws?

Throw Throws

Checked Exceptions can not be


Checked Exceptions can be propagated using throws
propagated using Throw only

The throw is followed by an instance Throws is followed by a class

A throw is used within the method The throws keyword is used to declare an exception

A throw keyword is used to declare an Multiple exceptions can be declared using throws: Public v
exception method()throws IO exception, SQL Exception

Multiple exceptions can be declared using throws Ex: Publi


We can only throw one exception
method()throws IO exception, SQL Exception

Q66: What is meant by an array?

An array is a data structure in programming that stores a fixed-size collection


of elements of the same data type. Each element in an array is accessed by
its index, which is a numeric value that represents its position in the array.

Q67: What are the advantages and disadvantages of an array?

Advantage:

In a single variable, we can store multiple values.

Disadvantages:

 It supports only similar data types.

13
 It is a fixed-size one.

 Memory wastage is high.

Q68: Write a code to initialize an array.

 Initializing without assigning any values:

Datatype refName[]= new Datatype[size];

class HelloWorld

public static void main(String[] args)

// Initializing an array of integers with specific values

int[] array= new int[5];

array for(int i = 0; i <5; i++)

System.out.println(array[i]);

Q69: Can we change the memory size of an array after initialization?

No, we can’t change the memory size of an array after initialization.

Q70: What is a collection?

Collection Framework is a combination of classes and interfaces, which is


used to store and manipulate the data in the form of objects. It provides
various classes such as ArrayList, Vector, Stack, and HashSet, etc., and
interfaces such as List, Queue, Set, etc. for this purpose.

 It will support dissimilar data types.

 It is dynamic memory allocation.

 No memory wastage like an array.

Q71: What is the difference between ArrayList and Vector?

14
ArrayList Vector

ArrayList is not synchronized i.e.executed parallel Vector is Synchronous ( exe

Not Thread safe Vector is Synchronous ( exe

ArrayList increases its size by 50% of the array size Vector is a legacy class

Vector increases its size by doubling theArray size Vector is thread-safe

Q72: What is the difference between ArrayList and LinkedList?

LinkedList:

 Insertion and deletion is the best one.

 Searching/retrieving is the worst.

 It makes performance issue.

ArrayList:

 In Arraylist retrieve/searching is the best one

 In ArrayList deletion and insertion is the worst one because if we


delete/insert one index value after all the index move to
forward/backward.

 It makes performance issue.

Q73: How to convert Array to List and List to Array?

 Native Method

 Using Arrays.asList() Method

 Using Collections.addAll() Method

 Using Java 8 Stream API

 Using Guava Lists.newArrayList() Method

Q74: Describe the Collections type hierarchy What are the main interfaces?

Main Interface:

 List

15
 Set

 Map

The hierarchy is as follows:

List:

 ArrayList

 LinkedList

 Vector

Set:

 HashSet

 LinkedHashSet

 TreeSet

Map:

 HashMap

 LinkedHashMap

 Hashtable

 TreeMap

 ConcurrentHahMap

Q75: What is the difference between a set and a List?

Set:

 It is a value-based one.

 It prints in random order.

 It won’t allow duplicates.

List:

 It is an Index based one.

 It prints in insertion order.

 It allows duplicates.

16
Q76: What is the difference between HashSet and TreeSet?

Hash set is implemented using HashTable The tree set is implemented using a tree structure.

The tree set does not allow the null object. It throws t
HashSet allows a null object
pointer exception.

Hash set use equals method to compare two


The tree set allows a heterogeneous object
objects

Hash set doesn’t now allow a heterogeneous


Hash set use the equals method to compare two obje
object

HashSet does not maintain any order TreeSet maintains an object in sorted order

Q77: How to convert List into Set?

By addAll() we can convert List into set.

Q78: What is a map?

 A map is an interface that is present in java.util package.

 It is used to represent the mapping between key and value.

 It is a key and value pair.

 Here key+value is one entry.

 Key ignore the duplicate value and value allow the duplicate.

Q79: What is the difference between Hash Map and Hash Table?

HashMap Hashtable

5) We can make the HashMap synchronized by calling this Hashtable is synch


code Map m = Collections.synchronizedMap(hashMap); and can be shared

2) HashMap allows one null key and multiple null values. Hashtable doesn’t

17
value.

3) HashMap is a new class introduced in JDK 1.2. Hashtable is a lega

4) HashMap is fast. Hashtable is slow.

Hashtable is interna
The enumerator in Hashtable is not fail-fast.
can’t be unsynchro

Hashtable is traver
6) HashMap is traversed by Iterator.
and Iterator.

7) Iterator in HashMap is fail-fast. Enumerator in Hash

8) HashMap inherits AbstractMap class. Hashtable inherits D

Q80: What is the difference between a set and a Map?

Set:

 It is a value-based one.

 It prints in random order.

 It won’t allow duplicates.

Map:

 It is a key and value pair.

 Here key+value is one entry.

 Key ignore the duplicate value and value allow the duplicate.

Q81: Can we iterator the list using normal for loop?

Yes, we can iterator the list using both normal and by using enhanced for
loop.

Q82: What are the methods available in the list but not in the set?

 indexOf();

18
 get();

 lastIndexOf();

Q83: Explain about user-defined Map.

 It is a key and value pair. Here key+value is one entry.

 Key ignore the duplicate value and value allow the duplicates

 Syntax: Map<String,String> map=new HashMap<String,String>();

Q84: How much null allows in the below maps:

HashMap :k?,v?
LinkedHashMap:k?,v?
TreeMap :k?,v?
HashTable :k?,v?

 HashMap :k-1 null,v- n null

 LinkedHashMap:k-1 null,v- n null

 TreeMap :k-ignore null,v- ignore null

 HashTable :k-ignore null,v- ignore null

Q85: How to Iterate Map?

 Iterating over entries using For-Each loop.

 Iterating over keys or values using the keySet() and values() method
using for-each loop.

 Iterating using stream() in JAVA 8.

 Using entrySet()

 Using Iterator through a Maps.

Q86: What is the return type of entrySet?

Set<Entry<key,value>>

Q87: Write the methods to get the key only and value only?

 For key only the keySet() method is used.

 For value, only values() method is used.

Q88: What is meant by File? In which package it is available?

19
The File is a class and it is used to perform the file operation. It is available in
java.io package.

Q89: What are the methods available in a File ?

 mkdir();

 mkdirs();

 list();

 createNewFile();

 isDirectory();

 isFile();

 isHidden();

Q90: While creating a file if we do not mention the format then under which
format will it save the file?

If we do not mention the file format it will automatically take the format as a
file.

Q91: What are the differences between the append and updating the file?

For updating the file: It will replace the old content of a file.

For appending the file: It will add the content at the end of a file.

Q92: What is meant by Enumerator, Iterator, and List Iterator?

Enumeration: It is a legacy interface and it is used before jdk version 1.4(old


version).

Iterator: It is an Interface used to iterate the class ArrayList, LinkedList.

List Iterator: It is an interface used for iterating the list only and has
backward direction special features(go back to the previous element).

Q93: Difference between Enumurator, Iterator, and List Iterator?

Property Enumeration Iterator Lis

It can be applied to any It can be


1. Where It can be applied only to the collection interface. interface
we can legacy classes.

20
apply?

2. Is it a Yes (introduced in 1.0 V). No (introduced in1.2 V). No (intro


legacy?

Bidirecti
Single direction, i.e we can
Single direction, i.e we can element
traverse elements present in
traverse elements present in both in f
the collection only in the
the collection only in the direction
3. Allowed forward direction.
forward direction.
Movement

We can p
We can perform read and
4.Allowed We can only perform the read add, and
remove operation.
Operation operation.

By calling iterator() method


By callin
present in any collection
By calling elements() method present
interface.
5. How can present in the vector class.
we get it?

Q94: What are the methods available in Enumerator, Iterator and List
Iterator?

Enumerator Methods:

 hasMoreElements();

 nextElement();

Iterator Methods:

 hasNext();

 next();

 remove();

21
ListIterator Methods:

 hasNext();

 next();

 remove();

 hasPrevious();

 previous();

Q95: Explain JDBC connection steps.

 Import JDBC packages.

 Load and register the JDBC driver.

 Open a connection to the database.

 Create a statement object to perform a query.

 Execute the statement object and return a query resultset.

 Process the resultset.

 Close the resultset and statement objects.

 Close the connection.

Q96: What are control statements?

Statements which has control over the loop or program are called control
statements. Example: if, if-else.

Q97: What are the differences between break and continue?

Break:

 It will terminate where the condition becomes true.

 It will not be used inside the loop other than the switch case.

Continue:

 It will skip the condition become true and keep executing the loop.

 It will not be used inside the loop

Q98: What is the difference between a while and a do-while loop?

While is an entry-controlled loop whereas do-while is an exit-controlled loop.

22
Q99: What is the difference between an if and an if-else loop?

if loop: execute only when the condition becomes true.

if-else: execute the else part when the condition becomes false and execute
the if part when the condition becomes true.

Q100: What is the difference between an Immutable and mutable string?

Immutable string:

 We can store more duplicate values in the same memory

 We can’t change the value in memory

 In concordnation, we have to create a new memory

Mutable string:

 We can’t store duplicate values in the same memory

 We can change the value in memory

 In concordnation, it takes the same memory

Q101: What is the difference between Removeall() and Retainall()?

removeAll(): removeAll() is a method, it is used to compare both the list and


remove all the list1 values in list 2

retainAll(): retainAll() is a method, it is used to compare both the list and


print the common values.

Q102: What is the difference between a Literal String and a Non-literal


string?

Literal String:

 It is stored inside the heap memory(string pool or string constant)

 It shares the memory if the same value (duplicate value)

Non-Literal String:

 It is stored in the heap memory

 It creates a new memory every time even if it’s a duplicate value(same


value)

Q103: What is the difference between Heap and stack memory?

23
Heap memory:

 Heap for dynamic memory allocation.

 Memory access is slow.

Static memory:

 Stack is used for static memory allocation.

 Variables allocated on the stack are stored directly into the memory
and access to this memory is very fast.

Q104: What is the default Package in Java?

java.lang

Q105: What is the difference between equals() & hashcode()?

Equals: Used to compare the two strings.

Hashcode: Used to return the address where it is stored.

Q106: Difference between a string buffer and a string builder?

String Buffer String Builder

It is asynchronized i.e., multiple threads


It is synchronized i.e. only one thread can
can enter the object at any point of
enter an object at any point of time.
time.

It is Thread safe. Multiple threads can’t enter It is not Thread safe i.e. multiple
the object simultaneously. OneThread has to threads can enter the object parallel.
wait until another thread has finished with Threads don’t have to wait until one
them. thread is finished.

Because of the above reason String Bufferis String builder is faster as a result of
slower this.

Q107: What is a String Constant pool?

String Constant Pool is the memory space in heap memory specially


allocated to store the string objects created using string literals. In String
Constant Pool, there will be no two string objects having the same
content/value.

24
Whenever you create a string object using string literal, JVM first checks the
content of the object to be created. If an object in the string constant pool
has the same content, then it returns the same reference of that object. It
doesn’t create a new object. If the content is different from the existing
objects then only it creates a new object.

Q108: Difference between Collection and Collections?

Collection Collections

A collection is an interface in java.utilpackage Collections is a utility clas

It is used to represent a group of individual objects as a It defines several utility m


single unit operate on collection.

It contains abstract and default methods. It has static


methods from Java 8 onwards It has only static methods

Add(), remove(), clear(), contains() andsize() are the Collections class sorts and
important methods in collection collection elements

Q109: Why do we need to go for collection when there is already an Array


concept?

In an array, we can store only similar types of objects. Array size is fixed and
cannot provide readymade methods for user requirements such as
searching, sorting, etc. Therefore we use collection where heterogenous or
dissimilar objects can be stored. In a collection, the size can be changed
dynamically as per the need and it also contains readymade methods.

Q110: Why do we need to go for collection when there is already an Array


concept?

We can use collections.SynchronisedList(refName of array)method to


synchronize arraylist in Java:

public class synchronizeArrayList{ public static void main(string[]args){

//Non-synchronized array list

List<String> language= new arrayList<String>(); language.add(“Java”);

language.add(“python”); language.add(“SQL”);

25
//synchronizing arraylist in Java

language=collections.synchronizedList(language);

//use synchronize block to avoid non-deterministic behaviour


synchronized(language){

Iterator<String>itr= language.iterator(); While(itr.hasNext())


{ System.out.println(itr.hasNext());

}}}

26

You might also like