Java

Concurrency Interview Questions

Java
1. What is Thread in Java? ⤴ The thread is an independent path of execution. It’s way to take advantage of multiple CPU available in a machine. By employing multiple threads you can speed up CPU bound task. For example, if one thread takes 100 milliseconds to do a job, you can use 10 thread to reduce that task into 10 milliseconds. Java provides excellent support for multi-threading at the language level, and it’s also one of the strong selling points. 2. Describe synchronization in respect to multi-threading. What is synchronization? ⤴ Several threads access common data. In order to keep the data in consistent state the access to it has to be synchronized (i.e. some ordering of data access has to be imposed). 3. Explain different ways of using thread? ⤴ Create a long-runnin

Exception Interview Questions

Java
Java Interview - Exceptions 5 minutes read Exceptions List questions: What are Checked and Unchecked Exception? What are runtime exceptions? What is the difference between error and an exception? How to create custom exceptions? If I want an object of my class to be thrown as an exception object, what should I do? If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object? How does an exception permeate through the code? What are the different ways to handle exceptions? What is the basic difference between the 2 approaches to exception handling…1> try catch block and 2> specifying the candidate exceptions in the throws clause? When should you use which approach?

Multi Threading in Java

Java
Tables Introduction Thread vs Process in Java Multitasking vs Multithreading vs Multiprocessing vs parallel processing Life cycle of a Thread Thread priorities Create a thread in Java Thread creation by extending Thread class Thread creation by implementing Runable Interface Method: isAlive() and join() Synchronization Inter-thread Communication Introduction ⤴ Thread vs Process in Java ⤴ Both process and Thread are independent path of execution but one process can have multiple Threads. Every process has its own memory space, executable code and a unique process identifier (PID) while every thread has its own stack in Java but it uses process main memory and share it with other threads. Threads are also refereed as task or light

Map in Java

Java
Tables Map Overview HashMap TreeMap Hashtable LinkedHashMap Map Overview ⤴ There are 4 commonly used implementations of Map in Java SE - HashMap, TreeMap, Hashtable and LinkedHashMap. If we use only one sentence to describe each implementation, it would be the following: HashMap is implemented as a hash table, and there is no ordering on keys or values. TreeMap is implemented based on red-black tree structure, and it is ordered by the key. LinkedHashMap preserves the insertion order. Hashtable is synchronized, in contrast to HashMap. It has an overhead for synchronization. This is the reason that HashMap should be used if the program is thread-safe. HashMap ⤴ If the key of a HashMap is a self-defined object, then the equals() and hashCode() contr

List in Java

Java
Tables List Overview ArrayList vs. LinkedList vs. Vector Example ArrayList example LinkedList example Vector Performance of ArrayList vs. LinkedList List Overview ⤴ List, as its name indicates, is an ordered sequence of elements. When we talk about List, it is a good idea to compare it with Set which is a set of unique and unordered elements. The following is the class hierarchy diagram of Collection. From the hierarchy diagram you can get a general idea of Java Collections. ArrayList vs. LinkedList vs. Vector ⤴ From the hierarchy diagram, they all implement List interface. They are very similar to use. Their main difference is their implementation which causes different performance for different operations. ArrayList is implemented as a resizabl

Set in Java

Java
Tables Set Interface HashSet vs. TreeSet vs. LinkedHashSet Example TreeSet Example HashSet Example LinkedHashSet Example Set Interface ⤴ Set interface extends Collection interface. In a set, no duplicates are allowed. Every element in a set must be unique. You can simply add elements to a set, and duplicates will be removed automatically. HashSet vs. TreeSet vs. LinkedHashSet ⤴ HashSet is Implemented using a hash table. Elements are not ordered. The add, remove, and contains methods have constant time complexity O(1). TreeSet is implemented using a tree structure(red-black tree). The elements in a set are sorted, but the add, remove, and contains methods has time complexity of O(log(n)). It offers several methods to deal with the ordered set like

Arrays in java

Java
Array is a fundamental construct in any programming languages, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Tables Array Declaration Array Instantiation ArrayIndexOutOfBoundsException Java Array Default Values Iterating a Java Array Multidimensional Arrays Iterate a java multidimensional array Sort a Java array Copy a Java array The Arrays Class Array Declaration ⤴ Syntax for declaring an array variable in Java dataType[] arrayRefVar; // preferred way dataType arrayRefVar[]; // for accommodate C/C++ programmers, but not preferred, Array Instantiat

Collection in Java

Java
Tables Collection vs. Collections Class hierarchy of Collection Class hierarchy of Map Collection Classes Summary Table Code Example Collection vs. Collections ⤴ First of all, “Collection” and “Collections” are two different concepts. As you will see from the hierarchy diagram below: “Collection” is a root interface in the Collection hierarchy. but “Collections” is a class which provide static methods to manipulate on some Collection types. Class hierarchy of Collection ⤴ Class hierarchy of Map ⤴ Collection Classes Summary Table ⤴ Code Example ⤴ List<String> a1 = new ArrayList<String>(); a1.add("Program"); a1.add("Creek"); a1.add("Java"); a1.add("Java"); System.out.println("ArrayList Elements"); System.out.print("\t" + a

Types of Garbage Collection

Java
Tables Introduction Serial Garbage Collector Parallel Garbage Collector CMS Garbage Collector G1 Garbage Collector Java 8 Improvement Garbage Collection JVM Options Type of Garbage Collector to run GC Optimization Options Example Usage of JVM GC Options Introduction ⤴ Java has four types of garbage collectors. Each of these four types has its own advantages and disadvantages. Most importantly, the programmers can choose the type of garbage collector to be used by the JVM. We can choose them by passing the choice as JVM argument. Each of these types differ largely and can provide completely different application performance. It is critical to understand each of these types of garbage collectors and use it rightly based on the application

Garbage Collection in Java

Java
Tables Introduction Can the Garbage Collection be forced explicitly? Advantages of Garbage Collection JVM architecture Java Heap Memory How Java Garbage Collection Works? Java Garbage Collection GC Initiation Java Garbage Collection Process Finalization of Instances in Garbage Collection When an object becomes eligible for garbage collection? Garbage collection is responsible for removing objects from memory when they can never be used again. An object becomes eligible for garbage collection when there are no more references to it or its references have all gone out of scope. The finalize() method will run once for each object if/when it is rst garbage collected. Introduction ⤴ In Java, allocation and de-allocation of memory space for object

Java Reference Types

Java
There are four types of references in Java. Tables Strong Reference Weak Reference Soft Reference Phantom Reference Topic Related Strong Reference ⤴ These type of references we use daily while writing the code. Any object in the memory which has active strong reference is not eligible for garbage collection. class A { //Class A } public class MainClass { public static void main(String[] args) { A a = new A(); // Strong Reference - at this point, this object can't be garbage collected a = null; // Now, object to which 'a' is pointing earlier is eligible for garbage collection. } } If you make reference ‘a’ to point to null, then, object to which ‘a’ is pointing earlier will become eligible for garbage collection. Becau

Java Encapsulation

Java
Encapsulation is one of four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction. Encapsulation is the ability to package data and related behavior in an object bundle and control/restrict access to them (both data and function) from other objects. It is all about packaging related stuff together and hide them from external elements. We should not misunderstood that encapsulation is all about data hiding only. When we say encapsulation, emphasis should be on grouping or packaging or bundling related data and behavior together. When we design a class in OOP, the first principle we should have in mind is encapsulation. Group the related data and its behavior in a bucket. Primary benefit of encapsulation is, better maintainability.

Abstraction in Java

Java
Abstraction is the concept of exposing only the required essential characteristics and behavior with respect to a context. Tables What is Abstraction? When do you use Abstraction? Java Abstract Class When Should I use an Abstract class Abstraction Using Interface in Java More about Java Abstract Java Abstract Method Extending an Abstract Class Abstract class Implements an Interface Can an Abstract Class have Constructor in Java? Can an Abstract class be final in Java? Difference between Abstraction and Encapsulation in Java Abstraction: Things to Remember What is Abstraction? ⤴ Abstraction in Java or Object oriented programming is a way to segregate implementation from an interface (hiding internal details and showing functionality)

Polymorphism in Java

Java
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object. Tables Example How Polymorphism supported in Java References Example public interface Vegetarian {} public class Animal {} public class Deer extends Animal implements Vegetarian {} Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above example: A Deer IS-A Animal A Deer IS-A Vegetarian A ...

Java Inheritance

Java
Inheritance allows code reuse in Object oriented programming language. Inheritance can be defined as the process where one class requires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order. Inheritance in Java is supported using extends and implements keyword, extends keyword is used to inherit from another Java Class and allow to reuse functionality of Parent class. While implements keyword is used to implement Interface in Java. The class which inherits the properties of other is known as subclass (derived class, child class) as the class whose properties are inherited is known as superclass (base class, parent class). Tables extends Keyword The super keyword implements Keyword The...

Assert in Java

Java
Tables Assertion Advantage of Assertion Syntax of using Assertion Where not to use Assertion Note Static block Initializer block Assertion ⤴ Assertion is a statement in java. It can be used to test your assumptions about the program. While executing assertion, it is believed to be true. If it fails, JVM will throw an error named AssertionError. It is mainly used for testing purpose. Advantage of Assertion ⤴ It provides an effective way to detect and correct programming errors. Syntax of using Assertion ⤴ There are two ways to use assertion. First way is: assert booleanExpression; and second way is: assert booleanExpression : errorMessage; Note: booleanExpression, so that expression must return an boolean. Where not to use Assertion

Inner classes in java

Java
Tables Nested classes Syntax Inner Classes (Non-static Nested Classes) Member Inner Class Method-local Inner Class Anonymous Inner Class Static Nested Class Nested classes ⤴ In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class. Syntax ⤴ The syntax to write a nested class is given below. Here the class Outer_Demo is the outer class and the class Inner_Demo is the nested class. class Outer_Demo{ class Nested_Demo{ } } Nested classes are divided into two types: Non-static nested classes: These are the non-static members of a

Java Exceptions

Java
Tables What is an exception? When an exception can occur? Reasons for Exceptions Difference between error and exception Why to handle exception? Advantages of Exception Handling Types of exceptions Checked exceptions Unchecked exceptions Exception hierarchy User defined Exception subclass User custom exceptions - Points to remember try-catch - Exception handling What is try-catch block? Multiple catch Unreachable catch block Nested try statement What is finally block? Cases when the finally block doesn’t execute throw and throws in Java Important points to remember What is an exception? ⤴ An Exception can be anything which interrupts the normal flow of the program. When an exception occurs pr

File IO

Java
The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, Object, localized characters, etc. Tables Review java.io package classes Non-stream classes Stream classes File and Directory Class java.io.File Create file/directory Listing Directories Verifying Properties of a File/Directory Layered (or Chained) I/O Streams Read a file line by line Write a file line by line Append/Replace to an existing file Standard Stream The java.io package contains a relatively large number of classes, but, as you can see from these pictures following, t...

Static & Final Keywords in Java

Java, Uncategorised
Tables Java Static Java Static Variables Java Static Methods Java Static Class More discussion Java Static Import Java Final Keyword final arrays in Java Difference between C++ const variables and Java final variables More discussion Java Static ⤴ Java Static Variables ⤴ Java instance variables are given separate memory for storage. If there is a need for a variable to be common to all the objects of a single Java class, then the static modifier should be used in the variable declaration. Any Java object that belongs to that class can modify its static variables. Also, an instance is not a must to modify the static variable and it can be accessed using the Java class directly. Static variables can be accessed by java instance me

Modifier Types in Java

Java
Modifiers are keywords that you add to those definitions to change their meanings. In Java language, we have: Java Access Modifiers Non Access Modifiers To use a modifier, we include its keyword in the definition of a class, method, or variable. Tables Java Access Control Modifiers Access Modifiers for Top-level Classes & Interfaces Accessibility Modifiers for Members Access Control and Inheritance Non Access Modifiers static abstract final synchronized (methods) transient (fields) native (methods) volatile (fields) Java Access Control Modifiers ⤴ Access Modifiers are used at 2 access levels in Java. They are Top-level for Classes & Interfaces Member-level for Classes & Interfaces Access Modifiers for

Variable types in Java

Java
There are three kinds of variables in Java: Local variables Instance variables Class/static variables Tables Local variables Instance variables Class/static variables Local variables ⤴ Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block. Access modifiers cannot used for local variables. Local variables are visible only within the declared method, constructor or block. Local variable are implemented at stack level internally. There are no default value for local variables so local variables should be declared and initial value should be assigned before the first use. Ins

Operators in java

Java
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators Logical Operators Assignment Operators Misc Operators Tables The Arithmetic Operators The Relational Operators The Bitwise Operators The Logical Operators The Assignment Operators The Misc Operators Conditional Operator (?:) instance of Operator Precedence of Java Operators The Arithmetic Operators ⤴ + (addition) - (subtraction) * (multiplication) / (devision) % (modulus) ++ (increment) -- (decrement) The Relational Operators ⤴ == (equal to) != (not equal to) > (greater than) < (less than) >= (g

Data Types

Java
here are two data types available in Java: Primitive Data Types: numeric types, boolean type, and return Address type. Reference/Object Data Types Tables Primitive Data Types Reference Data Types Java literals Primitive Data Types ⤴ There are eight primitive data types supported by Java. Primitives always have a value, they can never be null. If a primitive type is not set to a value when a variable is defined, it takes a default value. For boolean values, this is false. For the others, this is a representation of zero, such as 0 for ints or 0.0f for floats. Primitive types are the basic building blocks of Java types. They are assembled into reference types. Reference types can have methods and be assigned to null. In addition to “normal” numbers, numeric

Object & Classes

Java
Java is an Object-Oriented Language. As a language that has Object Oriented feature, java supports the following fundamental concepts: Polymorphism Inheritance Encapsulation Abstraction Classes Objects Instance Method Message Parsing In this part, we will look into the concepts of Classes and Objects. Tables Objects in Java Classes in Java Constructor Creating an Object Source file declaration rules Java package Import statements Objects in Java ⤴ Objects have states and behaviors. State is stored in fields and behavior is shown via methods. So, methods operate on the internal state of an object and the object-to-object communication is done via methods. Classes in Java ⤴ A class is a blue print from which individual

JVM

Java
Tables JVM (Java Virtual Machine) JRE (Java Runtime Environment) JDK (Java Development Kit) Java JIT (Just-In-Time) References JVM (Java Virtual Machine) ⤴ JVM understand Java bytecode. Java Virtual Machine interprets the bytecode into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all things like garbage collection, array bounds checking, etc … JVM is platform dependent. The JVM is called “virtual” because it provides a machine interface that does not depend on the underlying operating system and machine hardware architecture. This independence from hardware and operating system is a cornerstone of the write-once run-anywhere value of Java programs. JRE (Java Runtime Environment) ⤴ The Java Runtim

Basic Syntax

Java
A Java program it can be defined as a collection of objects that communicate via invoking each other’s methods. Object - Objects have states and behaviors. Class - A class can be defined as a template/blue print that describes the behaviors/states that object of its type support. Methods - A methods is basically a behavior. A class can contain many methods. Instance Variables - Each object has its unique set of instance variables. An object’s state is create by the values assigned to these instance variables. Tables Example First Java Program Basic Syntax Java Identifiers Java Modifiers Java Variables Java Arrays Java Enums Inheritance Interfaces Example First Java Program ⤴ public class MyFirstJavaProgram { /* This is my first java

Java Features

Java
The prime reason behind creation of Java was to bring portability and security feature into a computer language. Beside these two major features, there were many other features that played an important role in moulding out the final form of this outstanding language. Those features are : Tables Simple Object Oriented Robust Platform Independent Secure Multi Threading Architectural Neutral Portable High Performance 1. Simple ⤴ Java is easy to learn and its syntax is quite simple, clean and easy to understand. Eg : Pointers and Operator Overloading are not there in java but were an important part of C++. 2. Object Oriented ⤴ In Java, everything is Object which has some data and behavior. Java can be easily extended as it is based on Object Model. 3. Ro