<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ interview questions - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ interview questions - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 11 Jun 2026 23:15:12 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/interview-questions/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use Object-Oriented Programming in Python – Key OOP Concepts and Interview Questions for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ OOP is a crucial concept that every developer should grasp, especially when getting ready for job interviews. It helps you organize code into modular and reusable sections, which simplifies the development, maintenance, and scaling of software applic... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/object-oriented-programming-in-python-interview-questions/</link>
                <guid isPermaLink="false">671aeea7c5f85f75b4b243e8</guid>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Casmir Onyekani ]]>
                </dc:creator>
                <pubDate>Fri, 25 Oct 2024 01:04:39 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1729679277832/18ab2f5b-0636-44e7-b063-0773e5039fb0.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>OOP is a crucial concept that every developer should grasp, especially when getting ready for job interviews. It helps you organize code into modular and reusable sections, which simplifies the development, maintenance, and scaling of software applications.</p>
<p>In this article, I'll use some common interview questions to simplify the key OOP concepts, providing clear explanations and code snippets to boost your confidence for your next interview.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-oop">What is OOP?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-the-four-main-principles-of-oop">What are the Four Main Principles of OOP</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-method-overloading">What is Method Overloading?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-constructor-in-oop">What is a Constructor in OOP?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-destructor-in-oop">What is a Destructor in OOP?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-class-in-oop">What is a Class in OOP?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-an-object-in-oop">What is an Object in OOP?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-static-method">What is a Static Method?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-difference-between-a-class-variable-and-an-instance-variable">What is the Difference Between a Class Variable and an Instance Variable?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-does-python-support-multiple-inheritance">Does Python Support Multiple Inheritance?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-difference-between-an-abstract-class-and-an-interface">What is the Difference Between an Abstract Class and an Interface?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-oop">What is OOP?</h2>
<p>Object-Oriented Programming (OOP) is a way of writing software that revolves around objects<strong>.</strong> These objects can store data and their actions (methods). Rather than concentrating solely on processes and logic, OOP encourages you to structure your code around these objects.</p>
<p>This approach makes it easier to create modular, reusable, and scalable software designs.</p>
<h2 id="heading-what-are-the-four-main-principles-of-oop">What are the Four Main Principles of OOP</h2>
<p>The four pillars of OOP are:</p>
<ul>
<li><p>Encapsulation</p>
</li>
<li><p>Abstraction</p>
</li>
<li><p>Inheritance</p>
</li>
<li><p>Polymorphism</p>
</li>
</ul>
<h3 id="heading-what-is-encapsulation-and-why-is-it-important">What is Encapsulation, and Why is it Important?</h3>
<p>Encapsulation helps protect the data inside an object. Think of it like keeping certain details private, allowing only controlled access to them.</p>
<p>That is, instead of directly changing or viewing the data, you interact with it through specific methods. This ensures that the data is safe from unintended changes.</p>
<p>Example:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, age</span>):</span>
        self.name = name
        self.__age = age  <span class="hljs-comment"># Private attribute (notice the double underscore)</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_age</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.__age  <span class="hljs-comment"># A method to access the private age attribute</span>
</code></pre>
<p>In this example, <code>__age</code> is kept private, and we can only get the age using the <code>get_age()</code> method. This ensures that <code>age</code> is not accidentally modified in a way that could cause issues.</p>
<h3 id="heading-what-is-abstraction-and-how-is-it-different-from-encapsulation">What is Abstraction, and How is it Different from Encapsulation?</h3>
<p>Abstraction allows you to show only the important details of an object or system, while hiding the complex parts that the user doesn't need to see.</p>
<p>Think of it like driving a car, you only need to know how to use the steering wheel, gear, gas pedal, and brakes to drive. You don’t need to understand how the engine works internally.</p>
<p>In programming, abstraction helps you focus on what something does, not how it works inside.</p>
<p><strong>Example:</strong> Let’s say you’re using a <code>Car</code> class. The abstraction lets you start the car without knowing all the mechanical details:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">start_engine</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">"Engine started"</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">drive</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">"Car is driving"</span>)

<span class="hljs-comment"># The user interacts with the car without knowing how the engine works</span>
my_car = Car()
my_car.start_engine()
my_car.drive()
</code></pre>
<p>Here, you don’t need to worry about how the <code>start_engine</code> method works internally, you just use it!</p>
<p>Key Difference:</p>
<ul>
<li><p>Encapsulation: Focuses on bundling data and restricting access.</p>
</li>
<li><p>Abstraction: Focuses on hiding complexity and exposing only necessary details.</p>
</li>
</ul>
<h3 id="heading-what-is-inheritance-in-oop">What is inheritance in OOP?</h3>
<p>Inheritance lets you create a new class by using an existing class. The new class (called the child class) gets all the attributes and methods from the existing class (called the parent class).</p>
<p>This allows you to reuse code and build upon what you've already written without starting from scratch.</p>
<p>Example:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Parent class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vehicle</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, brand</span>):</span>
        self.brand = brand  <span class="hljs-comment"># This is an attribute (brand)</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">start</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">f"<span class="hljs-subst">{self.brand}</span> vehicle started"</span>)  <span class="hljs-comment"># This is a method</span>

<span class="hljs-comment"># Child class that inherits from Vehicle</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span>(<span class="hljs-params">Vehicle</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, brand, model</span>):</span>
        super().__init__(brand)  <span class="hljs-comment"># Inherit the brand from Vehicle (parent class)</span>
        self.model = model  <span class="hljs-comment"># Add a new attribute specific to Car</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">display_info</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">f"Car: <span class="hljs-subst">{self.brand}</span>, Model: <span class="hljs-subst">{self.model}</span>"</span>)

<span class="hljs-comment"># Creating an object of the Car class</span>
my_car = Car(<span class="hljs-string">"IVM"</span>, <span class="hljs-string">"Ikenga"</span>)
my_car.start()  <span class="hljs-comment"># Output: IVM vehicle started</span>
my_car.display_info()  <span class="hljs-comment"># Output: Car: IVM, Model: Ikenga</span>
</code></pre>
<p>In this example, <code>Vehicle</code> is the parent class, and <code>Car</code> is the child class. <code>Car</code> inherits the <code>brand</code> and <code>start()</code> method from <code>Vehicle</code>, but it also has its own attribute (<code>model</code>) and method (<code>display_info()</code>).</p>
<p>Inheritance makes it easier to create more specialized classes (like <code>Car</code>) based on a general class (like <code>Vehicle</code>).</p>
<h3 id="heading-what-is-polymorphism">What is Polymorphism?</h3>
<p>Polymorphism allows different types of objects to respond to the same action in their own unique way. It’s like how both cats and dogs make sounds, but each makes a different sound when you ask them to!</p>
<p>Polymorphism can be achieved through method overriding (when a child class has a method with the same name as a method in its parent class but provides its own implementation).</p>
<p>Example of method overriding:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Parent class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sound</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Some generic animal sound"</span>

<span class="hljs-comment"># Child class Dog overriding the sound method</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>(<span class="hljs-params">Animal</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sound</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Bark"</span>

<span class="hljs-comment"># Child class Cat overriding the sound method</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span>(<span class="hljs-params">Animal</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sound</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Meow"</span>

<span class="hljs-comment"># Creating instances of each class</span>
my_dog = Dog()
my_cat = Cat()

<span class="hljs-comment"># Calling the sound method</span>
print(my_dog.sound())  <span class="hljs-comment"># Output: Bark</span>
print(my_cat.sound())  <span class="hljs-comment"># Output: Meow</span>
</code></pre>
<p>In this example:</p>
<ul>
<li><p><code>Animal</code> is the parent class, and it has a method called <code>sound()</code>.</p>
</li>
<li><p>Both <code>Dog</code> and <code>Cat</code> are child classes of <code>Animal</code>, and they override the <code>sound()</code> method to provide their own specific sound.</p>
</li>
<li><p>When you call <code>sound()</code> on a dog, it returns "Bark", and for a cat, it returns "Meow."</p>
</li>
</ul>
<p>This is polymorphism in action, different objects (Dog, Cat) responding to the same method (<code>sound()</code>) in different ways.</p>
<p>It's a powerful tool that helps in creating flexible and easy-to-maintain code!</p>
<h2 id="heading-what-is-method-overloading">What is Method Overloading?</h2>
<p>Method overloading happens when you create multiple methods with the same name, but with different types of parameters inside the same class.</p>
<p>While Python doesn't support traditional method overloading, you can mimic similar behavior by using default arguments/parameters or handling multiple arguments inside the method.</p>
<p>Example 1: Using Default Parameters</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Calculator</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span>(<span class="hljs-params">self, a, b=<span class="hljs-number">0</span>, c=<span class="hljs-number">0</span></span>):</span>
        <span class="hljs-keyword">return</span> a + b + c

<span class="hljs-comment"># Create an instance of Calculator</span>
calc = Calculator()

<span class="hljs-comment"># Call the add method with different numbers of arguments</span>
print(calc.add(<span class="hljs-number">5</span>))        <span class="hljs-comment"># Output: 5 (a = 5, b and c default to 0)</span>
print(calc.add(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>))    <span class="hljs-comment"># Output: 15 (a = 5, b = 10, c default to 0)</span>
print(calc.add(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>, <span class="hljs-number">15</span>))<span class="hljs-comment"># Output: 30 (a = 5, b = 10, c = 15)</span>
</code></pre>
<p>In this example, the <code>add</code> method has one required parameter (<code>a</code>) and two optional parameters (<code>b</code> and <code>c</code>) with default values of <code>0</code>.</p>
<p>By changing the number of arguments you pass when calling the method, you can achieve a method overloading effect.</p>
<p>Example 2: Using <code>*args</code> for Dynamic Parameters</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Calculator</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span>(<span class="hljs-params">self, *args</span>):</span>
        <span class="hljs-keyword">return</span> sum(args)

<span class="hljs-comment"># Create an instance of Calculator</span>
calc = Calculator()

<span class="hljs-comment"># Call the add method with different numbers of arguments</span>
print(calc.add(<span class="hljs-number">5</span>))           <span class="hljs-comment"># Output: 5 (adds just one number)</span>
print(calc.add(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>))       <span class="hljs-comment"># Output: 15 (adds two numbers)</span>
print(calc.add(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>, <span class="hljs-number">15</span>))   <span class="hljs-comment"># Output: 30 (adds three numbers)</span>
</code></pre>
<p>In this example, the <code>add</code> method can handle any number of arguments thanks to <code>*args</code>, allowing you to call the method with one or more parameters. It sums up all the numbers passed to it.</p>
<h2 id="heading-what-is-a-constructor-in-oop">What is a Constructor in OOP?</h2>
<p>A constructor is a special method that automatically runs when you create a new object from a class. It helps to set up the object's initial values (like setting the name or age of a person).</p>
<p>In Python, the constructor method is named <code>__init__</code>, which stands for "initialize”.</p>
<p>Example:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, grade</span>):</span>  <span class="hljs-comment"># The constructor method</span>
        self.name = name  <span class="hljs-comment"># Setting the name when the object is created</span>
        self.grade = grade  <span class="hljs-comment"># Setting the grade when the object is created</span>

<span class="hljs-comment"># Creating a new Student object</span>
student1 = Student(<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"A"</span>)

<span class="hljs-comment"># Accessing the student's details</span>
print(student1.name)  <span class="hljs-comment"># Output: Alice</span>
print(student1.grade)  <span class="hljs-comment"># Output: A</span>
</code></pre>
<p>In this example, the <code>__init__</code> method automatically assigns the values for <code>name</code> and <code>grade</code> when we create a <code>Student</code> object (like <code>student1</code>).When you print <code>student1.name</code>, it shows "Alice," and <code>student1.grade</code> shows "A."</p>
<p>This helps to set up each student object with different details when needed!</p>
<h2 id="heading-what-is-a-destructor-in-oop">What is a Destructor in OOP?</h2>
<p>A destructor is a method that is called when an object is destroyed. In Python, the destructor is defined using <code>__del__</code>.</p>
<p>Example:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Demo</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">"Constructor called"</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__del__</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">"Destructor called"</span>)

obj = Demo()
<span class="hljs-keyword">del</span> obj  <span class="hljs-comment"># Explicitly calling the destructor</span>
</code></pre>
<p>In this example, the <code>Demo</code> class has a constructor (<code>__init__</code>) that prints "Constructor called" when an object is created, and a destructor (<code>__del__</code>) that prints "Destructor called" when the object is deleted.</p>
<p>The <code>del obj</code> explicitly triggers the destructor to clean up the object.</p>
<h2 id="heading-what-is-a-class-in-oop">What is a Class in OOP?</h2>
<p>A class is like a template for making objects in programming. It outlines what properties (called attributes) and actions (called methods) the objects will have. Think of a class as a recipe that tells you how to create something, like a car.</p>
<p>Example:</p>
<pre><code class="lang-python"> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, make, model</span>):</span>
        self.make = make  <span class="hljs-comment"># The brand of the car, like IVM</span>
        self.model = model  <span class="hljs-comment"># The specific model, like Ikenga</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">display_info</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">f"Car: <span class="hljs-subst">{self.make}</span>, Model: <span class="hljs-subst">{self.model}</span>"</span>  <span class="hljs-comment"># Shows the car's information</span>
</code></pre>
<p>In this example:</p>
<ul>
<li><p><code>Car</code> is the class that describes what a car is.</p>
</li>
<li><p><code>make</code> and <code>model</code> are attributes that hold information about the car.</p>
</li>
<li><p><code>display_info</code> is a method that tells us how to get details about the car.</p>
</li>
</ul>
<p>When we create a car object from this class, it will have its own make and model, just like real cars do!</p>
<h2 id="heading-what-is-an-object-in-oop">What is an Object in OOP?</h2>
<p>An object is a specific example of a class. Think of it like a real-life item that has certain characteristics defined by the class. When you create an object, you're giving it actual values for its properties.</p>
<pre><code class="lang-python">my_car = Car(<span class="hljs-string">"IVM"</span>, <span class="hljs-string">"Ikenga"</span>)
print(my_car.display_info())  <span class="hljs-comment"># This will show: Car: IVM, Model: Ikenga</span>
</code></pre>
<p>In this example, <code>my_car</code> is an object created from the <code>Car</code> class.</p>
<h2 id="heading-what-is-a-static-method">What is a Static Method?</h2>
<p>This is a method that belongs to a class, not to an instance (object) of that class. Unlike other methods, static methods don’t need access to instance-specific data (attributes) or class-specific data.</p>
<p>You can call a static method directly from the class without creating an object.</p>
<p>Example:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MathOperations</span>:</span>
<span class="hljs-meta">    @staticmethod  # This tells Python it's a static method</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>):</span>
        <span class="hljs-keyword">return</span> a + b

<span class="hljs-comment"># We don't need to create an object of the class to use the static method</span>
result = MathOperations.add(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>)
print(result)  <span class="hljs-comment"># Output: 8</span>
</code></pre>
<p>In this example, <code>@staticmethod</code> is used to define the method as static. You can call <code>MathOperations.add()</code> directly using the class name, without creating an object of <code>MathOperations</code>.</p>
<h2 id="heading-what-is-the-difference-between-a-class-variable-and-an-instance-variable">What is the Difference Between a Class Variable and an Instance Variable?</h2>
<p>A class variable is shared among all instances of a class, while an instance variable is specific to each object and defined inside methods, usually within the constructor.</p>
<p>Example:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span>:</span>
    class_var = <span class="hljs-string">"I am a class variable"</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, instance_var</span>):</span>
        self.instance_var = instance_var  <span class="hljs-comment"># Instance variable</span>
</code></pre>
<p>In this example, a class <code>MyClass</code> has a class variable <code>class_var</code> that is shared by all instances, and an instance variable <code>instance_var</code> that is unique to each object created from the class.</p>
<h2 id="heading-does-python-support-multiple-inheritance">Does Python Support Multiple Inheritance?</h2>
<p>Yes, Python allows multiple inheritance, where a class can inherit from more than one parent class.</p>
<p>Example:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Parent1</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">display</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">"Parent1"</span>)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Parent2</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">display</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">"Parent2"</span>)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Child</span>(<span class="hljs-params">Parent1, Parent2</span>):</span>
    <span class="hljs-keyword">pass</span>

child = Child()
child.display()  <span class="hljs-comment"># Method resolution order determines which display() is called</span>
</code></pre>
<p>In this example, the <code>Child</code> class inherits from both <code>Parent1</code> and <code>Parent2</code>, and due to the <a target="_blank" href="https://docs.python.org/3/howto/mro.html">method resolution order (MRO)</a>, <code>Child</code> will call <code>Parent1</code>'s <code>display()</code> method first.</p>
<h2 id="heading-what-is-the-difference-between-an-abstract-class-and-an-interface">What is the Difference Between an Abstract Class and an Interface?</h2>
<p>An abstract class is a special type of class that you cannot create an object from. It can have both incomplete methods (called abstract methods) that don’t have any implementation, as well as fully implemented methods that do have code.</p>
<p>An interface is like a contract that defines methods that must be implemented by any class that uses it. In Python, we achieve interfaces through abstract base classes (ABCs), which only contain abstract methods. They don’t have any implementation.</p>
<p>Simple example to illustrate the concepts:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> abc <span class="hljs-keyword">import</span> ABC, abstractmethod

<span class="hljs-comment"># Abstract Class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span>(<span class="hljs-params">ABC</span>):</span>
<span class="hljs-meta">    @abstractmethod</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sound</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">pass</span>  <span class="hljs-comment"># This is an abstract method, no implementation</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sleep</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Sleeping..."</span>  <span class="hljs-comment"># This is a regular method with implementation</span>

<span class="hljs-comment"># Subclass that implements the abstract method</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>(<span class="hljs-params">Animal</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sound</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Bark"</span>  <span class="hljs-comment"># Implementation of the abstract method</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span>(<span class="hljs-params">Animal</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sound</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Meow"</span>  <span class="hljs-comment"># Another implementation of the abstract method</span>

<span class="hljs-comment"># Using the classes</span>
my_dog = Dog()
print(my_dog.sound())  <span class="hljs-comment"># Output: Bark</span>
print(my_dog.sleep())  <span class="hljs-comment"># Output: Sleeping...</span>

my_cat = Cat()
print(my_cat.sound())  <span class="hljs-comment"># Output: Meow</span>
print(my_cat.sleep())  <span class="hljs-comment"># Output: Sleeping...</span>
</code></pre>
<p>In this example, an abstract class <code>Animal</code> with an abstract method <code>sound</code>, and two subclasses, <code>Dog</code> and <code>Cat</code>, implement the <code>sound</code> method, demonstrating the use of abstract classes and method overriding in Python.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Understanding these OOP principles is crucial for any developer. It forms the foundation of most modern programming languages.</p>
<p>By mastering the key concepts and being prepared for interview questions, you’ll not only build better software but also enhance your chances of landing your next developer role.</p>
<p>If you found this guide helpful please give it a like. You can follow me on <a target="_blank" href="https://x.com/casweb_dev">X</a> for more insightful articles.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The React Interview Prep Handbook – Essential Topics and Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In the ever-changing landscape of web development, React is in very high demand. Companies are often seeking skilled React developers to build dynamic and engaging web applications. If you are a web developer or aspiring to be one, it's ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-interview-prep-handbook/</link>
                <guid isPermaLink="false">670902eb7e9f1a89f2aa0ed0</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kunal Nalawade ]]>
                </dc:creator>
                <pubDate>Fri, 11 Oct 2024 10:50:19 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728643567956/00c98d19-4694-4942-9ad2-d2f25bcf05c0.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In the ever-changing landscape of web development, React is in very high demand. Companies are often seeking skilled React developers to build dynamic and engaging web applications.</p>
<p>If you are a web developer or aspiring to be one, it's important to understand what these companies look for in candidates. Preparing for interviews at these companies can be a daunting task.</p>
<p>So, in this article, I am going to list some of the topics to help you prepare for your next React interview. We'll discuss each topic in detail, with examples, so you can get a good look before the interviews and possibly gain an edge over other candidates. Let's dive into it!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-javascript-fundamentals">JavaScript Fundamentals</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-react-essentials">React Essentials</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-react-hooks">React Hooks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-additional-concepts">Additional Concepts</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-react-redux">React Redux</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-additional-notes">Additional Notes</a></p>
</li>
</ul>
<h2 id="heading-javascript-fundamentals">JavaScript Fundamentals</h2>
<p>To prepare for any web development interview, you need to get familiar with JavaScript fundamentals no matter what framework is listed in the job description. Framework based questions are always secondary to JavaScript fundamentals, so expect to get tested on JavaScript first.</p>
<p>If you are a beginner, you need to clear JavaScript fundamentals before jumping into React. A lot of people (including me) make the mistake of jumping straight into React after learning a bit of JavaScript.</p>
<p>I have written a detailed post on <a target="_blank" href="https://www.freecodecamp.org/news/js-interview-prep-handbook/">important JavaScript concepts for interviews</a>. You can include this as part of your React interview preparation. If you are clear on all JavaScript fundamentals, you can skip to the next section.</p>
<h2 id="heading-react-essentials">React Essentials</h2>
<p>Let's go through some essential topics you need to get familiar with:</p>
<h3 id="heading-what-is-virtual-dom-in-react">What is Virtual DOM in React?</h3>
<p>As we all know, the browser DOM (Document Object Model) is a tree-like structure of different HTML elements. Virtual DOM is an in-memory representation or a lightweight version of the real DOM. It is an abstraction created by React which is similar to the real DOM.</p>
<p>Why does React use the virtual DOM? Updating and re-rendering the real DOM is slow and inefficient, especially if it gets updated frequently. So, instead of updating the real DOM directly, React updates the virtual DOM.</p>
<p>The virtual DOM is then compared to the real DOM and once it identifies the differences, it only updates that part of the DOM, rather than rendering the entire DOM again. This process is known as <a target="_blank" href="https://legacy.reactjs.org/docs/reconciliation.html">diffing and reconciliation</a>.</p>
<h3 id="heading-what-is-jsx">What is JSX?</h3>
<p>JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code in the same file as the JavaScript code. This makes it very easy for your HTML to work with JavaScript.</p>
<p>You can write JSX code in a <code>.js</code> or <code>.jsx</code> file. Consider the following <strong>MyComponent.jsx</strong> file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> name = <span class="hljs-string">"Kunal"</span>
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            {name}
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
}
</code></pre>
<h3 id="heading-what-is-state">What is State?</h3>
<p>State is a React object that contains information about the component and determines how the component behaves. State can change any time based on user behavior. Any change in state causes the entire component to re-render.</p>
<p>State is used to render dynamic information in the component and makes the UI interactive. State determines how a component reacts to events like user input and data manipulation, and controls what it renders on screen.</p>
<p>Some things you need to keep in mind while using state:</p>
<ul>
<li><p>States are immutable. Always update the state using a <code>setState</code> function. For objects/arrays, create new ones and set the state with the new array/object. This ensures proper component behavior.</p>
</li>
<li><p>Use state only when necessary, avoid storing redundant information as it may cause unnecessary re-renders.</p>
</li>
<li><p>Use the state locally in the same component, avoid passing state down the DOM tree, unless absolutely necessary. For global state, use context or redux.</p>
</li>
</ul>
<p>Check the <a target="_blank" href="https://legacy.reactjs.org/docs/state-and-lifecycle.html">legacy docs</a> for state in class components. For functional components, refer to the <a class="post-section-overview" href="#heading-usestate-hook"><code>useState</code></a> section.</p>
<h3 id="heading-what-are-props">What are props?</h3>
<p>Props (short for properties) are a way to pass data from one component to another. They can be considered as arguments passed to components. Props are passed to a child component similar to HTML attributes.</p>
<p>Let's take an example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> name = <span class="hljs-string">"John Doe"</span>;
  <span class="hljs-keyword">const</span> age = <span class="hljs-number">30</span>;

  <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button clicked"</span>)
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">name</span>=<span class="hljs-string">{name}</span> <span class="hljs-attr">age</span>=<span class="hljs-string">{age}</span> <span class="hljs-attr">handleClick</span>=<span class="hljs-string">{handleClick}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">{ name, age, handleClick }</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Name: {name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Age: {age}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<ul>
<li><p>Here, the parent component passes down name, age and handleClick method as props to the child component.</p>
</li>
<li><p>These props form a <code>props</code> object that contains the values passed. Every functional component takes a <code>props</code> object as an argument</p>
</li>
<li><p>We have accessed the props by destructuring the object in the child component.</p>
</li>
</ul>
<p>Props can only be passed one way down the component tree. That is, from parent to child component. Props are read-only, you cannot change their value directly. State values passed down as props can be updated using state update function.</p>
<h3 id="heading-difference-between-class-and-functional-components">Difference Between Class and Functional components</h3>
<p>React components are of two types: class and functional components. Let's understand the difference between the two:</p>
<p><strong>Class Components:</strong></p>
<ul>
<li><p>Class components are written using ES6 classes. Its properties and functions are accessed using the <code>this</code> keyword. They need a <code>render</code> method to return JSX.</p>
</li>
<li><p>Class components are stateful components that contain built-in features like State and Context.</p>
</li>
<li><p>They have methods for different stages of component lifecycle: <code>componentDidMount()</code> <code>componentDidUpdate()</code> <code>componentWillUnmount()</code>, and so on.</p>
</li>
<li><p>Class components are verbose, hard to read and always need <code>this</code> keyword to access properties.</p>
</li>
</ul>
<p><strong>Functional Components:</strong></p>
<ul>
<li><p>Functional components are simple JavaScript functions that take a <code>props</code> object as an argument. They don't need a <code>render</code> method, they return JSX directly.</p>
</li>
<li><p>Functional components are stateless and do not have state of their own. Instead, they use Hooks to use class component features like State or Context.</p>
</li>
<li><p>There are no lifecycle methods, lifecycle is be managed with <code>useEffect</code> hook.</p>
</li>
<li><p>Functional components require less code than class components, so they are easier to read and write.</p>
</li>
</ul>
<p>Nowadays, developers prefer and recommend functional components, especially with Hooks. Class components are usually found in older codebases.</p>
<p>However, knowing class components is helpful as a lot of companies have old codebases written using class components.</p>
<h3 id="heading-what-is-the-component-lifecycle">What is the Component Lifecycle?</h3>
<p>Every React component has a lifecycle that goes through three phases: Mounting, Updating and Unmounting.</p>
<p><strong>Mounting</strong></p>
<p>In this phase, a component is created and added to the DOM. When a component is mounted, the following methods are called:</p>
<ul>
<li><a target="_blank" href="https://www.geeksforgeeks.org/react-js-constructor-method/"><code>constructor()</code></a></li>
</ul>
<ul>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/react-js-static-getderivedstatefromprops/"><code>static getDerivedStateFromProps(props, state)</code></a> (rarely used)</p>
</li>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/react-js-render-method/"><code>render()</code></a></p>
</li>
<li><p><code>componentDidMount()</code></p>
</li>
</ul>
<p><code>componentDidMount()</code> is called only once; that is, when the component mounts. It is the preferred method for executing side effects when a component loads for the first time. In functional components, its equivalent is <code>useEffect</code> Hook.</p>
<p><strong>Updating</strong></p>
<p>In updating phase, the component's state or props change, which causes the component to re-render. The following methods are called when component updates:</p>
<ul>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/reactjs-shouldcomponentupdate-method/"><code>shouldComponentUpdate(nextProps, nextState)</code></a></p>
</li>
<li><p><code>render()</code> (called again)</p>
</li>
<li><p><a target="_blank" href="https://www.geeksforgeeks.org/reactjs-getsnapshotbeforeupdate-method/"><code>getSnapshotBeforeUpdate()</code></a></p>
</li>
<li><p><code>componentDidUpdate()</code></p>
</li>
</ul>
<p>The <code>componentDidUpdate</code> method is called following times:</p>
<ul>
<li><p>The first time when component mounts, after the <code>componentDidMount</code> method.</p>
</li>
<li><p>Any state or props change triggering component re-render.</p>
</li>
</ul>
<p>It is useful to execute side effects when a state updates. In functional component, the equivalent is <code>useEffect</code> with dependencies.</p>
<p><strong>Unmounting</strong></p>
<p>In this phase, the component is removed from the DOM. The <code>componentWillUnmount</code> method is called while unmounting.</p>
<p>It is mostly used for cleanup tasks before the component unmounts. Refer to the <a class="post-section-overview" href="#heading-useeffect-hook"><code>useEffect</code></a> section for its equivalent.</p>
<h3 id="heading-controlled-and-uncontrolled-components">Controlled and Uncontrolled components</h3>
<p>In controlled components, the form elements are managed by React state. This means that the values of form fields are set and updated ("controlled" by React state). All form data is stored in state before submitting the form.</p>
<p>Example of controlled component:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ControlledComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [value, setValue] = useState(<span class="hljs-string">''</span>);

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    event.preventDefault();
    alert(<span class="hljs-string">`Value: <span class="hljs-subst">${value}</span>`</span>);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setValue(e.target.value)} /&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<ul>
<li><p>The value of the <code>input</code> field is being controlled by React state variable <code>value</code>.</p>
</li>
<li><p>When you update the input field, the state gets updated and value of the input is set accordingly.</p>
</li>
</ul>
<p>Uncontrolled components, on the other hand, do not depend on state to manage forms. Instead, the values of form fields are managed internally, usually with refs. Refs are used to directly interact with the DOM elements and update values without updating state and causing re-renders.</p>
<p>Example of uncontrolled component:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UncontrolledComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> inputRef = useRef(<span class="hljs-literal">null</span>);

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    event.preventDefault();
    alert(<span class="hljs-string">`Input Value: <span class="hljs-subst">${inputRef.current.value}</span>`</span>);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputRef}</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<p>Here, we have used a ref to directly access the input element's DOM node and used its value to access form data. This makes form handling much simpler compared to using state.</p>
<p>When to use either:</p>
<ul>
<li><p>Use controlled components if you want more control over data that the user inputs. This is particularly useful when two form fields are dependent on each other.</p>
</li>
<li><p>If you have multiple state dependent on the form data, using state is a good practice.</p>
</li>
<li><p>Use uncontrolled components if your form is very simple and there's no need to manipulate the form data.</p>
</li>
</ul>
<h3 id="heading-what-are-pure-components">What are Pure Components?</h3>
<p>A pure component is similar to a normal component, except that it only renders if its state or props have changed.</p>
<p>Let's take an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> PureExample = React.memo(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> Hello {this.props.name} <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
});

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [toggle, setToggle] = useState(<span class="hljs-literal">false</span>);
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{name}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setName(e.target.value)} /&gt;
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setToggle(!toggle)}&gt; Toggle <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">PureExample</span> <span class="hljs-attr">name</span>=<span class="hljs-string">{name}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<ul>
<li><p><code>PureExample</code> is a pure component that is a child of <code>App</code> component. Pure components can be created by surrounding the function with <code>React.memo()</code>.</p>
</li>
<li><p>In the example, we have an <code>input</code> field that updates <code>name</code>, and a button that toggles the state, <code>toggle</code>.</p>
</li>
<li><p><code>name</code> is passed down as props to <code>PureExample</code>, so it re-renders if <code>name</code> is updated. If you update <code>toggle</code> or any other state, <code>PureExample</code> does not re-render.</p>
</li>
</ul>
<p>In case of class components, pure components can be created by extending the <code>PureComponent</code> class. However, functional components are recommended.</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PureExample</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">PureComponent</span> </span>{
  render() {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> Hello {this.props.name} <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
  }
}
</code></pre>
<p>Usually, when parent component re-renders, React renders all its child components again, even if none of the child components have updated.</p>
<p>Pure components are used for child components that only need to re-render if one of their props change. This skips unnecessary re-renders and improves performance.</p>
<h2 id="heading-react-hooks">React Hooks</h2>
<p>React Hooks is a game-changing feature introduced to React in 2016. Hooks provide a way to implement class component features in functional components. Because of hooks, developers nowadays prefer functional to class components.</p>
<h3 id="heading-usestate-hook">useState Hook</h3>
<p>We have already seen what state is. Let's understand how to implement state in functional components with a simple example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);
<span class="hljs-keyword">const</span> increment = <span class="hljs-function">() =&gt;</span> {
    setCount(count + <span class="hljs-number">1</span>);
};
<span class="hljs-keyword">const</span> decrement = <span class="hljs-function">() =&gt;</span> {
    setCount(count - <span class="hljs-number">1</span>);
};
<span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Count: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{increment}</span>&gt;</span>Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{decrement}</span>&gt;</span>Decrement<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
);
</code></pre>
<ul>
<li><p><code>useState</code> function takes an initial value as an argument and returns an array containing two elements: the current state, and a state update function.</p>
</li>
<li><p>In this example, we have two buttons that increment and decrement the count. On click of the button, the increment/decrement operations are performed by updating the <code>count</code> state.</p>
</li>
<li><p>The component re-renders and displays the updated <code>count</code>.</p>
</li>
</ul>
<p>For more examples of its usages, check out my post below:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://levelup.gitconnected.com/4-different-examples-of-the-usestate-hook-in-react-5504ce011a20">https://levelup.gitconnected.com/4-different-examples-of-the-usestate-hook-in-react-5504ce011a20</a></div>
<p> </p>
<h3 id="heading-useeffect-hook">useEffect Hook</h3>
<p>The <code>useEffect</code> hook is used to implement side effects in a component. Side effects include API calls, subscription to a service and DOM manipulation. <code>useEffect</code> can also be used to conditionally update a state based on another state change.</p>
<p>Let's understand how to use it, with an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [data, setData] = useState([]);
  <span class="hljs-keyword">const</span> [page, setPage] = useState(<span class="hljs-number">1</span>);
  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://api.example.com/data?page=<span class="hljs-subst">${page}</span>`</span>);
      <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> response.json();
      setData(result);
    };

    fetchData();
  }, [page]);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> {JSON.stringify(data)} <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setPage(page - 1)} disabled={page <span class="hljs-tag">&lt;<span class="hljs-name">=</span> <span class="hljs-attr">1</span>}&gt;</span>
        Previous
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setPage(page + 1)}&gt;Next<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<ul>
<li><p><code>useEffect</code> takes two arguments: a function that performs side effects and a dependency array.</p>
</li>
<li><p>In this example, we display paginated data by including the fetching logic inside a <code>useEffect</code> and including the current page in the dependency.</p>
</li>
<li><p><code>useEffect</code> makes the API call on the first render, loading the first page of data. After that, it loads additional data every time user changes the page.</p>
</li>
</ul>
<p>How to implement lifecycle methods in <code>useEffect</code>:</p>
<ul>
<li><p>To implement <code>componentDidMount()</code>, pass an empty dependency array</p>
</li>
<li><p>To implement <code>componentDidUpdate()</code>, pass dependencies to run the <code>useEffect</code> if one of those dependencies changes</p>
</li>
<li><p>For <code>componentWillUnmount()</code>, return a callback function from <code>useEffect</code> containing the cleanup code</p>
</li>
</ul>
<p><code>useEffect</code> can be used in a lot of ways. The React <a target="_blank" href="https://react.dev/reference/react/useEffect#usage">docs</a> contain several examples of usages.</p>
<h3 id="heading-usecontext-hook">useContext Hook</h3>
<p>States are used to store information about a component and controls how the component behaves. In some cases, child components need access to the parent component’s state.</p>
<p>To achieve this we pass down the state data as props. However, passing data through props may lead to issues. Let’s understand the biggest issue:</p>
<p><strong>What is Prop Drilling?</strong></p>
<p>To pass data from parent to child component, we use props. But what if a component deep within the component tree needs access to a prop. You would need to pass it through several components that don't even need the prop.</p>
<p>The same issue arises when multiple components in different branches of the tree need access to the same prop.</p>
<p>Passing down props through numerous components leads to a situation known as prop drilling.</p>
<p><strong>How does React context solve the problem?</strong></p>
<p>Context lets parent components pass data to all components in the tree without drilling props through them. This eliminates the need to pass down props through multiple components in the tree.</p>
<p>Context was introduced as a <a target="_blank" href="https://legacy.reactjs.org/docs/context.html">class component feature</a> initially, but now it can be used in functional components with the <code>useContext</code> hook.</p>
<p>Let's see how to use the hook:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, {useContext} <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> DataContext = React.createContext(<span class="hljs-literal">null</span>);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">DataContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Some value"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">MainComponent</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">DataContext.Provider</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MainComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> data = useContext(DataContext);
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> Data: {data} <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
}
</code></pre>
<ul>
<li><p>We used <code>React.createContext</code> method to create a context and then created a provider function that wraps around the main component.</p>
</li>
<li><p>The <code>value</code> prop of <code>DataContext.Provider</code> is used the pass data to the entire component tree under <code>MainComponent</code>.</p>
</li>
<li><p>The <code>useContext</code> Hook consumes this data inside components. It returns the data that was passed to the <code>value</code> prop of the provider.</p>
</li>
</ul>
<p><code>useContext</code> can only be used if the component or one of its parents has a context provider wrapped around it. Examples use cases are themes, user info, language preferences and localization, and so on.</p>
<p>Check out additional usages of <code>useContext</code> in the <a target="_blank" href="https://react.dev/reference/react/useContext#usage">docs</a>.</p>
<h3 id="heading-useref-hook">useRef Hook</h3>
<p>Refs (short for references) are a way to interact directly with DOM elements. They give you direct access to the JavaScript DOM object and its <a target="_blank" href="https://www.tutorialspoint.com/javascript/javascript_dom_methods.htm">methods</a>.</p>
<p>Visit the <a target="_blank" href="https://legacy.reactjs.org/docs/refs-and-the-dom.html">legacy docs</a> for using refs in class components. In functional components, we have the <code>useRef</code> Hook. Let's take an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">const</span> myRef = useRef(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    myRef.current.focus();
  }, []);

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{myRef}</span> /&gt;</span></span>;
}
</code></pre>
<ul>
<li><p><code>useRef</code> takes an initial value as an argument and returns a <code>ref</code> object.</p>
</li>
<li><p>When this <code>ref</code> object is passed to the <code>ref</code> prop of an element, we get a direct reference to the element's DOM node.</p>
</li>
<li><p>The value of a <code>ref</code> is stored inside its <code>current</code> property.</p>
</li>
<li><p>Since <code>ref</code> is a JavaScript DOM object, we can call the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus">focus()</a> method to focus on the <code>input</code> element when the component mounts.</p>
</li>
</ul>
<p>Unlike state, refs do not cause component re-renders and unlike local variables, refs retain their values between renders.</p>
<p>Some things to remember about refs:</p>
<ul>
<li><p>Components can expose their DOM nodes to parent components by using <a target="_blank" href="https://react.dev/reference/react/forwardRef">forwardRef</a>.</p>
</li>
<li><p>Only use refs when you absolutely need to access DOM elements. Example use cases could be for tasks like focusing on input elements, selecting tests, triggering animations, determining elements positions, and so on.</p>
</li>
<li><p>Avoid over-using them, prefer state and props over refs. Avoid modifying DOM elements explicitly to control component behavior, use state instead.</p>
</li>
</ul>
<h3 id="heading-usememo-hook">useMemo Hook</h3>
<p>If your component needs to perform an intensive calculation while rendering something, it slows down website performance since the component executes the calculation on every render.</p>
<p>This may be acceptable for a state value dependent on it, but it's inefficient if the expensive function executes again on other, unrelated state updates. To tackle this, we memoize the result of the calculation and re-calculate it only when the relevant state changes.</p>
<p><code>useMemo</code> Hook is used to memoize the result of this calculation, so that it doesn't run on every render. Let's take an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> MemoExample = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [computedValue, setComputedValue] = useState(value);
  <span class="hljs-keyword">const</span> [otherState, setOtherState] = useState(<span class="hljs-string">'Initial State'</span>);

  <span class="hljs-keyword">const</span> expensiveFunction = <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-keyword">let</span> result = <span class="hljs-number">0</span>;
      <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10000000</span>; i++) {
          result += i * <span class="hljs-number">2</span>;
      }
      <span class="hljs-keyword">return</span> result;
  }

  <span class="hljs-keyword">const</span> value = useMemo(expensiveFunction, [computedValue]);

  <span class="hljs-keyword">return</span>  (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setComputedValue(computedValue + 1)}&gt;
            Re-calculate
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setOtherState('State Changed')}&gt;
        Change Other State
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};
</code></pre>
<ul>
<li><p><code>useMemo</code> takes in the function and a dependency array as arguments, and returns the result of this function. It memoizes the result for the next render and returns the memoized value unless some dependency changes.</p>
</li>
<li><p>We have passed <code>computedValue</code> state inside the array, so, after running on the first render, the function will run only when <code>computedValue</code> changes.</p>
</li>
<li><p>If you update any other state, the component re-renders, but the function does not run again.</p>
</li>
</ul>
<p>When to use:</p>
<ul>
<li><p>If you do not want to run a function on every render, except for the state dependent on it.</p>
</li>
<li><p>To maintain referential equality of arrays and object across renders. Array/object references change each time they are declared.</p>
</li>
<li><p>When rendering lists with <a target="_blank" href="http://Array.map"><code>Array.map</code></a> that do not need to change except for relevant state updates.</p>
</li>
</ul>
<h3 id="heading-usecallback-hook">useCallback Hook</h3>
<p><code>useCallback</code> is similar to <code>useMemo</code>, the only difference is that <code>useCallback</code> caches the function definition itself, rather than memoizing its return value.</p>
<p>Similar to arrays or objects, a function reference changes each time it is declared. So, wrapping it around a <code>useCallback</code> maintains referential equality of the function across renders.</p>
<p>Let's understand it with an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [toggle, setToggle] = useState(<span class="hljs-literal">false</span>);

  <span class="hljs-keyword">const</span> handleSubmit = useCallback(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Child component form submitted'</span>);
  }, []); <span class="hljs-comment">// Add props or state that this function depends on</span>
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{toggle</span> ? '<span class="hljs-attr">dark</span>' <span class="hljs-attr">:</span> ''}&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setToggle(!toggle)}&gt; Toggle Theme <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Child</span> <span class="hljs-attr">handleSubmit</span>=<span class="hljs-string">{handleSubmit}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">const</span> Child = React.memo(<span class="hljs-function">(<span class="hljs-params">{ handleSubmit }</span>) =&gt;</span> {

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000000000</span>; i++) {
    <span class="hljs-comment">// Assume component is slow</span>
  }
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span> Child component <span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span> Click Me <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
});
</code></pre>
<ul>
<li><p>Here, we deliberately slow down the child component to simulate slow renders. Since it's wrapped inside <code>React.memo()</code>, it only re-renders if its only prop <code>handleSubmit</code> changes.</p>
</li>
<li><p>But when <code>toggle</code> state changes, it triggers a re-render for the child component as well, even if it's not passed down to the child component.</p>
</li>
<li><p>This is because, every time the parent component renders, the <code>handleSubmit</code> function is created with a new reference. So, technically <code>handleSubmit</code> has changed and thus, the child component re-renders.</p>
</li>
<li><p>To avoid this behaviour, we wrap the <code>handleSubmit</code> function declaration inside a <code>useCallback</code>. This ensures that the function reference remains the same between renders.</p>
</li>
<li><p>In our example, the function is created only once, since there are no dependencies. If you add dependencies, the function is re-created only if one of them changes.</p>
</li>
</ul>
<p>When to use:</p>
<ul>
<li><p>When you have event handlers defined for an element inside your component, wrap them inside a <code>useCallback</code> to avoid unnecessary re-creations of event handlers.</p>
</li>
<li><p>When you call a function inside a <code>useEffect</code>, you would usually pass the function as a dependency. To avoid running <code>useEffect</code> unnecessarily on every render, wrap the function definition inside a <code>useCallback</code>.</p>
</li>
<li><p>If your custom Hook is returning a function, it is recommended to wrap it inside a <code>useCallback</code>. So, the users don't have to optimize the Hook – rather, they can focus on their own code.</p>
</li>
</ul>
<p>If you want to learn more about <code>useMemo</code> and <code>useCallback</code> hooks, check out my post below:</p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/difference-between-usememo-and-usecallback-hooks/">https://www.freecodecamp.org/news/difference-between-usememo-and-usecallback-hooks/</a></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/difference-between-usememo-and-usecallback-hooks/">https://www.freecodecamp.org/news/difference-between-usememo-and-usecallback-hooks/</a></div>
<p> </p>
<h3 id="heading-usereducer-hook">useReducer Hook</h3>
<p>The <code>useReducer</code> Hook is another way to manage state in React applications. As your application grows, its state gets more and more complex. With time, it becomes difficult to handle complex state logic with <code>useState</code> Hook.</p>
<p>useReducer offers a more structured way to manage complex state by handling all state updates in a reducer function. This makes state management easier since all the state update logic is at one place.</p>
<p>Let's see how to use this hook with an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> reducer = <span class="hljs-function">(<span class="hljs-params">state, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'INCREMENT'</span>:
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count + <span class="hljs-number">1</span> };
    <span class="hljs-keyword">case</span> <span class="hljs-string">'DECREMENT'</span>:
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count - <span class="hljs-number">1</span> };
    <span class="hljs-keyword">case</span> <span class="hljs-string">'RESET'</span>:
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`Unknown action type: <span class="hljs-subst">${action.type}</span>`</span>);
  }
};

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">const</span> initialState = { <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> };
  <span class="hljs-keyword">const</span> [state, dispatch] = useReducer(reducer, initialState);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'App'</span>&gt;</span>
      State: {state.count}
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>

        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch({ type: 'INCREMENT' })}&gt;Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch({ type: 'DECREMENT' })}&gt;Decrement<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> dispatch({ type: 'RESET' })}&gt;Reset<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<ul>
<li><p>This example contains a simple counter state with three actions: increment, decrement and reset.</p>
</li>
<li><p>We define a reducer function that accepts the current state and an action object as arguments. The action object contains the action type (a string) and payload (data passed to the action).</p>
</li>
<li><p>The <code>useReducer</code> Hook accepts the reducer function and an initial state, and returns an array containing the current state and a <code>dispatch</code> method.</p>
</li>
<li><p>To update state, we call the <code>dispatch</code> method and pass the action type and payload in an object. We call this process, "dispatching an action".</p>
</li>
</ul>
<p>When to use <code>useReducer</code>:</p>
<ul>
<li><p>Use this hook only when your component has complex state update logic. Since it involves writing more code, prefer <code>useState</code> for simpler state updates. The simple example provided is just for demonstration purpose.</p>
</li>
<li><p>When there are a lot of state update actions with different logic, it makes sense to have them all in a separate function. With this, you just pass the action type and payload to a <code>dispatch</code> function and the reducer handles the state update.</p>
</li>
</ul>
<p>If you want to understand more about the <code>useReducer</code> hook, check out my post:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/usereducer-hook-react/">https://www.freecodecamp.org/news/usereducer-hook-react/</a></div>
<p> </p>
<p>So far, we have covered the most common hooks that React provides. Besides these, React also offers additional, less commonly uses hooks. So, if you are interested, read about them in the <a target="_blank" href="https://react.dev/reference/react/hooks">docs</a>. However, learning the above hooks should be enough for your interviews.</p>
<h3 id="heading-custom-hooks">Custom Hooks</h3>
<p>There are some situations where you may need to create your own hooks on top of the existing ones. Custom hooks provide re-usable functionality across multiple components and contribute to cleaner, maintainable code.</p>
<p>To create a custom Hook, first identify a piece of functionality that you want to re-use. Then, you can export it as a function with its name starting with the prefix 'use'.</p>
<p>Let's say you have multiple components that need to fetch data from APIs. You can export the fetching logic as a Hook to avoid duplicating code.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useFetch</span>(<span class="hljs-params">url</span>) </span>{
  <span class="hljs-keyword">const</span> [data, setData] = useState(<span class="hljs-literal">null</span>);
  <span class="hljs-keyword">const</span> [loading, setLoading] = useState(<span class="hljs-literal">true</span>);
  <span class="hljs-keyword">const</span> [error, setError] = useState(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url);
        <span class="hljs-keyword">if</span> (!response.ok) {
          <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Network response was not ok'</span>);
        }
        <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> response.json();
        setData(result);
      } <span class="hljs-keyword">catch</span> (error) {
        setError(error);
      } <span class="hljs-keyword">finally</span> {
        setLoading(<span class="hljs-literal">false</span>);
      }
    };

    fetchData();
  }, [url]);

  <span class="hljs-keyword">return</span> { data, loading, error };
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> useFetch;
</code></pre>
<ul>
<li><p>In the <code>useFetch</code> custom hook, we fetched the data inside a <code>useEffect</code> Hook, just as would inside a component. We also handled loading and error states in the Hook.</p>
</li>
<li><p>Finally, we return the data, with the loading and error states, allowing the component to use them for handling the rendering logic.</p>
</li>
</ul>
<p>Let's use this in a component:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> UserList = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { data, loading, error } = useFetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users'</span>);

  <span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
  <span class="hljs-keyword">if</span> (error) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Error: {error.message}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      {data.map(user =&gt; (
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{user.id}</span>&gt;</span>{user.name}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
      ))}
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>
  );
};
</code></pre>
<p>The <code>UsersList</code> component displays a list of users fetched from an API, and also renders “Loading” text and an error if any. To use the custom Hook, we called <code>useFetch</code> just like any other hook, and passed an API endpoint. We can further modify the <code>useFetch</code> custom hook to include request headers, request body, etc.</p>
<p>This way, custom Hooks help you abstract the logic from a component and make it re-usable throughout the application. There are several other use cases:</p>
<ul>
<li><p>Event listeners for events like window resizing, mouse movements or keyboard presses.</p>
</li>
<li><p>Form handling, including form validation and submission.</p>
</li>
<li><p>Themes, caches, transitions, and so on.</p>
</li>
</ul>
<p>Check out the <a target="_blank" href="https://react.dev/learn/reusing-logic-with-custom-hooks">docs</a> to learn more about custom hooks.</p>
<h2 id="heading-additional-concepts">Additional Concepts</h2>
<p>Here are some additional concepts that can be helpful:</p>
<h3 id="heading-why-not-use-index-as-keys-while-rendering-lists">Why not Use Index as Keys while Rendering Lists?</h3>
<p>When you render lists in React using the <a target="_blank" href="http://Array.map"><code>Array.map</code></a> method, you are asked to provide a unique <code>key</code> prop to each item being rendered. This key is used to distinguish elements from each other.</p>
<p>Indices are unique, so it's tempting to use them as keys for simplicity. However, indices of elements are not stable.</p>
<p>Elements often get added or deleted in an array. The order of elements could get changed too. In these cases, value of <code>key</code> prop changes and may lead to unpredictable behavior.</p>
<p>Let's consider the following list:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> items = [
  {
    <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Item A'</span>
  },
  {
    <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>,
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Item B'</span>
  },
  {
    <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>,
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Item C'</span>
  }
]
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
    {items.map((item, index) =&gt; (
      <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{index}</span>&gt;</span>
        {item.name}
      <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    ))}
  <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>
);
</code></pre>
<p>Each rendered item in the list has its index as the key. If we delete <code>Item B</code> from the list, the references of the other elements get changed.</p>
<p>React uses keys to uniquely identify list elements, so that rendering them becomes easier. React often re-uses these elements for quick renders. However, if an element gets deleted, the keys of all subsequent elements are updated.</p>
<p>React may reuse the deleted key or render the entire list again which could lead to performance issues. Instead of indices, choose something unique, preferably username, email or an ID generated by database.</p>
<h3 id="heading-higher-order-components">Higher Order Components</h3>
<p>A higher order component (HOC) is a function that takes a component as an argument and returns a new component that wraps the original one. HOCs allow you to provide additional functionality to a component as well as re-use it across multiple components.</p>
<p>Rather than providing a short explanation here, I would recommend the following article that explains HOCs with various examples:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.freecodecamp.org/news/higher-order-components-in-react/">https://www.freecodecamp.org/news/higher-order-components-in-react/</a></div>
<p> </p>
<h3 id="heading-lazy-loading">Lazy Loading</h3>
<p>Lazy loading is a web development pattern that delays the loading of resources like images, videos, or non-essential components. It helps web pages load faster by first loading the content necessary for interaction, and then loading the rest of the content.</p>
<p>One example of lazy loading is an E-commerce product catalog page. The page first loads the names and prices of products and clickable elements. Then, it loads the images and other UI elements.</p>
<p>In React, lazy loading can be implemented using <code>React.lazy()</code> and <code>Suspense</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> LazyComponent = React.lazy(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./LazyComponent'</span>));

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Showing lazy component below<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>}&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">LazyComponent</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};
</code></pre>
<ul>
<li><p>Once you have identified a component to lazy load, use the <code>React.lazy()</code> function to dynamically import the lazy component.</p>
</li>
<li><p>Wrap the lazy-loaded component inside <code>Suspense</code>. It renders a fallback (default) component till the lazy component loads.</p>
</li>
</ul>
<p>This way, you can load a React component on demand. This is also known as code splitting<strong>.</strong> The code is split and some part of the React code is loaded dynamically when needed.</p>
<p>Code splitting optimizes the performance of React applications that have large, complex components. By using <code>Suspense</code>, you can display a temporary UI to the user, so they don't have to stare at a blank screen while a component is loading.</p>
<p>Code splitting breaks your application into several chunks, with each chunk being loaded independently. So, this process is also known as chunking<strong>.</strong></p>
<h3 id="heading-difference-between-client-side-and-server-side-rendering">Difference Between Client-side and Server-side Rendering</h3>
<p>There are two ways to render webpages in React. Let's have a look:</p>
<p><strong>Server Side Rendering (SSR):</strong></p>
<ul>
<li><p>Web Page is generated and rendered on the server before sending to the client. Client receives complete web page from the server and displays it directly to the user.</p>
</li>
<li><p>Loading the prepared HTML helps with faster loading times, improving the user experience. This is especially beneficial for users with slower internet connections.</p>
</li>
<li><p>Since the web page is already prepared, it helps search engines better index your website, making it more SEO-friendly.</p>
</li>
<li><p>SSR can increase server load if the page is updated frequently. Pages with dynamic content can take longer to update because they need to re-render often.</p>
</li>
<li><p>SSR is used for marketing, blogging and news websites where initial load times and SEO are important.</p>
</li>
</ul>
<p><strong>Client Side Rendering (CSR):</strong></p>
<ul>
<li><p>A basic HTML file is sent to the client, and then it renders dynamic content using JavaScript.</p>
</li>
<li><p>Initial load times are slower because preparing and rendering the content mostly happens on the client side.</p>
</li>
<li><p>Since it initially renders basic HTML and adds JavaScript content later, search engines may not be able to index your content, making it less SEO-friendly.</p>
</li>
<li><p>For web pages with dynamic content, rendering times are faster since all the rendering happens on client side.</p>
</li>
<li><p>CSR is used for websites with dynamic content and frequent user interactions like social media platforms or dashboards.</p>
</li>
</ul>
<h2 id="heading-react-redux">React Redux</h2>
<p>Redux is a state-management library that helps manage complex application state. It is a powerful library for managing state in large React applications.</p>
<p>In the context of React, let’s look at the Hooks Redux provides:</p>
<h3 id="heading-useselector">useSelector</h3>
<p>A selector function accepts a Redux state object as an argument and returns a part of that state. The <code>useSelector</code> Hook is used to call the selector function. Let's take the following example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// example state for e-commerce app</span>
<span class="hljs-keyword">const</span> initialState = {
    <span class="hljs-attr">users</span>: { 
        ...
    },
    <span class="hljs-attr">products</span>: {
        ...
    },
    <span class="hljs-attr">cart</span>: {
        ...
    }
    <span class="hljs-attr">orders</span>: {
        <span class="hljs-attr">ordersList</span>: [
            {
                <span class="hljs-attr">id</span>: <span class="hljs-number">101</span>,
                <span class="hljs-attr">status</span>: <span class="hljs-string">"Shipped"</span>
            },
            {
                <span class="hljs-attr">id</span>: <span class="hljs-number">102</span>,
                <span class="hljs-attr">status</span>: <span class="hljs-string">"Processing"</span>
            },

            ...
        ]
    }
}
</code></pre>
<p>Let's say you want to display list of orders on a page. We can't access this state directly from the component as it’s part of the redux store. So, we use selector functions.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> selectAllOrders = <span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> state.orders.ordersList
</code></pre>
<p>To call this selector function, we use the <code>useSelector</code> Hook:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> OrdersList = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> orders = useSelector(selectAllOrders);
  <span class="hljs-keyword">return</span> (
    <span class="hljs-comment">// display orders</span>
  );
};
</code></pre>
<p>The main advantage of using selectors is that you get access to the Redux state object, allowing you to access any slice of the state.</p>
<h3 id="heading-usedispatch">useDispatch</h3>
<p>The <code>useDispatch</code> Hook returns a function that you can use to dispatch actions, such as updating state and calling APIs. This function takes an action object as an argument and performs the corresponding action. This function is known as a dispatch function.</p>
<p>Let's take an example. We’ll work with the same state and update one of the order’s status:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> dispatch = useDispatch();

  <span class="hljs-keyword">const</span> handleUpdateStatus = <span class="hljs-function">() =&gt;</span> {
    dispatch({<span class="hljs-attr">type</span>: <span class="hljs-string">'ORDER_UPDATE_STATUS'</span>, <span class="hljs-attr">payload</span>: {
      <span class="hljs-attr">id</span>: <span class="hljs-number">102</span>,
      <span class="hljs-attr">status</span>: <span class="hljs-string">"Shipped"</span>
    }});
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Update Order Status<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleUpdateStatus}</span>&gt;</span>Mark as Delivered<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Here, the action <code>ORDER_UPDATE_STATUS</code> will be dispatched with the corresponding payload. This action will be mapped to a reducer that will perform the state update.</p>
<p>The advantage of using dispatch is that you can just specify the action type and pass the payload and the state update logic will be handled by the reducer, instead of the component itself.</p>
<h3 id="heading-others">Others</h3>
<p>I have just listed two Hooks that React provides to work with Redux. However, if you are not familiar with Redux, you should check out the <a target="_blank" href="https://redux.js.org/introduction/getting-started">docs</a> to get started.</p>
<p>Redux is much more than just these two Hooks. Make sure you are clear on the core concepts: store, slices, reducers, actions, selectors, dispatch. <a target="_blank" href="https://redux-saga.js.org/docs/introduction/GettingStarted">Redux Sagas</a> is another major concept you should learn. They are mainly used for async operations.</p>
<h2 id="heading-additional-notes">Additional Notes</h2>
<p>There are a few other areas that I haven't mentioned so far, but can be a good addition:</p>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/react-router-cheatsheet/">React Router</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/how-to-write-unit-tests-in-react/">Unit Testing in React</a></p>
</li>
</ul>
<p>Additionally, you may be asked to implement a small feature using the concepts I explained in this article. This gives you the opportunity to demonstrate your understanding of React.</p>
<p>Also, it's helpful to have a few React projects on your resume. Check out the <a target="_blank" href="https://www.freecodecamp.org/news/master-react-by-building-25-projects/">Master React by Building 25 Projects</a>.</p>
<p>Keep in mind that React is not limited to just these topics, there are additional resources in the References section. However, this handbook should serve as a useful guide before interviews. Feel free to keep re-visiting it during your interview preparation.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this handbook, we outlined several important topics to prepare for your next React interview. We started with a few basic concepts in React, then moved to Hooks. Then, we saw a few additional concepts that are good to know before discussing React Redux.</p>
<p>I have written clear and concise explanations for each topic, with examples. That should help you articulate these concepts to interviewers. At places where I couldn't explain, I have pointed to other helpful resources that explain better. This makes the article your go-to place any time during your interview prep.</p>
<p>During the interviews, just stay calm and confidently demonstrate your knowledge. Good communication puts a nice impression on the interview. Lastly, remember that each interview is a learning opportunity - whether you succeed or not. Stay positive and keep refining your skills. All the best in your interviews!</p>
<h3 id="heading-references">References</h3>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/react-interview-questions-and-answers/">React Interview Questions – Interview Prep with Answers and Examples</a></p>
</li>
<li><p><a target="_blank" href="https://www.interviewbit.com/react-interview-questions/">React Interview Questions</a> - InterviewBit</p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/learn-react-key-concepts/#how-much-javascript-do-you-need-to-know-before-learning-react">Learn React – A Guide to the Key Concepts by Ankur Tyagi</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Java Interview Prep Handbook – 50 Questions Solved + Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ If you're trying to get a job in big tech or you want to refine your skills in software development, a strong grasp of Java is indispensable.  Java is well-known for its robustness in Object-Oriented Programming (OOP), and it provides a comprehensive... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/java-interview-prep-handbook/</link>
                <guid isPermaLink="false">66b99afebe5923657131acd6</guid>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vahe Aslanyan ]]>
                </dc:creator>
                <pubDate>Thu, 07 Dec 2023 21:28:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/The-Java-Interview-Prep-Handbook-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're trying to get a job in big tech or you want to refine your skills in software development, a strong grasp of Java is indispensable. </p>
<p>Java is well-known for its robustness in Object-Oriented Programming (OOP), and it provides a comprehensive foundation essential for developers at every level.</p>
<p>This handbook offers a detailed pathway to help you excel in Java interviews. It focuses on delivering insights and techniques relevant to roles in esteemed big tech companies, ensuring you're well-prepared for the challenges ahead.</p>
<p>This guide serves as a comprehensive Java review tutorial, bridging the gap between foundational Java knowledge and the sophisticated expertise sought by industry leaders like Google. And it'll help you deepen your understanding and practical application of Java, preparing you for professional success in the tech industry.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-1-what-is-java">What is Java?</a></li>
<li><a class="post-section-overview" href="#heading-2-whats-the-difference-between-the-jdk-jre-and-jvm">What's the difference between the JDK, JRE, and JVM?</a></li>
<li><a class="post-section-overview" href="#heading-3-how-does-the-public-static-void-mainstring-args-method-work">How does the 'public static void main(String[] args)' method work?</a></li>
<li><a class="post-section-overview" href="#heading-4-what-is-bytecode-in-java">What is bytecode in Java?</a></li>
<li><a class="post-section-overview" href="#heading-5-differentiate-between-overloading-and-overriding">Differentiate between overloading and overriding</a></li>
<li><a class="post-section-overview" href="#heading-6-what-is-the-java-classloader">What is the Java ClassLoader?</a></li>
<li><a class="post-section-overview" href="#heading-7-can-we-override-static-methods-in-java">Can we override static methods in Java?</a></li>
<li><a class="post-section-overview" href="#heading-8-how-does-the-finally-block-differ-from-the-finalize-method-in-java">How does the 'finally' block differ from the 'finalize' method in Java?</a></li>
<li><a class="post-section-overview" href="#heading-9-what-is-the-difference-between-an-abstract-class-and-an-interface">What is the difference between an abstract class and an interface?</a></li>
<li><a class="post-section-overview" href="#heading-10-explain-the-concept-of-java-packages">Explain the concept of Java packages</a></li>
<li><a class="post-section-overview" href="#heading-11-what-are-java-annotations">What are Java annotations?</a></li>
<li><a class="post-section-overview" href="#heading-12-how-does-multi-threading-work-in-java">How does multi-threading work in Java?</a></li>
<li><a class="post-section-overview" href="#heading-13-use-throw-to-raise-an-exception">Use <code>throw</code> to raise an exception</a></li>
<li><a class="post-section-overview" href="#heading-14-use-throws-to-declare-exceptions">Use <code>throws</code> to declare exceptions</a></li>
<li><a class="post-section-overview" href="#heading-15-what-is-the-significance-of-the-transient-keyword">What is the significance of the transient keyword?</a></li>
<li><a class="post-section-overview" href="#heading-16-how-do-you-ensure-thread-safety-in-java">How do you ensure thread safety in Java?</a></li>
<li><a class="post-section-overview" href="#heading-17-explain-the-singleton-pattern">Explain the Singleton pattern</a></li>
<li><a class="post-section-overview" href="#heading-18-what-are-java-streams">What are Java Streams?</a></li>
<li><a class="post-section-overview" href="#heading-19-what-are-the-primary-differences-between-arraylist-and-linkedlist">What are the primary differences between ArrayList and LinkedList?</a></li>
<li><a class="post-section-overview" href="#heading-20-how-do-hashset-linkedhashset-and-treeset-differ">How do HashSet, LinkedHashSet, and TreeSet differ?</a></li>
<li><a class="post-section-overview" href="#heading-21-differentiate-between-hashmap-and-concurrenthashmap">Differentiate between HashMap and ConcurrentHashMap</a></li>
<li><a class="post-section-overview" href="#heading-22-describe-the-contract-between-the-hashcode-and-equals-methods">Describe the contract between hashCode() and equals() methods</a></li>
<li><a class="post-section-overview" href="#heading-23-what-is-java-reflection">What is Java reflection?</a></li>
<li><a class="post-section-overview" href="#heading-24-how-do-you-create-a-custom-exception-in-java">How do you create a custom exception in Java?</a></li>
<li><a class="post-section-overview" href="#heading-25-what-is-the-difference-between-a-checked-and-unchecked-exception">What is the difference between a checked and unchecked exception?</a></li>
<li><a class="post-section-overview" href="#heading-26-what-are-generics-why-are-they-used">What are generics? Why are they used?</a></li>
<li><a class="post-section-overview" href="#heading-27-explain-the-concept-of-java-lambda-expressions">Explain the concept of Java Lambda Expressions</a></li>
<li><a class="post-section-overview" href="#heading-28-what-is-the-diamond-problem-in-inheritance">What is the diamond problem in inheritance?</a></li>
<li><a class="post-section-overview" href="#heading-29-describe-the-difference-between-fail-fast-and-fail-safe-iterators">Describe the difference between fail-fast and fail-safe iterators</a></li>
<li><a class="post-section-overview" href="#heading-30-what-is-type-erasure-in-java-generics">What is type erasure in Java generics?</a></li>
<li><a class="post-section-overview" href="#heading-31-describe-the-differences-between-stringbuilder-and-stringbuffer">Describe the differences between StringBuilder and StringBuffer</a></li>
<li><a class="post-section-overview" href="#heading-32-what-is-the-volatile-keyword-in-java">What is the volatile keyword in Java?</a></li>
<li><a class="post-section-overview" href="#heading-33-explain-the-java-memory-model">Explain the Java memory model</a></li>
<li><a class="post-section-overview" href="#heading-34-what-is-the-purpose-of-the-default-keyword-in-interfaces">What is the purpose of the default keyword in interfaces?</a></li>
<li><a class="post-section-overview" href="#heading-35-how-does-switch-differ-in-java-7-and-java-8">How does switch differ in Java 7 and Java 8?</a></li>
<li><a class="post-section-overview" href="#heading-36-explain-the-concept-of-autoboxing-and-unboxing">Explain the concept of Autoboxing and Unboxing</a></li>
<li><a class="post-section-overview" href="#heading-37-describe-the-functionalinterface-annotation">Describe the @FunctionalInterface annotation</a></li>
<li><a class="post-section-overview" href="#heading-38-how-can-you-achieve-immutability-in-java">How can you achieve immutability in Java?</a></li>
<li><a class="post-section-overview" href="#heading-39-what-is-the-decorator-pattern">What is the decorator pattern?</a></li>
<li><a class="post-section-overview" href="#heading-40-explain-java-io-streams">Explain the Java I/O streams</a></li>
<li><a class="post-section-overview" href="#heading-41-how-does-the-garbage-collector-work-in-java">How does the garbage collector work in Java?</a></li>
<li><a class="post-section-overview" href="#heading-42-what-are-the-benefits-of-using-java-nio">What are the benefits of using Java NIO?</a></li>
<li><a class="post-section-overview" href="#heading-43-explain-the-observer-pattern">Explain the Observer pattern</a></li>
<li><a class="post-section-overview" href="#heading-44-explain-the-purpose-of-the-this-keyword">What is the purpose of Java's Optional?</a></li>
<li><a class="post-section-overview" href="#heading-45-explain-javas-try-with-resources">Explain Java's try-with-resources</a></li>
<li><a class="post-section-overview" href="#heading-46-explain-the-difference-between-c-and-java">Explain the difference between C++ and Java</a></li>
<li><a class="post-section-overview" href="#heading-47-what-is-polymorphism-provide-an-example">What is polymorphism? Provide an example</a></li>
<li><a class="post-section-overview" href="#heading-48-how-can-you-avoid-memory-leaks-in-java">How can you avoid memory leaks in Java?</a></li>
<li><a class="post-section-overview" href="#heading-49-explain-the-purpose-of-javas-synchronized-block">Explain the purpose of Java's synchronized block</a></li>
<li><a class="post-section-overview" href="#50-explain-the-concept-of-modules-in-java-">Explain the concept of modules in Java</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-1-what-is-java">1. What is Java?</h2>
<p>Java is a high-level, object-oriented programming language known for its platform independence. It allows developers to write code once and run it anywhere using the Java Virtual Machine (JVM).</p>
<h2 id="heading-2-whats-the-difference-between-the-jdk-jre-and-jvm">2. What's the Difference between the JDK, JRE, and JVM?</h2>
<ul>
<li><strong>JDK (Java Development Kit):</strong> This is a software package that provides developers with the tools and utilities necessary to develop, compile, and run Java applications.</li>
<li><strong>JRE (Java Runtime Environment):</strong> A subset of the JDK, the JRE contains the essential components, including the JVM, to run Java applications but not to develop them.</li>
<li><strong>JVM (Java Virtual Machine):</strong> An abstract computing machine, the JVM enables Java bytecode to be executed, providing the platform independence Java is known for.</li>
</ul>
<h2 id="heading-3-how-does-the-public-static-void-mainstring-args-method-work">3. How Does the <code>public static void main(String[] args)</code> Method Work?</h2>
<p>This method is the entry point for Java applications. The <code>public</code> modifier means it's accessible from other classes, <code>static</code> denotes it's a class-level method, and <code>void</code> indicates it doesn't return any value. The argument <code>String[] args</code> allows command-line arguments to be passed to the application.</p>
<h2 id="heading-4-what-is-bytecode-in-java">4. What is bytecode in Java?</h2>
<p>Bytecode is an intermediate, platform-independent code that Java source code is compiled into. It is executed by the JVM, enabling the "write once, run anywhere" capability.</p>
<h2 id="heading-5-differentiate-between-overloading-and-overriding">5. Differentiate between overloading and overriding</h2>
<ul>
<li><strong>Overloading:</strong> This occurs when two or more methods in the same class share the same name but have different parameters. It's a compile-time concept.</li>
</ul>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MathOperation</span> </span>{
    <span class="hljs-comment">// Method 1: Overloaded with two integer parameters</span>
    int multiply(int a, int b) {
        <span class="hljs-keyword">return</span> a * b;
    }

    <span class="hljs-comment">// Method 2: Same method name but different parameters (one double, one integer)</span>
    double multiply(double a, int b) {
        <span class="hljs-keyword">return</span> a * b;
    }

    <span class="hljs-comment">// Method 3: Same method name but different number of parameters</span>
    int multiply(int a, int b, int c) {
        <span class="hljs-keyword">return</span> a * b * c;
    }
}

public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span>[] args) {
        MathOperation operation = <span class="hljs-keyword">new</span> MathOperation();

        <span class="hljs-comment">// Calling the first multiply method</span>
        System.out.println(<span class="hljs-string">"Result 1: "</span> + operation.multiply(<span class="hljs-number">4</span>, <span class="hljs-number">5</span>));

        <span class="hljs-comment">// Calling the second multiply method</span>
        System.out.println(<span class="hljs-string">"Result 2: "</span> + operation.multiply(<span class="hljs-number">5.5</span>, <span class="hljs-number">2</span>));

        <span class="hljs-comment">// Calling the third multiply method</span>
        System.out.println(<span class="hljs-string">"Result 3: "</span> + operation.multiply(<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>));
    }
}
</code></pre><ul>
<li><strong>Overriding:</strong> In this case, a subclass provides a specific implementation for a method already defined in its superclass. It's a runtime concept.</li>
</ul>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-comment">// Method in superclass</span>
    <span class="hljs-keyword">void</span> speak() {
        System.out.println(<span class="hljs-string">"Animal speaks"</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-comment">// Overriding the speak method in the subclass</span>
    @Override
    <span class="hljs-keyword">void</span> speak() {
        System.out.println(<span class="hljs-string">"Dog barks"</span>);
    }
}

public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span>[] args) {
        Animal myAnimal = <span class="hljs-keyword">new</span> Animal();
        Animal myDog = <span class="hljs-keyword">new</span> Dog();

        <span class="hljs-comment">// Calling the method from the superclass</span>
        myAnimal.speak();

        <span class="hljs-comment">// Calling the overridden method in the subclass</span>
        myDog.speak();
    }
}
</code></pre><h2 id="heading-6-what-is-the-java-classloader">6. What is the Java ClassLoader?</h2>
<p>The Java ClassLoader is a part of the JRE that dynamically loads Java classes into the JVM during runtime. It plays a crucial role in Java's runtime environment by extending the core Java classes.</p>
<h2 id="heading-7-can-we-override-static-methods-in-java">7. Can We Override Static Methods in Java?</h2>
<p>No, we cannot override static methods. While a subclass can declare a method with the same name as a static method in its superclass, this is considered method hiding, not overriding.</p>
<h2 id="heading-8-how-does-the-finally-block-differ-from-the-finalize-method-in-java">8. How Does the <code>finally</code> Block Differ from the <code>finalize</code> Method in Java?</h2>
<p>Understanding the distinction between the <code>finally</code> block and the <code>finalize</code> method in Java is crucial for effective resource management and exception handling in your programs.</p>
<p><strong>Finally Block:</strong></p>
<ul>
<li><strong>Purpose and Usage:</strong> The <code>finally</code> block is a key component of Java's exception handling mechanism. It is used in conjunction with <code>try-catch</code> blocks.</li>
<li><strong>Execution Guarantee:</strong> Regardless of whether an exception is thrown or caught within the <code>try</code> or <code>catch</code> blocks, the code within the <code>finally</code> block is always executed. This ensures that it runs even if there’s a return statement in the <code>try</code> or <code>catch</code> block.</li>
<li><strong>Common Uses:</strong> It is typically utilized for cleaning up resources, such as closing file streams, database connections, or releasing any system resources that were acquired in the <code>try</code> block. This helps in preventing resource leaks.</li>
</ul>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FinallyDemo</span> </span>{
    public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span>[] args) {
        <span class="hljs-keyword">try</span> {
            int division = <span class="hljs-number">10</span> / <span class="hljs-number">0</span>;
        } <span class="hljs-keyword">catch</span> (ArithmeticException e) {
            System.out.println(<span class="hljs-string">"Arithmetic Exception: "</span> + e.getMessage());
        } <span class="hljs-keyword">finally</span> {
            System.out.println(<span class="hljs-string">"This is the finally block. It always executes."</span>);
        }
    }
}
</code></pre><p><strong>Finalize Method:</strong></p>
<ul>
<li><strong>Definition:</strong> The <code>finalize</code> method is a protected method of the <code>Object</code> class in Java. It acts as a final resort for objects garbage collection.</li>
<li><strong>Garbage Collector Call:</strong> It is called by the garbage collector on an object when the garbage collector determines that there are no more references to the object. However, its execution is not guaranteed, and it's generally unpredictable when, or even if, the <code>finalize</code> method will be invoked.</li>
<li><strong>Resource Release:</strong> The <code>finalize</code> method is designed to allow an object to clean up its resources before it is collected by the garbage collector. For example, it might be used to ensure that an open file owned by an object is closed.</li>
<li><strong>Caution in Use:</strong> It's important to note that relying on <code>finalize</code> for resource cleanup is generally not recommended due to its unpredictability and potential impact on performance.</li>
</ul>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FinalizeDemo</span> </span>{
    protected <span class="hljs-keyword">void</span> finalize() throws Throwable {
        System.out.println(<span class="hljs-string">"finalize method called before garbage collection"</span>);
    }

    public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span>[] args) {
        FinalizeDemo obj = <span class="hljs-keyword">new</span> FinalizeDemo();
        obj = <span class="hljs-literal">null</span>; <span class="hljs-comment">// Making the object eligible for garbage collection</span>
        System.gc(); <span class="hljs-comment">// Requesting JVM for garbage collection</span>
    }
}
</code></pre><p><strong>Access Modifiers in Java:</strong></p>
<ul>
<li><strong>Private:</strong> This modifier makes a member accessible only within its own class. Other classes cannot access private members of a different class.</li>
</ul>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PrivateDemo</span> </span>{
    private int privateVariable = <span class="hljs-number">10</span>;

    private <span class="hljs-keyword">void</span> display() {
        System.out.println(<span class="hljs-string">"Private variable: "</span> + privateVariable);
    }
}
</code></pre><ul>
<li><strong>Default (no modifier):</strong> When no access modifier is specified, the member has package-level access. This means it is accessible to all classes within the same package.</li>
</ul>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DefaultDemo</span> </span>{
    int defaultVariable = <span class="hljs-number">20</span>;

    <span class="hljs-keyword">void</span> display() {
        System.out.println(<span class="hljs-string">"Default variable: "</span> + defaultVariable);
    }
}
</code></pre><ul>
<li><strong>Protected:</strong> A protected member is accessible within its own package and also in subclasses. This is often used in inheritance.</li>
</ul>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProtectedDemo</span> </span>{
    protected int protectedVariable = <span class="hljs-number">30</span>;

    protected <span class="hljs-keyword">void</span> display() {
        System.out.println(<span class="hljs-string">"Protected variable: "</span> + protectedVariable);
    }
}
</code></pre><ul>
<li><strong>Public:</strong> Public members are accessible from any class in the Java program. It provides the widest level of access.</li>
</ul>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PublicDemo</span> </span>{
    public int publicVariable = <span class="hljs-number">40</span>;

    public <span class="hljs-keyword">void</span> display() {
        System.out.println(<span class="hljs-string">"Public variable: "</span> + publicVariable);
    }
}
</code></pre><p>Understanding these distinctions and access levels is vital for effective Java programming, ensuring resource management, security, and encapsulation are handled appropriately in your software development endeavors.</p>
<h2 id="heading-9-what-is-the-difference-between-an-abstract-class-and-an-interface">9. What is the Difference between an Abstract Class and an Interface?</h2>
<p>An abstract class in Java is used as a base for other classes. It can contain both abstract methods (without an implementation) and concrete methods (with an implementation).</p>
<p>Abstract classes can have member variables that can be inherited by subclasses. A class can extend only one abstract class due to Java's single inheritance property.</p>
<p><strong>Example of an Abstract Class:</strong></p>
<pre><code>abstract <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Shape</span> </span>{
    <span class="hljs-built_in">String</span> color;

    <span class="hljs-comment">// abstract method</span>
    abstract double area();

    <span class="hljs-comment">// concrete method</span>
    public <span class="hljs-built_in">String</span> getColor() {
        <span class="hljs-keyword">return</span> color;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Shape</span> </span>{
    double radius;

    Circle(<span class="hljs-built_in">String</span> color, double radius) {
        <span class="hljs-built_in">this</span>.color = color;
        <span class="hljs-built_in">this</span>.radius = radius;
    }

    @Override
    double area() {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.PI * <span class="hljs-built_in">Math</span>.pow(radius, <span class="hljs-number">2</span>);
    }
}

public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span>[] args) {
        Shape shape = <span class="hljs-keyword">new</span> Circle(<span class="hljs-string">"Red"</span>, <span class="hljs-number">2.5</span>);
        System.out.println(<span class="hljs-string">"Color: "</span> + shape.getColor());
        System.out.println(<span class="hljs-string">"Area: "</span> + shape.area());
    }
}
</code></pre><p>An interface in Java, on the other hand, is a completely "abstract class" that is used to group related methods with empty bodies.</p>
<p>From Java 8 onwards, interfaces can have default and static methods with a body. A class can implement any number of interfaces.</p>
<p><strong>Example of an Interface:</strong></p>
<pre><code>interface Drawable {
    <span class="hljs-keyword">void</span> draw();

    <span class="hljs-comment">// default method</span>
    <span class="hljs-keyword">default</span> <span class="hljs-keyword">void</span> display() {
        System.out.println(<span class="hljs-string">"Displaying the drawable"</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Rectangle</span> <span class="hljs-title">implements</span> <span class="hljs-title">Drawable</span> </span>{
    public <span class="hljs-keyword">void</span> draw() {
        System.out.println(<span class="hljs-string">"Drawing a rectangle"</span>);
    }
}

public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span>[] args) {
        Drawable drawable = <span class="hljs-keyword">new</span> Rectangle();
        drawable.draw();
        drawable.display();
    }
}
</code></pre><p>Both abstract classes and interfaces are foundational concepts in Java, used for achieving abstraction and supporting design patterns like Strategy and Adapter. The use of these concepts depends on the specific requirements and design considerations of your software project.</p>
<h2 id="heading-10-explain-the-concept-of-java-packages">10. Explain the Concept of Java Packages</h2>
<p>Java packages are a way of organizing and structuring classes and interfaces in Java applications. They provide a means to group related code together. Packages help prevent naming conflicts, enhance code readability, and facilitate code reusability.</p>
<p>For example, consider a banking application. You might have packages like <code>com.bank.accounts</code>, <code>com.bank.customers</code>, and <code>com.bank.transactions</code>. These packages contain classes and interfaces specific to their respective functionalities.</p>
<p>In essence, Java packages are like directories or folders in a file system, organizing code and making it more manageable.</p>
<h2 id="heading-11-what-are-java-annotations">11. What are Java Annotations?</h2>
<p>Java annotations are metadata that can be added to Java source code. They provide information about the code to the compiler or runtime environment. Annotations do not directly affect the program's functionality – instead, they convey instructions to tools or frameworks.</p>
<p>A common use of annotations is for marking classes or methods as belonging to a specific framework or for providing additional information to tools like code analyzers, build tools, or even custom code generators.</p>
<p>For example, the <code>@Override</code> annotation indicates that a method is intended to override a method from a superclass, helping catch coding errors during compilation. Another example is <code>@Deprecated</code>, which indicates that a method or class is no longer recommended for use.</p>
<h2 id="heading-12-how-does-multi-threading-work-in-java">12. How Does Multi-threading Work in Java?</h2>
<p>Multi-threading in Java allows a program to execute multiple threads concurrently. Threads are lightweight processes within a program that can run independently. Java provides a rich set of APIs and built-in support for multi-threading.</p>
<p>Threads in Java are typically created by either extending the <code>Thread</code> class or implementing the <code>Runnable</code> interface. Once created, threads can be started using the <code>start()</code> method, causing them to run concurrently.</p>
<p>Java's multi-threading model ensures that threads share resources like memory and CPU time efficiently while providing mechanisms like synchronization and locks to control access to shared data.</p>
<p>Multi-threading is useful for tasks such as improving application responsiveness, utilizing multi-core processors, and handling concurrent operations, as often seen in server applications.</p>
<h2 id="heading-13-use-throw-to-raise-an-exception">13. Use <code>throw</code> to Raise an Exception</h2>
<p>In Java programming, the <code>throw</code> keyword is crucial for handling exceptions deliberately and responsively. This approach to exception management allows developers to enforce specific conditions in their code and maintain control over the program flow.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">verifyAge</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age)</span> </span>{
    <span class="hljs-keyword">if</span> (age &lt; <span class="hljs-number">18</span>) {
        <span class="hljs-comment">// Throwing an IllegalArgumentException if the age is below the legal threshold</span>
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalArgumentException(<span class="hljs-string">"Access Denied - You must be at least 18 years old."</span>);
    } <span class="hljs-keyword">else</span> {
        System.out.println(<span class="hljs-string">"Access Granted - Age requirement met."</span>);
    }
}
</code></pre>
<p>In this example, an <code>IllegalArgumentException</code> is thrown if the <code>age</code> parameter is less than 18. This method of raising an exception ensures that the program behaves predictably under defined conditions, enhancing both the security and reliability of the code.</p>
<h2 id="heading-14-use-throws-to-declare-exceptions">14. Use <code>throws</code> to Declare Exceptions</h2>
<p>The <code>throws</code> keyword in Java serves to declare that a method may cause an exception to be thrown. It signals to the method's caller that certain exceptions might arise, which should be either caught or further declared.</p>
<pre><code class="lang-java">
<span class="hljs-keyword">import</span> java.io.FileNotFoundException;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FileHandler</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">readFile</span><span class="hljs-params">(String fileName)</span> <span class="hljs-keyword">throws</span> FileNotFoundException </span>{
        <span class="hljs-comment">// Code to read a file</span>
        <span class="hljs-comment">// If the file does not exist, throw a FileNotFoundException</span>
        <span class="hljs-keyword">if</span> (!fileExists(fileName)) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> FileNotFoundException(<span class="hljs-string">"File not found: "</span> + fileName);
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">fileExists</span><span class="hljs-params">(String fileName)</span> </span>{
        <span class="hljs-comment">// Check if the file exists in the file system</span>
        <span class="hljs-comment">// Return true if found, false otherwise</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        FileHandler fileHandler = <span class="hljs-keyword">new</span> FileHandler();
        <span class="hljs-keyword">try</span> {
            fileHandler.readFile(<span class="hljs-string">"sample.txt"</span>);
        } <span class="hljs-keyword">catch</span> (FileNotFoundException e) {
            System.out.println(<span class="hljs-string">"Exception: "</span> + e.getMessage());
        }
    }
}
</code></pre>
<p>In this scenario, the <code>readDocument</code> method declares that it might throw a <code>FileNotFoundException</code>. This declaration requires the caller of this method to handle this exception, ensuring that appropriate measures are in place to deal with potential errors, and thus improving the robustness of the application.</p>
<p>Both <code>throw</code> and <code>throws</code> are integral to managing exceptions in Java. <code>throw</code> is used for actively raising an exception in the code, while <code>throws</code> declares possible exceptions that a method might produce, thereby mandating their handling by the caller. This distinction is essential for writing error-resistant and well-structured Java programs.</p>
<h2 id="heading-15-what-is-the-significance-of-the-transient-keyword">15. What is the Significance of the <code>transient</code> Keyword?</h2>
<p>The <code>transient</code> keyword in Java is used to indicate that a field should not be serialized when an object of a class is converted to a byte stream (for example, when using Java Object Serialization). </p>
<p>This is significant when you have fields in a class that you do not want to include in the serialized form, perhaps because they are temporary, derived, or contain sensitive information.</p>
<p>Example:</p>
<pre><code class="lang-java">
<span class="hljs-keyword">import</span> java.io.Serializable;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Serializable</span> </span>{
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">transient</span> String temporaryData; <span class="hljs-comment">// This field won't be serialized</span>

    <span class="hljs-comment">// Constructors, getters, setters...</span>
}
</code></pre>
<h2 id="heading-16-how-do-you-ensure-thread-safety-in-java">16. How Do You Ensure Thread Safety in Java?</h2>
<p>Thread safety in Java is achieved by synchronizing access to shared resources, ensuring that multiple threads can't simultaneously modify data in a way that leads to inconsistencies or errors. </p>
<p>You can ensure thread safety through synchronization mechanisms like <code>synchronized</code> blocks, using thread-safe data structures, or utilizing concurrent utilities from the <code>java.util.concurrent</code> package.</p>
<pre><code class="lang-java">
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SharedCounter</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> count = <span class="hljs-number">0</span>;

    <span class="hljs-comment">// Synchronized method ensures thread safety</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title">increment</span><span class="hljs-params">()</span> </span>{
        count++;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getCount</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> count;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-keyword">final</span> SharedCounter counter = <span class="hljs-keyword">new</span> SharedCounter();

        Runnable task = () -&gt; {
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10000</span>; i++) {
                counter.increment();
            }
        };

        Thread thread1 = <span class="hljs-keyword">new</span> Thread(task);
        Thread thread2 = <span class="hljs-keyword">new</span> Thread(task);

        thread1.start();
        thread2.start();

        <span class="hljs-keyword">try</span> {
            thread1.join();
            thread2.join();
        } <span class="hljs-keyword">catch</span> (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        System.out.println(<span class="hljs-string">"Final Count: "</span> + counter.getCount());
    }
}
</code></pre>
<p>In the code above, we have a <code>SharedCounter</code> class with a synchronized <code>increment</code> method, ensuring that only one thread can increment the <code>count</code> variable at a time. This synchronization mechanism prevents data inconsistencies when multiple threads access and modify the shared <code>count</code> variable.</p>
<p>We create two threads (<code>thread1</code> and <code>thread2</code>) that concurrently increment the counter. By using synchronized methods or blocks, we guarantee thread safety, and the final count will be accurate, regardless of thread interleaving.</p>
<h2 id="heading-17-explain-the-singleton-pattern">17. Explain the Singleton Pattern</h2>
<p>The Singleton pattern is a design pattern that ensures a class has only one instance and provides a global point of access to that instance. It is achieved by making the constructor of the class private, creating a static method to provide a single point of access to the instance, and lazily initializing the instance when needed.</p>
<h3 id="heading-implementation-without-singleton">Implementation without Singleton:</h3>
<p>Let's imagine a scenario where you want to establish a database connection. Without the Singleton pattern, every time you'd need a connection, you might end up creating a new one.</p>
<pre><code class="lang-java">
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DatabaseConnectionWithoutSingleton</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DatabaseConnectionWithoutSingleton</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Establishing a new database connection..."</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">query</span><span class="hljs-params">(String SQL)</span> </span>{
        System.out.println(<span class="hljs-string">"Executing query: "</span> + SQL);
    }
}
</code></pre>
<p>Now, imagine initializing this connection multiple times in different parts of your application:</p>
<pre><code class="lang-java">
DatabaseConnectionWithoutSingleton connection1 = <span class="hljs-keyword">new</span> DatabaseConnectionWithoutSingleton();
DatabaseConnectionWithoutSingleton connection2 = <span class="hljs-keyword">new</span> DatabaseConnectionWithoutSingleton();
</code></pre>
<p>For the above code, "Establishing a new database connection..." would be printed twice, implying two separate connections were created. This is redundant and can be resource-intensive.</p>
<h3 id="heading-implementation-with-singleton">Implementation with Singleton:</h3>
<p>With the Singleton pattern, even if you attempt to get the connection multiple times, you'd be working with the same instance.</p>
<pre><code class="lang-java">
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DatabaseConnectionWithSingleton</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> DatabaseConnectionWithSingleton instance;

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">DatabaseConnectionWithSingleton</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Establishing a single database connection..."</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">synchronized</span> DatabaseConnectionWithSingleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">if</span> (instance == <span class="hljs-keyword">null</span>) {
            instance = <span class="hljs-keyword">new</span> DatabaseConnectionWithSingleton();
        }
        <span class="hljs-keyword">return</span> instance;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">query</span><span class="hljs-params">(String SQL)</span> </span>{
        System.out.println(<span class="hljs-string">"Executing query: "</span> + SQL);
    }
}
</code></pre>
<p>Initializing this connection multiple times:</p>
<pre><code class="lang-java">
DatabaseConnectionWithSingleton connection1 = DatabaseConnectionWithSingleton.getInstance();
DatabaseConnectionWithSingleton connection2 = DatabaseConnectionWithSingleton.getInstance();
</code></pre>
<p>For the above code, "Establishing a single database connection..." would be printed just once, even though we've called <code>getInstance()</code> twice.</p>
<h2 id="heading-18-what-are-java-streams">18. What are Java Streams?</h2>
<p>Java Streams are a powerful abstraction for processing sequences of elements, such as collections, arrays, or I/O channels, in a functional and declarative style. They provide methods for filtering, mapping, reducing, and performing various transformations on data. </p>
<p>Streams can significantly simplify code and improve readability when working with data collections.</p>
<h2 id="heading-19-what-are-the-primary-differences-between-arraylist-and-linkedlist">19. What Are the Primary Differences between ArrayList and LinkedList?</h2>
<p><code>ArrayList</code> and <code>LinkedList</code> are both implementations of the <code>List</code> interface. The primary differences between them lie in their internal data structures. </p>
<p><code>ArrayList</code> uses a dynamic array to store elements, offering fast random access but slower insertions and deletions. <code>LinkedList</code> uses a doubly-linked list, which provides efficient insertions and deletions but slower random access.</p>
<h2 id="heading-20-how-do-hashset-linkedhashset-and-treeset-differ">20. How do <code>HashSet</code>, <code>LinkedHashSet</code>, and <code>TreeSet</code> Differ?</h2>
<ul>
<li><strong><code>HashSet</code></strong> stores elements in an unordered manner, offering constant-time complexity for basic operations.</li>
<li><strong><code>LinkedHashSet</code></strong> maintains the order of insertion, providing ordered iteration of elements.</li>
<li><strong><code>TreeSet</code></strong> stores elements in a sorted order (natural or custom), offering log(n) time complexity for basic operations.</li>
</ul>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.HashSet;
<span class="hljs-keyword">import</span> java.util.LinkedHashSet;
<span class="hljs-keyword">import</span> java.util.TreeSet;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SetPerformanceExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-keyword">int</span> numElements = <span class="hljs-number">1000000</span>;

        <span class="hljs-keyword">long</span> startTime = System.nanoTime();
        HashSet&lt;Integer&gt; hashSet = <span class="hljs-keyword">new</span> HashSet&lt;&gt;();
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; numElements; i++) {
            hashSet.add(i);
        }
        <span class="hljs-keyword">long</span> endTime = System.nanoTime();
        <span class="hljs-keyword">long</span> hashSetTime = endTime - startTime;

        startTime = System.nanoTime();
        LinkedHashSet&lt;Integer&gt; linkedHashSet = <span class="hljs-keyword">new</span> LinkedHashSet&lt;&gt;();
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; numElements; i++) {
            linkedHashSet.add(i);
        }
        endTime = System.nanoTime();
        <span class="hljs-keyword">long</span> linkedHashSetTime = endTime - startTime;

        startTime = System.nanoTime();
        TreeSet&lt;Integer&gt; treeSet = <span class="hljs-keyword">new</span> TreeSet&lt;&gt;();
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; numElements; i++) {
            treeSet.add(i);
        }
        endTime = System.nanoTime();
        <span class="hljs-keyword">long</span> treeSetTime = endTime - startTime;

        System.out.println(<span class="hljs-string">"HashSet Time (ns): "</span> + hashSetTime);
        System.out.println(<span class="hljs-string">"LinkedHashSet Time (ns): "</span> + linkedHashSetTime);
        System.out.println(<span class="hljs-string">"TreeSet Time (ns): "</span> + treeSetTime);
    }
}
</code></pre>
<p>In this code, we add a large number of elements to each type of set (<code>HashSet</code>, <code>LinkedHashSet</code>, and <code>TreeSet</code>) and measure the time it takes to perform this operation. This demonstrates the performance characteristics of each set type. </p>
<p>Typically, you will observe that <code>HashSet</code> performs the fastest for adding elements since it doesn't maintain any specific order, followed by <code>LinkedHashSet</code>, and <code>TreeSet</code>, which maintains a sorted order.</p>
<pre><code class="lang-java"><span class="hljs-function">HashSet <span class="hljs-title">Time</span> <span class="hljs-params">(ns)</span>: 968226
LinkedHashSet <span class="hljs-title">Time</span> <span class="hljs-params">(ns)</span>: 1499057
TreeSet <span class="hljs-title">Time</span> <span class="hljs-params">(ns)</span>: 2384328</span>
</code></pre>
<p>This output demonstrates the time taken (in nanoseconds) to add one million elements to each of the three sets: <code>HashSet</code>, <code>LinkedHashSet</code>, and <code>TreeSet</code>. As you can see, <code>HashSet</code> is the fastest, followed by <code>LinkedHashSet</code>, and <code>TreeSet</code> is the slowest due to its need to maintain elements in sorted order.</p>
<h2 id="heading-21-differentiate-between-hashmap-and-concurrenthashmap">21. Differentiate between <code>HashMap</code> and <code>ConcurrentHashMap</code></h2>
<p><code>HashMap</code> is not thread-safe and is suitable for single-threaded applications. <code>ConcurrentHashMap</code>, on the other hand, is designed for concurrent access and supports multiple threads without external synchronization. It provides high concurrency and performance for read and write operations.</p>
<h2 id="heading-22-describe-the-contract-between-the-hashcode-and-equals-methods">22. Describe the Contract between the <code>hashCode()</code> and <code>equals()</code> Methods</h2>
<p>The contract between <code>hashCode()</code> and <code>equals()</code> methods states that if two objects are equal (<code>equals()</code> returns true), their hash codes (<code>hashCode()</code>) must also be equal. </p>
<p>However, the reverse is not necessarily true: objects with equal hash codes may not be equal. Adhering to this contract is crucial when using objects as keys in hash-based collections like <code>HashMap</code>.</p>
<h2 id="heading-23-what-is-java-reflection">23. What is Java Reflection?</h2>
<p>Java reflection is a feature that allows you to inspect and manipulate the metadata of classes, methods, fields, and other program elements at runtime. It enables you to perform tasks such as dynamically creating objects, invoking methods, and accessing fields, even for classes that were not known at compile time.</p>
<h2 id="heading-24-how-do-you-create-a-custom-exception-in-java">24. How Do You Create a Custom Exception in Java?</h2>
<p>You can create a custom exception in Java by extending the <code>Exception</code> class or one of its subclasses. By doing so, you can define your exception with specific attributes and behaviors tailored to your application's needs.</p>
<p>Example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomException</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Exception</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CustomException</span><span class="hljs-params">(String message)</span> </span>{
        <span class="hljs-keyword">super</span>(message);
    }
}
</code></pre>
<h2 id="heading-25-what-is-the-difference-between-a-checked-and-unchecked-exception">25. What is the Difference between a Checked and Unchecked Exception?</h2>
<p>Checked exceptions are exceptions that must be either caught using a <code>try-catch</code> block or declared in the method signature using the <code>throws</code> keyword. </p>
<p>Unchecked exceptions (usually subclasses of <code>RuntimeException</code>) do not require such handling.</p>
<p>Checked exceptions are typically used for recoverable errors, while unchecked exceptions represent programming errors or runtime issues. </p>
<p>Here is a code example to illustrate checked and unchecked exceptions.</p>
<pre><code class="lang-java">
<span class="hljs-comment">// Checked Exception (IOException)</span>
<span class="hljs-keyword">import</span> java.io.File;
<span class="hljs-keyword">import</span> java.io.FileReader;
<span class="hljs-keyword">import</span> java.io.IOException;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CheckedExceptionExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-keyword">try</span> {
            File file = <span class="hljs-keyword">new</span> File(<span class="hljs-string">"example.txt"</span>);
            FileReader reader = <span class="hljs-keyword">new</span> FileReader(file);
            <span class="hljs-comment">// Perform file reading operations</span>
            reader.close();
        } <span class="hljs-keyword">catch</span> (IOException e) {
            <span class="hljs-comment">// Handle the checked exception</span>
            System.err.println(<span class="hljs-string">"An IOException occurred: "</span> + e.getMessage());
        }
    }
}
</code></pre>
<p>In this code, we attempt to read a file using FileReader, which may throw a checked exception called <code>IOException</code>. </p>
<p>To handle this exception, we enclose the file reading code in a try-catch block specifically catching <code>IOException</code>. This is an example of how you handle checked exceptions, which are typically used for recoverable errors like file not found or I/O issues.</p>
<p>Now, let's take a look at an example of an unchecked exception:</p>
<pre><code class="lang-java"><span class="hljs-comment">// Unchecked Exception (ArithmeticException)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UncheckedExceptionExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-keyword">int</span> dividend = <span class="hljs-number">10</span>;
        <span class="hljs-keyword">int</span> divisor = <span class="hljs-number">0</span>;

        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">int</span> result = dividend / divisor; <span class="hljs-comment">// This will throw an ArithmeticException</span>
            System.out.println(<span class="hljs-string">"Result: "</span> + result);
        } <span class="hljs-keyword">catch</span> (ArithmeticException e) {
            <span class="hljs-comment">// Handle the unchecked exception</span>
            System.err.println(<span class="hljs-string">"An ArithmeticException occurred: "</span> + e.getMessage());
        }
    }
}
</code></pre>
<p>In this code, we attempt to divide an integer by zero, which leads to an unchecked exception called <code>ArithmeticException</code>. Unchecked exceptions do not require explicit handling using a try-catch block. However, it's good practice to catch and handle them when you anticipate such issues. These exceptions often represent programming errors or runtime issues.</p>
<h2 id="heading-26-what-are-generics-why-are-they-used">26. What Are Generics? Why Are They Used?</h2>
<p>Generics in Java are a powerful feature that allows you to create classes, interfaces, and methods that operate on types. They provide a way to define classes or methods with a placeholder for the data type that will be used when an instance of the class is created or when a method is called. </p>
<p>Generics are used to make your code more reusable, type-safe, and less error-prone by allowing you to write generic algorithms that work with different data types. They help eliminate the need for typecasting and enable compile-time type checking.</p>
<p>For example, consider the use of a generic class to create a List of integers:</p>
<pre><code class="lang-java">
List&lt;Integer&gt; numbers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
numbers.add(<span class="hljs-number">1</span>);
numbers.add(<span class="hljs-number">2</span>);
<span class="hljs-keyword">int</span> sum = numbers.get(<span class="hljs-number">0</span>) + numbers.get(<span class="hljs-number">1</span>);
</code></pre>
<p>Generics ensure that you can only add integers to the list and that you don't need to perform explicit typecasting when retrieving elements from the list.</p>
<h2 id="heading-27-explain-the-concept-of-java-lambda-expressions">27. Explain the Concept of Java Lambda Expressions</h2>
<p>Lambda expressions in Java are a concise way to express instances of single-method interfaces (functional interfaces) using a more compact syntax. They facilitate functional programming by allowing you to treat functions as first-class citizens. </p>
<p>Lambda expressions consist of a parameter list, an arrow (-&gt;), and a body. They provide a way to define and use anonymous functions.</p>
<p>For example, consider a functional interface <code>Runnable</code> that represents a task to be executed. With a lambda expression, you can define and execute a runnable task as follows:</p>
<pre><code class="lang-java">Runnable task = () -&gt; {
    System.out.println(<span class="hljs-string">"Executing a runnable task."</span>);
};
task.run(); <span class="hljs-comment">// Executes the task</span>
</code></pre>
<p>We will talk about a more practical example later down the post.</p>
<h2 id="heading-28-what-is-the-diamond-problem-in-inheritance">28. What is the Diamond Problem in Inheritance?</h2>
<p>The diamond problem in inheritance is a common issue in object-oriented programming languages that support multiple inheritance. It occurs when a class inherits from two classes that have a common ancestor class, resulting in ambiguity about which superclass's method or attribute to use.</p>
<p>Java solves the diamond problem by not supporting multiple inheritance of classes (that is, a class cannot inherit from more than one class). </p>
<p>But Java allows multiple inheritance of interfaces, which doesn't lead to the diamond problem because interfaces only declare method signatures, and the implementing class must provide concrete implementations. In case of method conflicts, the implementing class must explicitly choose which method to use.</p>
<p>Here's a simplified example to illustrate the diamond problem (even though Java doesn't directly encounter it):</p>
<pre><code class="lang-java">
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Class A"</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">B</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">default</span> <span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Interface B"</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">C</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">default</span> <span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Interface C"</span>);
    }
}

<span class="hljs-comment">// This would lead to a diamond problem if Java supported multiple inheritance of classes:</span>
<span class="hljs-comment">// class D extends B, C { }</span>

<span class="hljs-comment">// To solve this issue in Java with interfaces, you must provide an explicit implementation:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">D</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">B</span>, <span class="hljs-title">C</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Choose which method to use</span>
        B.<span class="hljs-keyword">super</span>.display(); <span class="hljs-comment">// Using B's method</span>
        C.<span class="hljs-keyword">super</span>.display(); <span class="hljs-comment">// Using C's method</span>
    }
}
</code></pre>
<p>In Java, the diamond problem is avoided through interface implementation and explicit method choice when conflicts arise.</p>
<h2 id="heading-29-describe-the-difference-between-fail-fast-and-fail-safe-iterators">29. Describe the Difference between Fail-fast and Fail-safe Iterators</h2>
<p>In Java, fail-fast and fail-safe are two strategies for handling concurrent modification of collections during iteration. </p>
<p>Fail-fast iterators throw a <code>ConcurrentModificationException</code> if a collection is modified while being iterated. Fail-safe iterators, on the other hand, do not throw exceptions and allow safe iteration even if the collection is modified concurrently.</p>
<h3 id="heading-fail-fast-iterator-example">Fail-Fast Iterator Example:</h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.Iterator;
<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FailFastExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        List&lt;String&gt; list = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
        list.add(<span class="hljs-string">"Alice"</span>);
        list.add(<span class="hljs-string">"Bob"</span>);
        list.add(<span class="hljs-string">"Charlie"</span>);

        <span class="hljs-comment">// Create an iterator</span>
        Iterator&lt;String&gt; iterator = list.iterator();

        <span class="hljs-keyword">while</span> (iterator.hasNext()) {
            String name = iterator.next();
            System.out.println(name);

            <span class="hljs-comment">// Simulate concurrent modification</span>
            <span class="hljs-keyword">if</span> (name.equals(<span class="hljs-string">"Bob"</span>)) {
                list.remove(name); <span class="hljs-comment">// This will throw ConcurrentModificationException</span>
            }
        }
    }
}
</code></pre>
<p>In this example, when we attempt to remove an element from the <code>list</code> while iterating, it leads to a <code>ConcurrentModificationException</code>, which is characteristic of fail-fast behavior. Fail-fast iterators immediately detect and throw an exception when they detect that the collection has been modified during iteration.</p>
<h3 id="heading-fail-safe-iterator-example"><strong>Fail-Safe Iterator Example:</strong></h3>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Iterator;
<span class="hljs-keyword">import</span> java.util.concurrent.ConcurrentHashMap;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FailSafeExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        ConcurrentHashMap&lt;Integer, String&gt; map = <span class="hljs-keyword">new</span> ConcurrentHashMap&lt;&gt;();
        map.put(<span class="hljs-number">1</span>, <span class="hljs-string">"One"</span>);
        map.put(<span class="hljs-number">2</span>, <span class="hljs-string">"Two"</span>);
        map.put(<span class="hljs-number">3</span>, <span class="hljs-string">"Three"</span>);

        <span class="hljs-comment">// Create an iterator</span>
        Iterator&lt;Integer&gt; iterator = map.keySet().iterator();

        <span class="hljs-keyword">while</span> (iterator.hasNext()) {
            Integer key = iterator.next();
            System.out.println(key);

            <span class="hljs-comment">// Simulate concurrent modification (no exception thrown)</span>
            <span class="hljs-keyword">if</span> (key == <span class="hljs-number">2</span>) {
                map.put(<span class="hljs-number">4</span>, <span class="hljs-string">"Four"</span>);
            }
        }
    }
}
</code></pre>
<p>In this example, a <code>ConcurrentHashMap</code> is used, which supports fail-safe iterators. Even if we modify the <code>map</code> concurrently while iterating, there is no <code>ConcurrentModificationException</code> thrown. Fail-safe iterators continue iterating over the original elements and do not reflect changes made after the iterator is created.</p>
<h2 id="heading-30-what-is-type-erasure-in-java-generics">30. What is Type Erasure in Java Generics?</h2>
<p>Type erasure is a process in Java where type parameters in generic classes or methods are replaced with their upper bound or <code>Object</code> during compilation. This erasure ensures backward compatibility with pre-generic Java code. But it means that the type information is not available at runtime, which can lead to issues in some cases.</p>
<h2 id="heading-31-describe-the-differences-between-stringbuilder-and-stringbuffer">31. Describe the Differences between <code>StringBuilder</code> and <code>StringBuffer</code></h2>
<h3 id="heading-thread-safety">Thread Safety:</h3>
<p><code>StringBuffer</code> is thread-safe. This means it is synchronized, so it ensures that only one thread can modify it at a time. This is crucial in a multithreaded environment where you have multiple threads modifying the same string buffer.</p>
<p><code>StringBuilder</code>, on the other hand, is not thread-safe. It does not guarantee synchronization, making it unsuitable for use in scenarios where a string is accessed and modified by multiple threads concurrently. But this lack of synchronization typically leads to better performance under single-threaded conditions.</p>
<h3 id="heading-performance">Performance:</h3>
<p>Because <code>StringBuffer</code> operations are synchronized, they involve a certain overhead that can impact performance negatively when high-speed string manipulation is required.</p>
<p><code>StringBuilder</code> is faster than <code>StringBuffer</code> because it avoids the overhead of synchronization. It's an excellent choice for string manipulation in a single-threaded environment.</p>
<h3 id="heading-use-case-scenarios">Use Case Scenarios:</h3>
<p>Use <code>StringBuffer</code> when you need to manipulate strings in a multithreaded environment. Its thread-safe nature makes it the appropriate choice in this scenario.</p>
<p>Use <code>StringBuilder</code> in single-threaded situations, such as local method scope or within a block synchronized externally, where thread safety is not a concern. Its performance benefits shine in these cases.</p>
<h3 id="heading-api-similarity">API Similarity:</h3>
<p>Both <code>StringBuilder</code> and <code>StringBuffer</code> have almost identical APIs. They provide similar methods for manipulating strings, such as <code>append()</code>, <code>insert()</code>, <code>delete()</code>, <code>reverse()</code>, and so on. </p>
<p>This similarity means that switching from one to the other in your code is generally straightforward.</p>
<h3 id="heading-memory-efficiency">Memory Efficiency:</h3>
<p>Both classes are more memory efficient compared to using <code>String</code> for concatenation. Since <code>String</code> is immutable in Java, concatenation with <code>String</code> creates multiple objects, whereas <code>StringBuilder</code> and <code>StringBuffer</code> modify the string in place.</p>
<h3 id="heading-introduced-versions">Introduced Versions:</h3>
<p><code>StringBuffer</code> has been a part of Java since version 1.0, whereas <code>StringBuilder</code> was introduced later in Java 5. This introduction was primarily to offer a non-synchronized alternative to <code>StringBuffer</code> for improved performance in single-threaded applications.</p>
<p>You should make the choice between <code>StringBuilder</code> and <code>StringBuffer</code> based on the specific requirements of your application, particularly regarding thread safety and performance needs. </p>
<p>While <code>StringBuffer</code> provides safety in a multithreaded environment, <code>StringBuilder</code> offers speed and efficiency in single-threaded or externally synchronized scenarios.</p>
<h2 id="heading-32-what-is-the-volatile-keyword-in-java">32. What is the <code>volatile</code> Keyword in Java?</h2>
<p><strong>Basic Definition:</strong> The volatile keyword is used to modify the value of a variable by different threads. It ensures that the value of the volatile variable will always be read from the main memory and not from the thread's local cache.</p>
<p><strong>Visibility Guarantee:</strong> In a multithreading environment, threads can cache variables. Without volatile, there's no guarantee that one thread's changes to a variable will be visible to another. The volatile keyword guarantees visibility of changes to variables across threads.</p>
<p><strong>Happens-Before Relationship:</strong> <code>volatile</code> establishes a happens-before relationship in Java. This means that all the writes to the <code>volatile</code> variable are visible to subsequent reads of that variable, ensuring a consistent view of the variable across threads.</p>
<p><strong>Usage Scenarios:</strong> <code>volatile</code> is used for variables that may be updated by multiple threads. It's often used for flags or status variables. For example, a volatile boolean running variable can be used to stop a thread.</p>
<p><strong>Limitations:</strong> Volatile cannot be used with class or instance variables. It's only applicable to fields. It doesn't provide atomicity. </p>
<p>For instance, volatile int i; i++; is not an atomic operation. For atomicity, you might need to resort to <code>AtomicInteger</code> or synchronized methods or blocks. It's not a substitute for synchronization in every case, especially when multiple operations on the volatile variable need to be atomic.</p>
<p><strong>Avoiding Common Misconceptions:</strong> A common misconception is that <code>volatile</code> makes the whole block of statements atomic, which is not true. It only ensures the visibility and ordering of the writes to the volatile variable. </p>
<p>Another misconception is that <code>volatile</code> variables are slow. But while they might have a slight overhead compared to non-volatile variables, they are generally faster than using synchronized methods or blocks.  </p>
<p><strong>Performance Considerations:</strong> <code>volatile</code> can be a more lightweight alternative to synchronization in cases where only visibility concerns are present. It doesn't incur the locking overhead that synchronized methods or blocks do.  </p>
<p><strong>Best Practices:</strong> Use <code>volatile</code> sparingly and only when necessary. Overusing it can lead to memory visibility issues that are harder to detect and debug.<br>Always assess whether your use case requires atomicity, in which case other concurrent utilities or synchronization might be more appropriate.</p>
<h3 id="heading-volatile-use-case"><code>volatile</code> use case:</h3>
<p>We will create a simple program where one thread modifies a <code>volatile</code> boolean flag, and another thread reads this flag. This flag will be used to control the execution of the second thread.</p>
<h4 id="heading-code-example">Code Example:</h4>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">VolatileExample</span> </span>{

    <span class="hljs-comment">// The 'volatile' keyword ensures that changes to this variable</span>
    <span class="hljs-comment">// are immediately visible to other threads.</span>
    <span class="hljs-comment">// This variable acts as a flag to control the execution of the thread.</span>
    private volatile boolean running = <span class="hljs-literal">true</span>;

    public <span class="hljs-keyword">void</span> startThread() {
        Thread thread1 = <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Runnable() {
            @Override
            public <span class="hljs-keyword">void</span> run() {
                <span class="hljs-comment">// The thread keeps running as long as 'running' is true.</span>
                <span class="hljs-comment">// Due to 'volatile', the latest value of 'running' is read from main memory.</span>
                <span class="hljs-keyword">while</span> (running) {
                    System.out.println(<span class="hljs-string">"Thread is running..."</span>);
                    <span class="hljs-keyword">try</span> {
                        <span class="hljs-comment">// Simulating some work with sleep</span>
                        Thread.sleep(<span class="hljs-number">1000</span>);
                    } <span class="hljs-keyword">catch</span> (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        System.out.println(<span class="hljs-string">"Thread was interrupted"</span>);
                    }
                }
                System.out.println(<span class="hljs-string">"Thread stopped."</span>);
            }
        });

        thread1.start();
    }

    public <span class="hljs-keyword">void</span> stopThread() {
        <span class="hljs-comment">// Updating the 'running' variable, which will be visible to thread1</span>
        <span class="hljs-comment">// because the variable is marked as 'volatile'.</span>
        running = <span class="hljs-literal">false</span>;
    }

    public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span>[] args) throws InterruptedException {
        VolatileExample example = <span class="hljs-keyword">new</span> VolatileExample();

        <span class="hljs-comment">// Start the thread</span>
        example.startThread();

        <span class="hljs-comment">// Main thread sleeps for 5 seconds, representing some processing time</span>
        Thread.sleep(<span class="hljs-number">5000</span>);

        <span class="hljs-comment">// Stop the thread by changing the state of 'running'</span>
        example.stopThread();
    }
}
</code></pre><h3 id="heading-key-points-in-the-comments">Key Points in the Comments:</h3>
<ul>
<li><strong>Visibility of <code>volatile</code> variable:</strong> The most crucial aspect of using <code>volatile</code> here is ensuring that the update to the <code>running</code> variable in one thread (main thread) is immediately visible to another thread (<code>thread1</code>). This is what allows <code>thread1</code> to stop gracefully when <code>running</code> is set to <code>false</code>.</li>
<li><strong>Use in a Simple Flag Scenario:</strong> The example demonstrates a common scenario for using <code>volatile</code>, that is as a simple flag to control the execution flow in a multithreaded environment.</li>
<li><strong>Absence of Compound Operations:</strong> Note that we are not performing any compound operations (like incrementing) on the <code>running</code> variable. If we were, additional synchronization would be needed because <code>volatile</code> alone does not guarantee atomicity of compound actions.</li>
<li><strong>Choice of <code>volatile</code> Over Synchronization:</strong> The choice to use <code>volatile</code> over other synchronization mechanisms (like <code>synchronized</code> blocks or <code>Locks</code>) is due to its lightweight nature when dealing with the visibility of a single variable. It avoids the overhead associated with acquiring and releasing locks.</li>
</ul>
<h2 id="heading-33-explain-the-java-memory-model">33. Explain the Java Memory Model</h2>
<p>The JMM defines how Java threads interact through memory. Essentially, it describes the relationship between variables and the actions of threads (reads and writes), ensuring consistency and predictability in concurrent programming.</p>
<h3 id="heading-happens-before-relationship">Happens-Before Relationship:</h3>
<p>At the heart of the JMM is the 'happens-before' relationship. This principle ensures memory visibility, guaranteeing that if one action happens-before another, then the first is visible to and affects the second.</p>
<p>For example, changes to a variable made by one thread are guaranteed to be visible to other threads only if a happens-before relationship is established.</p>
<h3 id="heading-memory-visibility">Memory Visibility:</h3>
<p>Without the JMM, threads might cache variables, and changes made by one thread might not be visible to others. The JMM ensures that changes made to a shared variable by one thread will eventually be visible to other threads.</p>
<h3 id="heading-synchronization">Synchronization:</h3>
<p>The JMM utilizes synchronization to establish happens-before relationships. When a variable is accessed within synchronized blocks, any write operation in one synchronized block is visible to any subsequent read operation in another synchronized block.</p>
<p>Additionally, the JMM governs the behavior of volatile variables, ensuring visibility of updates to these variables across threads without synchronization.</p>
<h3 id="heading-thread-interleaving-and-atomicity">Thread Interleaving and Atomicity:</h3>
<p>The JMM defines how operations can interleave when executed by multiple threads. This can lead to complex states if not managed correctly.</p>
<p>Atomicity refers to operations that are indivisible and uninterrupted. In Java, operations on most primitive types (except <code>long</code> and <code>double</code>) are atomic. However, compound operations (like incrementing a variable) are not automatically atomic.</p>
<h3 id="heading-reordering">Reordering:</h3>
<p>The JMM allows compilers to reorder instructions for performance optimization as long as happens-before guarantees are maintained. However, this can lead to subtle bugs if not properly understood.</p>
<h3 id="heading-use-of-volatile-keyword">Use of Volatile Keyword:</h3>
<p>The <code>volatile</code> keyword plays a significant role in the JMM. It ensures that any write to a volatile variable establishes a happens-before relationship with subsequent reads of that variable, thus ensuring memory visibility without the overhead of synchronization.</p>
<h3 id="heading-locking-mechanisms">Locking Mechanisms:</h3>
<p>Locks in Java (implicit via synchronized blocks/methods or explicit via <code>ReentrantLock</code> or others) also adhere to the JMM, ensuring that memory visibility is maintained across threads entering and exiting locks.</p>
<h3 id="heading-safe-publication">Safe Publication:</h3>
<p>The JMM also addresses the concept of safe publication, ensuring that objects are fully constructed and visible to other threads after their creation.</p>
<h3 id="heading-high-level-implications">High-Level Implications:</h3>
<p>Understanding the JMM is critical for writing correct and efficient multi-threaded Java applications. It helps developers reason about how shared memory is handled, especially in complex applications where multiple threads interact and modify shared data.</p>
<h3 id="heading-best-practices">Best Practices:</h3>
<ul>
<li>Always use the appropriate synchronization mechanism to ensure memory visibility and atomicity.</li>
<li>Be cautious about memory visibility issues; even simple operations can lead to visibility problems in a multi-threaded context.</li>
<li>Understand the cost of synchronization and use volatile variables where appropriate.</li>
</ul>
<h2 id="heading-34-what-is-the-purpose-of-the-default-keyword-in-interfaces">34. What is the Purpose of the <code>default</code> Keyword in Interfaces?</h2>
<p>The <code>default</code> keyword in Java interfaces, introduced in Java 8, marks a significant evolution in the Java language, especially in how interfaces are used and implemented. It serves several key purposes:</p>
<h3 id="heading-adding-method-implementations-in-interfaces">Adding Method Implementations in Interfaces:</h3>
<p>Prior to Java 8, interfaces in Java could only contain method signatures (abstract methods) without any implementation. </p>
<p>The <code>default</code> keyword allows you to provide a default implementation for a method within an interface. This feature bridges a gap between full abstraction (interfaces) and concrete implementations (classes).</p>
<h3 id="heading-enhancing-interface-evolution">Enhancing Interface Evolution:</h3>
<p>One of the primary motivations for introducing the <code>default</code> keyword was to enhance the evolution of interfaces. </p>
<p>Before Java 8, adding a new method to an interface meant breaking all its existing implementations. With <code>default</code> methods, you can add new methods to interfaces with default implementations without breaking the existing implementations. </p>
<p>This is particularly useful for library designers, ensuring backward compatibility when interfaces need to be expanded.</p>
<h3 id="heading-facilitating-functional-programming">Facilitating Functional Programming:</h3>
<p>\The introduction of <code>default</code> methods played a crucial role in enabling functional programming features in Java, such as Lambda expressions. It allowed for richer interfaces (like <code>java.util.stream.Stream</code>) which are fundamental to functional-style operations in Java.</p>
<h3 id="heading-multiple-inheritance-of-behavior">Multiple Inheritance of Behavior:</h3>
<p>While Java does not allow multiple inheritance of state (that is, you cannot inherit from multiple classes), the <code>default</code> keyword enables multiple inheritance of behavior. </p>
<p>A class can implement multiple interfaces, and each interface can provide a default implementation of methods, which the class inherits.</p>
<h3 id="heading-reducing-boilerplate-code">Reducing Boilerplate Code:</h3>
<p><code>default</code> methods can be used to reduce the amount of boilerplate code by providing a general implementation that can be shared across multiple implementing classes, while still allowing individual classes to override the default implementation if a more specific behavior is required.</p>
<p><strong>Example Usage:</strong></p>
<pre><code>public interface Vehicle {
    <span class="hljs-comment">// An abstract method</span>
    <span class="hljs-keyword">void</span> cleanVehicle();

    <span class="hljs-comment">// A default method in the interface</span>
    <span class="hljs-keyword">default</span> <span class="hljs-keyword">void</span> startEngine() {
        System.out.println(<span class="hljs-string">"Engine started."</span>);
    }
}
</code></pre><p>In this example, any class implementing the <code>Vehicle</code> interface must provide an implementation for <code>cleanVehicle</code>, but it's optional for <code>startEngine</code>. The default implementation of <code>startEngine</code> can be used as is, or overridden by the implementing class.</p>
<h3 id="heading-best-practices-and-considerations">Best Practices and Considerations:</h3>
<ul>
<li><strong>Use Sparingly:</strong> Default methods should be used judiciously. They are best suited for gradually evolving interfaces or for methods that have a common implementation across most implementing classes.</li>
<li><strong>Design With Care:</strong> When designing interfaces with <code>default</code> methods, consider how they might be used or overridden. It's important to document the expected behavior and interactions between default methods and other abstract methods in the interface.</li>
<li><strong>Overriding Default Methods:</strong> Just like any inherited method, default methods can be overridden in the implementing class. This should be done to provide a specific behavior different from the default implementation.</li>
</ul>
<h2 id="heading-35-how-does-switch-differ-in-java-7-and-java-8">35. How Does <code>switch</code> Differ in Java 7 and Java 8?</h2>
<h3 id="heading-in-java-7">In Java 7:</h3>
<p><strong>Limited Case Types:</strong> In Java 7, the <code>switch</code> statement supports limited types for the case labels, namely <code>byte</code>, <code>short</code>, <code>char</code>, <code>int</code>, and their corresponding Wrapper classes, along with <code>enum</code> types and, as of Java 7, <code>String</code>.</p>
<p><strong>Traditional Structure:</strong> The structure of the <code>switch</code> statement in Java 7 follows the conventional C-style format, with a series of case statements and an optional default case. Each case falls through to the next unless it ends with a <code>break</code> statement or other control flow statements like <code>return</code>.</p>
<p><strong>No Lambda Expressions:</strong> Java 7 does not support lambda expressions, and thus, they cannot be used within a <code>switch</code> statement or case labels.</p>
<h3 id="heading-in-java-8">In Java 8:</h3>
<p><strong>Lambda Expressions:</strong> While the basic syntax and supported types for the <code>switch</code> statement itself did not change in Java 8, the introduction of lambda expressions in this version brought a new paradigm in handling conditional logic. </p>
<p>This doesn’t directly change how <code>switch</code> works, but it offers alternative patterns for achieving similar outcomes, especially when used in conjunction with functional interfaces.</p>
<p><strong>Functional Programming Approach:</strong> Java 8 promotes a more functional programming style, encouraging the use of streams, lambda expressions, and method references. This can lead to alternatives for traditional <code>switch</code> statements, like using <code>Map</code> of lambdas for conditional logic, which can be more readable and concise.</p>
<p><strong>Enhanced Readability and Maintainability:</strong> Although not a direct change to the <code>switch</code> statement, the use of lambda expressions and functional programming practices in Java 8 can lead to more readable and maintainable code structures that might otherwise use complex <code>switch</code> or nested <code>if-else</code> statements.</p>
<h3 id="heading-practical-considerations">Practical Considerations:</h3>
<ul>
<li><strong>When to Use <code>switch</code> in Java 8:</strong> Despite the advancements in Java 8, the <code>switch</code> statement remains a viable and efficient method for controlling complex conditional logic. It is particularly useful when dealing with a known set of possible values, such as enum constants or strings.</li>
<li><strong>Combining <code>switch</code> with Lambdas:</strong> While you cannot use lambdas directly in a <code>switch</code> statement, Java 8 allows for more elegant ways to handle complex conditional logic that might traditionally have been a use case for <code>switch</code>. For example, using a <code>Map</code> with lambdas or method references can sometimes replace a complex <code>switch</code> statement.</li>
<li><strong>Performance Considerations:</strong> The performance of a <code>switch</code> statement is generally better than a series of <code>if-else</code> statements, especially when dealing with a large number of cases, due to its internal implementation using jump tables or binary search.</li>
</ul>
<h2 id="heading-36-explain-the-concept-of-autoboxing-and-unboxing">36. Explain the Concept of Autoboxing and Unboxing</h2>
<h3 id="heading-what-is-autoboxing">What is autoboxing?</h3>
<p>Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an <code>int</code> to an <code>Integer</code>, a <code>double</code> to a <code>Double</code>, and so on.</p>
<h3 id="heading-when-to-use-autoboxing">When to use autoboxing</h3>
<p>This feature is commonly used when working with collections, like <code>ArrayList</code> or <code>HashMap</code>, which can only store objects and not primitive types.</p>
<p>It simplifies the code by allowing direct assignment of a primitive value to a variable of the corresponding wrapper class.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-java">List&lt;Integer&gt; list = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;(); 
<span class="hljs-keyword">int</span> number = <span class="hljs-number">5</span>; 
list.add(number); 
<span class="hljs-comment">// Here, 'number' is automatically converted to an Integer object</span>
</code></pre>
<h3 id="heading-behind-the-scenes">Behind the Scenes:</h3>
<p>When autoboxing, the compiler essentially uses the valueOf method of the respective wrapper class to convert the primitive to its wrapper type.</p>
<p>For example, <code>Integer.valueOf(int)</code> is used for converting <code>int</code> to <code>Integer</code>.</p>
<h3 id="heading-performance-considerations">Performance Considerations:</h3>
<ul>
<li>While convenient, autoboxing can introduce performance overhead, especially in scenarios with extensive boxing and unboxing in tight loops, due to the creation of additional objects.</li>
</ul>
<h3 id="heading-what-is-unboxing">What is unboxing?</h3>
<p>Unboxing is the reverse process, where the Java compiler automatically converts an object of a wrapper type to its corresponding primitive type.</p>
<h3 id="heading-when-to-use-unboxing">When to use unboxing</h3>
<p>It is often used when performing arithmetic operations or comparisons on objects of wrapper classes, where primitive types are required.</p>
<p><strong>Example:</strong></p>
<pre><code>Integer wrappedInt = <span class="hljs-keyword">new</span> Integer(<span class="hljs-number">10</span>); 
int primitiveInt = wrappedInt; 
<span class="hljs-comment">// Unboxing from Integer to int</span>
</code></pre><h3 id="heading-behind-the-scenes-1">Behind the Scenes:</h3>
<p>During unboxing, the compiler uses the corresponding wrapper class's method to extract the primitive value. For instance, it uses <code>Integer.intValue()</code> to get the <code>int</code> from an <code>Integer</code>.</p>
<h3 id="heading-null-pointer-exception">Null Pointer Exception:</h3>
<p>A crucial point to consider is that unboxing a <code>null</code> object reference will throw a <code>NullPointerException</code>. This is a common bug in code that relies heavily on autoboxing and unboxing.</p>
<h3 id="heading-best-practices-and-considerations-1">Best Practices and Considerations:</h3>
<ul>
<li><strong>Be Aware of Implicit Conversions:</strong> It's important to be aware that these conversions are happening, as they can sometimes lead to unexpected behavior, especially with regards to <code>NullPointerExceptions</code> during unboxing of <code>null</code> references.</li>
<li><strong>Consider Performance:</strong> In performance-sensitive applications, prefer using primitives to avoid the overhead of autoboxing and unboxing.</li>
<li><strong>Null Safety:</strong> Always check for <code>null</code> before unboxing, to avoid potential <code>NullPointerExceptions</code>.</li>
<li><strong>Readability vs Efficiency:</strong> While autoboxing and unboxing significantly improve code readability and reduce boilerplate, be mindful of their impact on performance and choose wisely based on the application's context.</li>
</ul>
<h2 id="heading-37-describe-the-functionalinterface-annotation">37. Describe the <code>@FunctionalInterface</code> Annotation</h2>
<p>The <code>@FunctionalInterface</code> annotation in Java is a key feature that dovetails with the language's embrace of functional programming concepts, particularly since Java 8. It serves a specific purpose in defining and enforcing certain coding patterns, making it a vital tool for developers focusing on functional-style programming.</p>
<h3 id="heading-definition-and-purpose">Definition and Purpose</h3>
<p><code>@FunctionalInterface</code> is an annotation that marks an interface as a functional interface. </p>
<p>A functional interface in Java is an interface that contains exactly one abstract method. This restriction makes it eligible to be used in lambda expressions and method references, which are core components of Java's functional programming capabilities.</p>
<h3 id="heading-enforcing-single-abstract-method">Enforcing Single Abstract Method</h3>
<p>The primary role of <code>@FunctionalInterface</code> is to signal the compiler to enforce the rule of a single abstract method. If the annotated interface does not adhere to this rule, the compiler throws an error, ensuring the interface's contract is not accidentally broken by adding additional abstract methods.</p>
<h3 id="heading-usage-and-implications">Usage and Implications:</h3>
<ol>
<li><strong>Lambda Expressions:</strong> Functional interfaces provide target types for lambda expressions and method references.<br>For example, Java's standard <code>java.util.function</code> package contains several functional interfaces like <code>Function&lt;T,R&gt;</code>, <code>Predicate&lt;T&gt;</code>, <code>Consumer&lt;T&gt;</code>, which are widely used in stream operations and other functional programming scenarios.</li>
<li><strong>Optional but Recommended:</strong> While the <code>@FunctionalInterface</code> annotation is not mandatory for an interface to be considered a functional interface by the Java compiler, using it is considered best practice. It makes the developer's intention clear and ensures the contract of the functional interface is not inadvertently broken.</li>
<li><strong>Existing Interfaces:</strong> Many existing interfaces from earlier versions of Java naturally fit the definition of a functional interface. For example, <code>java.lang.Runnable</code> and <code>java.util.concurrent.Callable</code> are both functional interfaces as they have only one abstract method.</li>
</ol>
<h3 id="heading-example">Example:</h3>
<pre><code>@FunctionalInterface
public interface SimpleFunction {
    <span class="hljs-keyword">void</span> execute();
}
</code></pre><p>In this example, <code>SimpleFunction</code> is a functional interface with one abstract method <code>execute()</code>. The <code>@FunctionalInterface</code> annotation ensures that no additional abstract methods are inadvertently added.</p>
<h3 id="heading-best-practices-and-considerations-2">Best Practices and Considerations:</h3>
<ul>
<li><strong>Clarity and Documentation:</strong> Use <code>@FunctionalInterface</code> to communicate your intention clearly both to the compiler and to other developers. It serves as a form of documentation.</li>
<li><strong>Design with Care:</strong> When designing a functional interface, consider its general utility and how it fits into the broader application architecture, especially if it's intended to be used across different parts of the application.</li>
<li><strong>Avoid Overuse:</strong> While functional programming in Java can lead to more elegant and concise code, be cautious of overusing lambdas and functional interfaces, as they can make the code harder to read and debug if used excessively or inappropriately.</li>
<li><strong>Compatibility with Older Java Versions:</strong> Be aware that <code>@FunctionalInterface</code> is a Java 8 feature. If you're working on applications that need to be compatible with earlier Java versions, you won’t be able to use this feature.</li>
</ul>
<h2 id="heading-38-how-can-you-achieve-immutability-in-java">38. How Can You Achieve Immutability in Java?</h2>
<p>Achieving immutability in Java is a fundamental practice, particularly useful for creating robust, thread-safe applications. </p>
<p>An immutable object is one whose state cannot be modified after it is created. Here's a detailed and precise explanation of how to achieve immutability in Java:</p>
<h3 id="heading-core-principles-of-immutability">Core Principles of Immutability:</h3>
<ol>
<li><strong>No Setters:</strong> Immutable objects do not expose any methods to modify their state after construction. This typically means not providing any setter methods.</li>
<li><strong>Final Class:</strong> The class should be declared as <code>final</code> to prevent subclassing. Subclasses could add mutable state, undermining the immutability of the parent class.</li>
<li><strong>Final Fields:</strong> All fields should be <code>final</code>, ensuring they are assigned only once, typically within the constructor, and cannot be re-assigned.</li>
<li><strong>Private Fields:</strong> Fields should be private to prevent external modification and to encapsulate the data.</li>
<li><p><strong>No Direct Access to Mutable Objects:</strong></p>
</li>
<li><p>If your class has fields that are references to mutable objects (like arrays or collections), ensure these fields are not directly exposed or modified:</p>
</li>
<li>Do not provide methods that modify mutable objects.</li>
<li>Do not share references to the mutable objects. Provide copies of mutable objects when needed.</li>
</ol>
<h3 id="heading-how-to-create-an-immutable-class">How to Create an Immutable Class:</h3>
<pre><code>public final <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ImmutableClass</span> </span>{
    private final int value;
    private final <span class="hljs-built_in">String</span> name;
    private final List&lt;<span class="hljs-built_in">String</span>&gt; dataList;

    public ImmutableClass(int value, <span class="hljs-built_in">String</span> name, List&lt;<span class="hljs-built_in">String</span>&gt; dataList) {
        <span class="hljs-built_in">this</span>.value = value;
        <span class="hljs-built_in">this</span>.name = name;
        <span class="hljs-comment">// Creating a defensive copy of the mutable object</span>
        <span class="hljs-built_in">this</span>.dataList = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;(dataList);
    }

    public int getValue() {
        <span class="hljs-keyword">return</span> value;
    }

    public <span class="hljs-built_in">String</span> getName() {
        <span class="hljs-keyword">return</span> name;
    }

    <span class="hljs-comment">// Return a copy of the mutable object to maintain immutability</span>
    public List&lt;<span class="hljs-built_in">String</span>&gt; getDataList() {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> ArrayList&lt;&gt;(dataList);
    }
}
</code></pre><h3 id="heading-best-practices-and-considerations-3">Best Practices and Considerations:</h3>
<ul>
<li><strong>Defensive Copies:</strong> When dealing with mutable objects passed to the constructor or returned by methods, create defensive copies. This practice prevents external code from modifying the internal state of the immutable object.</li>
<li><strong>Immutable Collections:</strong> Utilize immutable collections (like those provided in Java 9 and later) to simplify the creation of classes with immutable collection fields.</li>
<li><strong>Performance Considerations:</strong> Be mindful of the performance implications of creating defensive copies, especially in performance-critical applications.</li>
<li><strong>Use in Multi-threaded Environments:</strong> Immutable objects are inherently thread-safe, making them ideal for use in multi-threaded environments.</li>
<li><strong>String and Wrapper Types:</strong> Leverage the immutability of String and wrapper types (Integer, Long, and so on) as part of your immutable objects.</li>
<li><strong>Design Strategy:</strong> Consider immutability as a design strategy, especially for objects representing values that are not expected to change, such as configuration data, constants, or natural data types.</li>
</ul>
<h3 id="heading-advantages-of-immutability">Advantages of Immutability:</h3>
<ol>
<li><strong>Simplicity and Clarity:</strong> Immutable objects are easier to understand and use. There's no need to track changes in state, reducing cognitive load.</li>
<li><strong>Thread Safety:</strong> Immutability eliminates issues related to concurrency and synchronization, as immutable objects can be freely shared between threads without synchronization.</li>
<li><strong>Caching and Reuse:</strong> Immutable objects can be cached and reused, as they are guaranteed not to change, reducing the overhead of object creation.</li>
<li><strong>Hashcode Caching:</strong> Immutable objects are great candidates for caching their hashcode, which can be beneficial in collections like <code>HashMaps</code> and <code>HashSets</code>.</li>
</ol>
<h2 id="heading-39-what-is-the-decorator-pattern">39. What is the Decorator Pattern?</h2>
<p>The Decorator Pattern is a structural design pattern used in object-oriented programming, and it's particularly useful for extending the functionality of objects at runtime. It is a robust alternative to subclassing, providing a more flexible approach to add responsibilities to objects without modifying their underlying classes.</p>
<h3 id="heading-purpose-of-decorator-pattern">Purpose of decorator pattern</h3>
<p>The Decorator Pattern allows you to attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.</p>
<p>The pattern involves a set of decorator classes that are used to wrap concrete components. Each decorator class has a reference to a component object and adds its own behavior either before or after delegating the task to the component object.</p>
<h3 id="heading-how-to-implement-the-decorator-pattern">How to implement the decorator pattern</h3>
<p>It typically involves an abstract decorator class that implements or extends the same interface or superclass as the objects it will dynamically add functionality to. Concrete decorators then extend the abstract decorator.</p>
<h3 id="heading-key-components">Key Components:</h3>
<ul>
<li><strong>Component:</strong> An interface or abstract class defining the operations that can be altered by decorators.</li>
<li><strong>Concrete Component:</strong> A class implementing or extending the Component, defining an object to which additional responsibilities can be attached.</li>
<li><strong>Decorator:</strong> An abstract class that extends or implements the Component interface and has a reference to a Component.</li>
<li><strong>Concrete Decorator:</strong> A class that extends the Decorator and adds functionalities to the Component it decorates.</li>
</ul>
<h3 id="heading-decorator-example-in-java">Decorator example in Java:</h3>
<pre><code><span class="hljs-comment">// Component</span>
public interface Coffee {
    <span class="hljs-built_in">String</span> getDescription();
    double getCost();
}

<span class="hljs-comment">// Concrete Component</span>
public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SimpleCoffee</span> <span class="hljs-title">implements</span> <span class="hljs-title">Coffee</span> </span>{
    @Override
    public <span class="hljs-built_in">String</span> getDescription() {
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Simple Coffee"</span>;
    }

    @Override
    public double getCost() {
        <span class="hljs-keyword">return</span> <span class="hljs-number">2.0</span>;
    }
}

<span class="hljs-comment">// Decorator</span>
public abstract <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CoffeeDecorator</span> <span class="hljs-title">implements</span> <span class="hljs-title">Coffee</span> </span>{
    protected final Coffee decoratedCoffee;

    public CoffeeDecorator(Coffee coffee) {
        <span class="hljs-built_in">this</span>.decoratedCoffee = coffee;
    }

    public <span class="hljs-built_in">String</span> getDescription() {
        <span class="hljs-keyword">return</span> decoratedCoffee.getDescription();
    }

    public double getCost() {
        <span class="hljs-keyword">return</span> decoratedCoffee.getCost();
    }
}

<span class="hljs-comment">// Concrete Decorator</span>
public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MilkCoffeeDecorator</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">CoffeeDecorator</span> </span>{
    public MilkCoffeeDecorator(Coffee coffee) {
        <span class="hljs-built_in">super</span>(coffee);
    }

    @Override
    public <span class="hljs-built_in">String</span> getDescription() {
        <span class="hljs-keyword">return</span> decoratedCoffee.getDescription() + <span class="hljs-string">", with milk"</span>;
    }

    @Override
    public double getCost() {
        <span class="hljs-keyword">return</span> decoratedCoffee.getCost() + <span class="hljs-number">0.5</span>;
    }
}
</code></pre><h3 id="heading-usage-and-advantages">Usage and Advantages:</h3>
<ul>
<li><strong>Flexibility:</strong> The Decorator Pattern provides a more flexible way to add responsibilities to objects compared to subclassing. New functionalities can be added at runtime.</li>
<li><strong>Avoid Class Explosion:</strong> It helps in avoiding an extensive hierarchy of subclasses when you need multiple combinations of functionalities.</li>
<li><strong>Single Responsibility Principle:</strong> Decorators allow functionalities to be divided into simple classes with single responsibilities.</li>
</ul>
<h3 id="heading-considerations">Considerations:</h3>
<ul>
<li><strong>Complexity:</strong> Overuse of the decorator pattern can lead to complexity, making the code harder to understand and maintain.</li>
<li><strong>Instantiation Management:</strong> Managing the instantiation of decorated objects can be challenging, especially when dealing with multiple layers of decoration.</li>
</ul>
<p>The Decorator Pattern is a powerful tool in a software developer's toolkit, offering a dynamic and flexible solution for extending object functionality. Understanding and applying this pattern can greatly enhance the design of software, particularly in situations where adding responsibilities to objects at runtime is necessary. </p>
<p>This pattern is highly valued in software development, as it showcases an ability to effectively manage and extend object functionalities without altering existing codebases, aligning with principles of maintainability and scalability.</p>
<h2 id="heading-40-explain-java-io-streams">40. Explain Java I/O Streams</h2>
<p>Java I/O (Input/Output) streams are a fundamental part of the Java I/O API, providing a robust framework for handling input and output operations in Java. Understanding these streams is crucial for efficient data handling in Java applications.</p>
<h3 id="heading-overview-of-java-io-streams">Overview of Java I/O Streams</h3>
<p>I/O streams in Java are used to read data from an input source and to write data to an output destination. The Java I/O API is rich and provides various classes to handle different types of data, like bytes, characters, objects, etc.</p>
<h3 id="heading-stream-types">Stream Types:</h3>
<p>Java I/O streams are broadly categorized into two types:</p>
<ul>
<li><strong>Byte Streams:</strong> Handle I/O of raw binary data.</li>
<li><strong>Character Streams:</strong> Handle I/O of character data, automatically handling character encoding and decoding.</li>
</ul>
<h4 id="heading-byte-streams">Byte Streams:</h4>
<ul>
<li><strong>Classes:</strong> <code>InputStream</code> and <code>OutputStream</code> are abstract classes at the hierarchy's root for byte streams.</li>
<li><strong>Usage:</strong> They are used for reading and writing binary data, such as image or video files.</li>
<li><strong>Example Classes:</strong> <code>FileInputStream</code>, <code>FileOutputStream</code>, <code>BufferedInputStream</code>, <code>BufferedOutputStream</code>, etc.</li>
</ul>
<h4 id="heading-character-streams">Character Streams:</h4>
<ul>
<li><strong>Classes:</strong> <code>Reader</code> and <code>Writer</code> are abstract classes for character streams.</li>
<li><strong>Usage:</strong> Suitable for handling textual data, ensuring correct interpretation of characters according to the default character encoding.</li>
<li><strong>Example Classes:</strong> <code>FileReader</code>, <code>FileWriter</code>, <code>BufferedReader</code>, <code>BufferedWriter</code>, etc.</li>
</ul>
<h3 id="heading-key-features-of-java-io-streams">Key Features of Java I/O Streams:</h3>
<ol>
<li><strong>Stream Hierarchy:</strong> Java uses a hierarchy of classes to manage different types of I/O operations, allowing for flexibility and reusability of code.</li>
<li><strong>Decorators:</strong> Java I/O uses decorators, where one stream wraps another and adds additional capabilities, like buffering, data conversion, and so on.</li>
<li><strong>Buffering:</strong> Buffering is a common practice in I/O streams to enhance I/O efficiency, allowing for the temporary storage of data in memory before it's written to or read from the actual I/O source.</li>
<li><strong>Exception Handling:</strong> I/O operations in Java are prone to errors like file not found, access denied, etc. Hence, most I/O operations throw <code>IOException</code>, which must be properly handled using try-catch blocks or thrown further.</li>
</ol>
<h3 id="heading-best-practices-1">Best Practices:</h3>
<ul>
<li><strong>Use Buffered Streams:</strong> Always use buffered streams (<code>BufferedInputStream</code>, <code>BufferedOutputStream</code>, <code>BufferedReader</code>, <code>BufferedWriter</code>) for efficient I/O operations, as they reduce the number of actual I/O operations by buffering chunks of data.</li>
<li><strong>Close Streams:</strong> Ensure streams are closed after their operation is complete to free up system resources. This is typically done in a finally block or using try-with-resources introduced in Java 7.</li>
<li><strong>Error Handling:</strong> Implement robust error handling. I/O operations are susceptible to many issues, so proper exception handling is crucial.</li>
<li><strong>Character Encoding:</strong> Be mindful of character encoding while using character streams. Incorrect handling of encoding can lead to data corruption.</li>
</ul>
<h3 id="heading-practical-example">Practical Example:</h3>
<pre><code><span class="hljs-keyword">try</span> (BufferedReader reader = <span class="hljs-keyword">new</span> BufferedReader(<span class="hljs-keyword">new</span> FileReader(<span class="hljs-string">"input.txt"</span>));
     BufferedWriter writer = <span class="hljs-keyword">new</span> BufferedWriter(<span class="hljs-keyword">new</span> FileWriter(<span class="hljs-string">"output.txt"</span>))) {

    <span class="hljs-built_in">String</span> line;
    <span class="hljs-keyword">while</span> ((line = reader.readLine()) != <span class="hljs-literal">null</span>) {
        writer.write(line);
        writer.newLine();
    }
} <span class="hljs-keyword">catch</span> (IOException e) {
    e.printStackTrace();
}
</code></pre><p>In this example, <code>BufferedReader</code> and <code>BufferedWriter</code> are used for reading from and writing to a text file, demonstrating the use of character streams with buffering for efficiency.</p>
<p>Java I/O streams form the backbone of data handling in Java applications. Understanding the distinction between byte and character streams, along with the proper use of buffering and exception handling, is essential for writing efficient, robust, and maintainable Java code. </p>
<p>This knowledge is vital for Java developers and is often a subject of interest in technical interviews, showcasing one's capability to handle data proficiently in Java applications.</p>
<h2 id="heading-41-how-does-the-garbage-collector-work-in-java">41. How Does the Garbage Collector Work in Java?</h2>
<p>In Java, garbage collection (GC) is a critical process of automatically freeing memory by reclaiming space from objects that are no longer in use, ensuring efficient memory management. </p>
<p>Understanding how the garbage collector works in Java is essential for writing high-performance applications and is a key area of knowledge in professional Java development.</p>
<h3 id="heading-overview-of-garbage-collection-in-java">Overview of Garbage Collection in Java</h3>
<p>The primary function of garbage collection in Java is to identify and discard objects that are no longer needed by a program. This prevents memory leaks and optimizes memory usage.</p>
<h3 id="heading-automatic-memory-management">Automatic Memory Management</h3>
<p>Unlike languages where memory management is manual (like C/C++), Java provides automatic memory management through its garbage collector, which runs in the background.</p>
<h3 id="heading-how-the-garbage-collector-works">How the Garbage Collector Works</h3>
<h4 id="heading-object-creation-and-heap-storage">Object Creation and Heap Storage:</h4>
<p>In Java, objects are created in a heap memory area. This heap is divided into several parts – Young Generation, Old Generation (or Tenured Generation), and Permanent Generation (replaced by Metaspace in Java 8).</p>
<ol>
<li><strong>Young Generation:</strong> Newly created objects reside in the Young Generation, which is further divided into three parts: one Eden space and two Survivor spaces (S0 and S1).<br>Most objects die young. When the Eden space fills up, a minor GC is triggered, moving surviving objects to one of the Survivor spaces (S0 or S1) and clearing Eden.</li>
<li><strong>Aging of Objects:</strong> As objects survive more garbage collection cycles, they age. After surviving certain cycles, they are moved to the Old Generation.</li>
<li><strong>Old Generation:</strong> The Old Generation stores long-living objects. A more comprehensive form of GC, known as major GC, occurs here, which is generally more time-consuming.</li>
<li><strong>Metaspace (Java 8 and above):</strong> Metaspace stores metadata of classes. Unlike the PermGen (Permanent Generation) space in earlier Java versions, Metaspace uses native memory, and its size is not fixed but can be configured.</li>
</ol>
<h3 id="heading-types-of-garbage-collectors-in-java">Types of Garbage Collectors in Java:</h3>
<ul>
<li><strong>Serial GC:</strong> Suitable for single-threaded environments. It freezes all application threads during garbage collection.</li>
<li><strong>Parallel GC:</strong> Also known as Throughput Collector, it uses multiple threads for young generation garbage collection but stops all application threads during major GC.</li>
<li><strong>Concurrent Mark Sweep (CMS) GC:</strong> Minimizes pauses by doing most of its work concurrently with application threads but requires more CPU resources.</li>
<li><strong>G1 Garbage Collector:</strong> Designed for large heap memory areas, it divides the heap into regions and prioritizes GC on regions with the most garbage first.</li>
</ul>
<h3 id="heading-garbage-collection-processes">Garbage Collection Processes</h3>
<p>The process starts by <strong>marking</strong> all reachable objects. Reachable objects are those that are accessible directly or indirectly through references from root objects (like local variables, static fields, etc.).</p>
<p>Unreachable objects (those not marked as reachable) are considered for <strong>deletion</strong>.</p>
<p>To prevent fragmentation and optimize memory usage, some garbage collectors perform <strong>compaction</strong>, moving surviving objects closer together.</p>
<h3 id="heading-best-practices-and-considerations-4">Best Practices and Considerations:</h3>
<ul>
<li><strong>Avoid Memory Leaks:</strong> Despite automatic garbage collection, memory leaks can still occur (for example, through static references). It's crucial to be mindful of object references and their lifecycles.</li>
<li><strong>GC Tuning:</strong> For high-performance applications, GC tuning can be essential. Understanding different garbage collector types and their configuration parameters allows for optimal tuning according to application needs.</li>
<li><strong>Monitoring and Profiling:</strong> Regular monitoring of garbage collection and memory usage is important, especially for applications with high throughput or large heaps.</li>
</ul>
<p>Garbage collection in Java is a sophisticated system designed to efficiently manage memory in the Java Virtual Machine (JVM). An in-depth understanding of how garbage collection works, its types, and its impact on application performance is essential for Java developers, particularly those working on large-scale, high-performance applications. </p>
<p>This knowledge not only helps in writing efficient and robust applications but also is a valuable skill in troubleshooting and performance tuning, aspects highly regarded in the field of software development.</p>
<h2 id="heading-42-what-are-the-benefits-of-using-java-nio">42. What Are the Benefits of Using Java NIO?</h2>
<p>Java NIO (New Input/Output), introduced in JDK 1.4, marks a substantial advancement in Java's approach to I/O operations. It was developed to address the constraints of traditional I/O methods, leading to improved scalability and efficiency. </p>
<p>This makes Java NIO particularly advantageous in scenarios demanding high throughput and concurrent access. </p>
<p>Let’s discuss the key benefits of using Java NIO in detail.</p>
<h3 id="heading-1-channels-and-buffers-enhanced-data-handling">1. Channels and Buffers: Enhanced Data Handling</h3>
<ul>
<li><strong>Channels</strong>: These are bi-directional conduits allowing both reading and writing operations. Unlike traditional unidirectional streams, channels simplify I/O patterns, especially for network sockets, by enabling two-way communication within a single channel.</li>
<li><strong>Buffers</strong>: Acting as fixed-size data containers, buffers allow batch processing of data. This is more efficient compared to the byte-by-byte processing in traditional I/O, as it enables handling data in larger, more manageable blocks.</li>
</ul>
<h3 id="heading-2-non-blocking-and-asynchronous-io">2. Non-blocking and Asynchronous I/O</h3>
<p>Java NIO supports non-blocking and asynchronous I/O operations, a stark contrast to the blocking nature of traditional I/O where a thread remains idle until an operation completes. </p>
<p>This feature of NIO means a thread can initiate an I/O operation and continue performing other tasks without waiting for the I/O process to finish. This capability significantly enhances the scalability and responsiveness of applications, making them more efficient in handling multiple concurrent I/O requests.</p>
<h3 id="heading-3-practical-applications">3. Practical Applications</h3>
<p>Java NIO is particularly effective in environments that require high-performance and low latency, such as:</p>
<ul>
<li><strong>Web and Application Servers</strong>: Managing high-volume network traffic efficiently.</li>
<li><strong>Real-time Systems</strong>: Like trading platforms where quick data processing is critical.</li>
<li><strong>Big Data Applications</strong>: Benefiting from efficient handling of large datasets.</li>
<li><strong>File-based Database Systems</strong>: Where efficient file I/O operations are crucial.</li>
</ul>
<h3 id="heading-4-channels-the-foundation-of-nios-architecture">4. Channels: The Foundation of NIO’s Architecture</h3>
<p>Channels serve as the backbone of NIO, providing a more unified and simplified interface for various I/O operations. They come in different types, each catering to specific needs:</p>
<ul>
<li><strong>FileChannel</strong>: For file operations.</li>
<li><strong>SocketChannel and ServerSocketChannel</strong>: For TCP network communications.</li>
<li><strong>DatagramChannel</strong>: For UDP operations.</li>
<li><strong>Pipes</strong>: For inter-thread communication. Particularly in network operations, the ability of channels to operate in a non-blocking mode allows a single thread to handle multiple connections, enhancing the application’s scalability.</li>
</ul>
<h3 id="heading-5-buffers-central-to-nios-data-transfer">5. Buffers: Central to NIO’s Data Transfer</h3>
<p>Buffers in NIO are essential for data transfer, acting as temporary storage for data during I/O operations. Their key operations include:</p>
<ul>
<li><strong>Put and Get</strong>: For writing and reading data.</li>
<li><strong>Flip</strong>: To switch modes between reading and writing.</li>
<li><strong>Clear and Compact</strong>: Preparing the buffer for new data. Different buffer types (like ByteBuffer, CharBuffer, IntBuffer) cater to various data primitives, enhancing the flexibility and efficiency of data handling. Notably, direct buffers, which are allocated outside of the JVM heap, can provide faster I/O operations, though they come with higher allocation and deallocation costs.</li>
</ul>
<h3 id="heading-6-selectors-streamlining-scalable-io-operations">6. Selectors: Streamlining Scalable I/O Operations</h3>
<p>Selectors are a unique NIO feature enabling a single thread to monitor multiple channels for readiness, thus efficiently managing numerous I/O operations. This reduces the need for multiple threads, cutting down on resource usage and context switching, which is particularly advantageous in high-performance environments.</p>
<h3 id="heading-7-improved-performance-and-scalability">7. Improved Performance and Scalability</h3>
<p>The amalgamation of channels, buffers, and selectors provides a substantial performance boost. The non-blocking nature of NIO minimizes idle thread time, and managing multiple channels with a single thread significantly improves the scalability. This is pivotal in server environments dealing with numerous simultaneous connections.</p>
<p>Java NIO offers a robust, scalable, and efficient framework for handling I/O operations, addressing many of the limitations of traditional I/O. Its design is particularly advantageous for high-throughput and concurrent-processing systems. </p>
<p>While the complexity of NIO might be higher compared to traditional I/O, the performance and scalability benefits it provides make it an indispensable tool for developers working on large-scale, I/O-intensive Java applications.</p>
<h2 id="heading-43-explain-the-observer-pattern">43. Explain the Observer Pattern</h2>
<p>The Observer pattern is a design pattern where an object, known as the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. </p>
<p>It's particularly useful in the scenario where a single object needs to notify an array of objects about a change in its state. In the context of a newsletter system, the Observer pattern can be effectively used to notify subscribers whenever a new post is available.</p>
<h3 id="heading-how-to-implement-the-observer-pattern-for-a-newsletter-system">How to Implement the Observer Pattern for a Newsletter System</h3>
<p>Let's break down the implementation using the Observer pattern in the context of a newsletter system:</p>
<ol>
<li><strong>Subject (Newsletter)</strong>: This is the entity being observed. It will notify all attached observers when a new post is available.</li>
<li><strong>Observer (Subscriber)</strong>: These are the observers who wish to be notified about new posts in the newsletter.</li>
<li><strong>Client</strong>: This will use both the Subject and Observers.</li>
</ol>
<h4 id="heading-step-1-create-the-subject-class-newsletter">Step 1: Create the Subject Class (Newsletter)</h4>
<pre><code><span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.List;

public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Newsletter</span> </span>{
    private List&lt;Subscriber&gt; subscribers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
    private <span class="hljs-built_in">String</span> latestPost;

    public <span class="hljs-keyword">void</span> setLatestPost(<span class="hljs-built_in">String</span> post) {
        <span class="hljs-built_in">this</span>.latestPost = post;
        notifyAllSubscribers();
    }

    public <span class="hljs-keyword">void</span> attach(Subscriber subscriber){
        subscribers.add(subscriber);      
    }

    private <span class="hljs-keyword">void</span> notifyAllSubscribers(){
        <span class="hljs-keyword">for</span> (Subscriber subscriber : subscribers) {
            subscriber.update(latestPost);
        }
    }   
}
</code></pre><h4 id="heading-step-2-create-the-observer-abstract-class-subscriber">Step 2: Create the Observer Abstract Class (Subscriber)</h4>
<pre><code>public abstract <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Subscriber</span> </span>{
    protected Newsletter newsletter;
    public abstract <span class="hljs-keyword">void</span> update(<span class="hljs-built_in">String</span> update);
}
</code></pre><h4 id="heading-step-3-create-concrete-observer-classes">Step 3: Create Concrete Observer Classes</h4>
<p><strong>EmailSubscriber.java</strong></p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmailSubscriber</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Subscriber</span> </span>{
    public EmailSubscriber(Newsletter newsletter) {
        <span class="hljs-built_in">this</span>.newsletter = newsletter;
        <span class="hljs-built_in">this</span>.newsletter.attach(<span class="hljs-built_in">this</span>);
    }

    @Override
    public <span class="hljs-keyword">void</span> update(<span class="hljs-built_in">String</span> post) {
        System.out.println(<span class="hljs-string">"Email Subscriber: New post available! "</span> + post);
    }
}
</code></pre><p><strong>SMSSubscriber.java</strong></p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SMSSubscriber</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Subscriber</span> </span>{
    public SMSSubscriber(Newsletter newsletter) {
        <span class="hljs-built_in">this</span>.newsletter = newsletter;
        <span class="hljs-built_in">this</span>.newsletter.attach(<span class="hljs-built_in">this</span>);
    }

    @Override
    public <span class="hljs-keyword">void</span> update(<span class="hljs-built_in">String</span> post) {
        System.out.println(<span class="hljs-string">"SMS Subscriber: New post available! "</span> + post);
    }
}
</code></pre><h4 id="heading-step-4-use-the-newsletter-and-concrete-subscriber-objects">Step 4: Use the Newsletter and Concrete Subscriber Objects</h4>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NewsletterSystemDemo</span> </span>{
    public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span>[] args) {
        Newsletter newsletter = <span class="hljs-keyword">new</span> Newsletter();

        <span class="hljs-keyword">new</span> EmailSubscriber(newsletter);
        <span class="hljs-keyword">new</span> SMSSubscriber(newsletter);

        newsletter.setLatestPost(<span class="hljs-string">"Understanding the Observer Pattern"</span>);
        newsletter.setLatestPost(<span class="hljs-string">"Observer Pattern in Real-world Applications"</span>);
    }
}
</code></pre><h4 id="heading-step-5-output-verification">Step 5: Output Verification</h4>
<p>When running <code>NewsletterSystemDemo</code>, the output will be something like:</p>
<pre><code>Email Subscriber: New post available! Understanding the Observer Pattern
SMS Subscriber: New post available! Understanding the Observer Pattern
Email Subscriber: New post available! Observer Pattern <span class="hljs-keyword">in</span> Real-world Applications
SMS Subscriber: New post available! Observer Pattern <span class="hljs-keyword">in</span> Real-world Applications
</code></pre><p>This output indicates that both the email and SMS subscribers are notified whenever the newsletter has a new post.</p>
<p>The Observer pattern provides a clean and straightforward way to implement a subscription mechanism in a newsletter system, ensuring that all subscribers are automatically updated with the latest posts. </p>
<p>This pattern enhances modularity and separation of concerns, making the system easier to understand, maintain, and extend.</p>
<h2 id="heading-44-explain-the-purpose-of-the-this-keyword">44. Explain the Purpose of the <code>this</code> Keyword.</h2>
<p>The <code>this</code> keyword in Java serves a very specific and useful purpose. It refers to the current instance of the class in which it is used. This is particularly valuable in scenarios where you need to distinguish between class fields (instance variables) and parameters or variables within a method that have the same name. Let's break it down:</p>
<p><strong>Reference to Instance Variables:</strong> When a class’s field is shadowed by a method or constructor parameter, <code>this</code> can be used for referencing the class's field. For instance, in a setter method, <code>this</code> helps differentiate between the instance variable and the parameter passed to the method.</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    private <span class="hljs-built_in">String</span> name;

    public <span class="hljs-keyword">void</span> setName(<span class="hljs-built_in">String</span> name) {
        <span class="hljs-built_in">this</span>.name = name; <span class="hljs-comment">// 'this.name' refers to the field, 'name' refers to the parameter</span>
    }
}
</code></pre><p><strong>Calling One Constructor from Another:</strong> In a class with overloaded constructors, <code>this</code> can be used to call one constructor from another, avoiding code duplication.</p>
<pre><code>public User(<span class="hljs-built_in">String</span> name) {
    <span class="hljs-built_in">this</span>.name = name;
}

public User() {
    <span class="hljs-built_in">this</span>(<span class="hljs-string">"Default Name"</span>);
}
</code></pre><p><strong>Returning the Current Instance:</strong> Methods can return <code>this</code> to return the current class instance. This is often used in method chaining.</p>
<pre><code>public User setName(<span class="hljs-built_in">String</span> name) {
    <span class="hljs-built_in">this</span>.name = name;
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
}
</code></pre><p><strong>Passing the Current Instance to Another Method:</strong> <code>this</code> can be passed as an argument in the method call or constructor call. This is common in event handling.</p>
<p><strong>Disambiguation:</strong> It eliminates ambiguity when instance variables and parameters or local variables share the same name.</p>
<h2 id="heading-45-explain-javas-try-with-resources">45. Explain Java's try-with-resources.</h2>
<p>Java's try-with-resources, introduced in Java 7, is a mechanism that ensures more efficient handling of resources, like files or sockets, in Java. Its primary purpose is to simplify the cleanup of resources which must be closed after their operations are completed.</p>
<h4 id="heading-key-characteristics">Key Characteristics:</h4>
<p><strong>Automatic Resource Management:</strong> In try-with-resources, resources declared within the try clause are automatically closed at the end of the statement, even if exceptions are thrown. This reduces boilerplate code significantly as compared to traditional try-catch-finally blocks.</p>
<p><strong>Syntax:</strong> The resources that implement <code>java.lang.AutoCloseable</code> or <code>java.io.Closeable</code> are declared and initialized within parentheses just after the <code>try</code> keyword.</p>
<pre><code><span class="hljs-keyword">try</span> (BufferedReader br = <span class="hljs-keyword">new</span> BufferedReader(<span class="hljs-keyword">new</span> FileReader(<span class="hljs-string">"path/to/file.txt"</span>))) {
    <span class="hljs-comment">// Read from the file</span>
} <span class="hljs-keyword">catch</span> (IOException e) {
    <span class="hljs-comment">// Handle possible I/O errors</span>
}
</code></pre><ol>
<li>Here, the <code>BufferedReader</code> instance is automatically closed when the try block exits, regardless of whether it exits normally or due to an exception.</li>
<li><strong>Exception Handling:</strong> Any exception thrown by the automatic closure of resources is suppressed if an exception is thrown in the try block. These suppressed exceptions can be retrieved using <code>Throwable.getSuppressed()</code> method.</li>
<li><strong>Improved Readability and Reliability:</strong> This structure enhances code readability and reliability. It reduces the risk of resource leaks, as the closing of resources is handled automatically.</li>
<li><strong>Use in Custom Resources:</strong> Custom classes can also utilize this mechanism by implementing the <code>AutoCloseable</code> interface and overriding the <code>close</code> method.</li>
</ol>
<h4 id="heading-practical-implications">Practical Implications:</h4>
<p>In real-world applications, try-with-resources ensures that resources like file streams, database connections, or network sockets are closed properly, preventing resource leaks which could lead to performance issues and other bugs. It is especially valuable in large-scale applications where resource management is critical for efficiency and reliability.</p>
<h2 id="heading-46-explain-the-difference-between-c-and-java">46. Explain the Difference between C++ and Java.</h2>
<p>When distinguishing between C++ and Java, it's important to understand that both are powerful programming languages with their unique characteristics and use cases. </p>
<p>They share some similarities, as both are object-oriented and have similar syntax (being influenced by C), but there are key differences that set them apart.</p>
<h3 id="heading-language-nature-and-design-philosophy">Language Nature and Design Philosophy:</h3>
<p><strong>C++</strong> is a multi-paradigm language that supports both procedural and object-oriented programming. It's often chosen for system-level programming due to its efficiency and fine-grained control over memory management.</p>
<p><strong>Java</strong>, on the other hand, is primarily object-oriented and designed with a simpler approach to avoid common programming errors (like pointer errors in C++). Java's design principle "Write Once, Run Anywhere" (WORA) emphasizes portability, which is achieved through the Java Virtual Machine (JVM).</p>
<h3 id="heading-memory-management">Memory Management:</h3>
<p>In <strong>C++</strong>, memory management is manual. Programmers have direct control over memory allocation and deallocation using operators like <code>new</code> and <code>delete</code>.</p>
<p><strong>Java</strong> abstracts away the complexity of direct memory management through its Automatic Garbage Collection, which periodically frees memory that's no longer in use, reducing the likelihood of memory leaks but at the cost of less control and potential overhead.</p>
<h3 id="heading-platform-dependency-and-portability">Platform Dependency and Portability:</h3>
<p><strong>C++</strong> is platform-dependent. A C++ program needs to be compiled for each specific platform it's intended to run on, which can lead to more work when targeting multiple platforms.</p>
<p><strong>Java</strong> is platform-independent at the source level. Java programs are compiled into bytecode, which can run on any device equipped with a JVM, making it highly portable.</p>
<h3 id="heading-runtime-and-performance">Runtime and Performance:</h3>
<p><strong>C++</strong> generally offers higher performance than Java. It compiles directly to machine code, which the CPU executes, resulting in faster execution suitable for performance-critical applications.</p>
<p><strong>Java</strong> may have slower performance due to the added abstraction layer of the JVM. But improvements in Just-In-Time (JIT) compilers within the JVM have significantly narrowed this performance gap.</p>
<h3 id="heading-pointers-and-memory-safety">Pointers and Memory Safety:</h3>
<p><strong>C++</strong> supports both pointers and references, allowing for powerful, albeit potentially risky, memory manipulation.</p>
<p><strong>Java</strong> has references but does not support pointers (at least not in the traditional sense), reducing the risk of memory access errors, thereby increasing program safety.</p>
<h3 id="heading-exception-handling">Exception Handling:</h3>
<p><strong>C++</strong> supports exception handling but does not enforce error handling (uncaught exceptions can lead to undefined behavior).</p>
<p><strong>Java</strong> has a robust exception handling mechanism, requiring checked exceptions to be caught or declared in the method signature, promoting better error management practices.</p>
<h3 id="heading-multi-threading">Multi-Threading:</h3>
<p><strong>C++</strong> has more complex approaches to multi-threading and requires careful management to ensure thread safety.</p>
<p><strong>Java</strong> provides built-in support for multi-threading with synchronized methods and blocks, making concurrent programming more manageable.</p>
<h3 id="heading-standard-template-library-stl-vs-java-standard-library">Standard Template Library (STL) vs. Java Standard Library:</h3>
<p><strong>C++</strong>'s STL is a powerful library that offers containers, algorithms, iterators, and so on for efficient data manipulation.</p>
<p><strong>Java</strong>'s Standard Library provides a rich set of APIs, including collections, streams, networking, and so on with a focus on ease of use.</p>
<h3 id="heading-legacy-and-use-cases">Legacy and Use Cases:</h3>
<p><strong>C++</strong> is often chosen for system/software development, game development, and applications where hardware access and performance are critical.</p>
<p><strong>Java</strong> is widely used in enterprise environments, web services, and Android app development due to its portability and robust libraries.</p>
<p>Both C++ and Java have their strengths and are chosen based on the requirements of the project. </p>
<p>C++ is preferred for scenarios where performance and memory control are crucial, while Java is ideal for applications where portability and ease of use are more important. </p>
<p>Understanding these differences is key in selecting the right language for a particular task or project, and adapting to the strengths of each can lead to more efficient and effective programming practices.</p>
<h2 id="heading-47-what-is-polymorphism-provide-an-example">47. What is Polymorphism? Provide an Example.</h2>
<p>Polymorphism, a fundamental concept in object-oriented programming, allows objects to be treated as instances of their parent class or interface. It’s a Greek word meaning “many shapes” and in programming, it refers to the ability of a single function or method to work in different ways based on the object it is acting upon. </p>
<p>There are two primary types of polymorphism: compile-time (or static) polymorphism and runtime (or dynamic) polymorphism.</p>
<p><strong>Compile-Time Polymorphism</strong>: This is achieved through method overloading and operator overloading. It’s called compile-time polymorphism because the decision about which method to call is made by the compiler.</p>
<p><strong>Method Overloading</strong> involves having multiple methods in the same scope, with the same name but different parameters.</p>
<p><strong>Example</strong>:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MathOperation</span> </span>{
    <span class="hljs-comment">// Method with two integer parameters</span>
    int operate(int a, int b) {
        <span class="hljs-keyword">return</span> a + b;
    }

    <span class="hljs-comment">// Same method with double parameters</span>
    double operate(double a, double b) {
        <span class="hljs-keyword">return</span> a + b;
    }
}
</code></pre><p>In this example, the <code>operate</code> method is overloaded with different parameter types, allowing it to behave differently based on the type of arguments passed.</p>
<p><strong>Runtime Polymorphism</strong>: This is mostly achieved through method overriding, which is a feature of inheritance in object-oriented programming. In runtime polymorphism, the method to be executed is determined at runtime.</p>
<p><strong>Method Overriding</strong> involves defining a method in a subclass that has the same name, return type, and parameters as a method in its superclass.</p>
<p><strong>Example</strong>:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-keyword">void</span> speak() {
        System.out.println(<span class="hljs-string">"The animal makes a sound"</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
    @Override
    <span class="hljs-keyword">void</span> speak() {
        System.out.println(<span class="hljs-string">"The dog barks"</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    public <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> main(<span class="hljs-built_in">String</span> args[]) {
        Animal myAnimal = <span class="hljs-keyword">new</span> Dog();
        myAnimal.speak();  <span class="hljs-comment">// Outputs: The dog barks</span>
    }
}
</code></pre><p>In this example, the <code>speak</code> method in the subclass <code>Dog</code> overrides the <code>speak</code> method in its superclass <code>Animal</code>. When the <code>speak</code> method is called on an object of type <code>Dog</code>, the overridden method in the <code>Dog</code> class is executed, demonstrating runtime polymorphism.</p>
<h3 id="heading-why-polymorphism-is-important">Why Polymorphism is Important</h3>
<ol>
<li><strong>Flexibility and Extensibility</strong>: Polymorphism allows for flexible and extensible code. You can create a more generalized code that works on the superclass type, and it automatically adapts to the specific subclass types.</li>
<li><strong>Code Reusability</strong>: It enables the reuse of code through inheritance and the ability to override or overload methods.</li>
<li><strong>Loose Coupling</strong>: By using polymorphic behavior, components can be designed loosely coupled, which means a change in one part of the system causes minimal or no effect on other parts of the system.</li>
<li><strong>Simplifies Code Maintenance</strong>: With polymorphism, developers can write more maintainable and manageable code, as changes to a superclass are inherited by all subclasses, reducing the need for changes across multiple classes.</li>
</ol>
<p>Polymorphism is a cornerstone in the world of object-oriented programming, enabling more dynamic and flexible code. It allows objects to interact in a more abstract manner, focusing on the shared behavior rather than the specific types. </p>
<p>Understanding and effectively using polymorphism can lead to more robust and maintainable code, a crucial aspect for any software developer looking to excel in their field.</p>
<h2 id="heading-48-how-can-you-avoid-memory-leaks-in-java">48. How Can You Avoid Memory Leaks in Java?</h2>
<p>Avoiding memory leaks in Java, despite its automated garbage collection mechanism, requires a deep understanding of how memory allocation and release work in Java, alongside meticulous coding practices and effective use of analysis tools. </p>
<p>Let’s delve into some advanced and specific strategies for preventing memory leaks in Java applications:</p>
<h3 id="heading-understand-object-lifecycle-and-scope">Understand Object Lifecycle and Scope:</h3>
<ul>
<li><strong>Scope Management</strong>: Ensure objects are scoped as narrowly as possible. For instance, use local variables within methods rather than class-level variables if the data does not need to persist beyond the method’s execution context.</li>
<li><strong>Reference Management</strong>: Be cautious with static references. Static fields can keep objects alive for the lifetime of the class, potentially leading to memory leaks.</li>
</ul>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ScopedObject</span> </span>{
    public <span class="hljs-keyword">void</span> methodScope() {
        <span class="hljs-comment">// Local variable, limited to method scope</span>
        <span class="hljs-built_in">String</span> localString = <span class="hljs-string">"This is a local string"</span>;
        <span class="hljs-comment">// ...</span>
    }
    <span class="hljs-comment">// Avoid using unnecessary class-level static variables</span>
}
</code></pre><h3 id="heading-efficient-use-of-collections">Efficient Use of Collections:</h3>
<ul>
<li><strong>WeakHashMap</strong>: For cache implementations, consider using <code>WeakHashMap</code>. It uses weak references for keys, which allows keys (and their associated values) to be garbage-collected when no longer in use.</li>
<li><strong>Data Structure Choice</strong>: Be mindful of the choice of data structure. For example, use <code>ArrayList</code> over <code>LinkedList</code> for large lists of data where frequent access is required, as <code>LinkedList</code> can consume more memory due to the storage of additional node references.</li>
</ul>
<pre><code><span class="hljs-keyword">import</span> java.lang.ref.WeakReference;
<span class="hljs-keyword">import</span> java.util.WeakHashMap;

public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CacheExample</span> </span>{
    private WeakHashMap&lt;WeakReference&lt;<span class="hljs-built_in">String</span>&gt;, <span class="hljs-built_in">String</span>&gt; cache = <span class="hljs-keyword">new</span> WeakHashMap&lt;&gt;();

    public <span class="hljs-keyword">void</span> addToCache(<span class="hljs-built_in">String</span> key, <span class="hljs-built_in">String</span> value) {
        cache.put(<span class="hljs-keyword">new</span> WeakReference&lt;&gt;(key), value);
    }
}
</code></pre><h3 id="heading-leveraging-weakreferences-and-softreferences">Leveraging <code>WeakReferences</code> and <code>SoftReferences</code>:</h3>
<ul>
<li><strong>SoftReferences for Caches</strong>: Use <code>SoftReference</code> for memory-sensitive caches. The garbage collector will only remove soft-referenced objects if it needs memory, making them more persistent than weak references.</li>
<li><strong>WeakReferences for Listeners</strong>: Utilize <code>WeakReference</code> for listener patterns where listeners might not be explicitly removed.</li>
</ul>
<pre><code><span class="hljs-keyword">import</span> java.lang.ref.SoftReference;

public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CacheWithSoftReference</span> </span>{
    private SoftReference&lt;<span class="hljs-built_in">String</span>&gt; cachedData;

    public <span class="hljs-keyword">void</span> cacheData(<span class="hljs-built_in">String</span> data) {
        cachedData = <span class="hljs-keyword">new</span> SoftReference&lt;&gt;(data);
    }
}
</code></pre><h3 id="heading-managing-resources-and-io">Managing Resources and I/O:</h3>
<ul>
<li><strong>AutoCloseable and Try-with-Resources</strong>: For resources like streams, files, and connections, use try-with-resources for automatic closure. Ensure that objects implementing <code>AutoCloseable</code> are closed properly to release resources.</li>
</ul>
<pre><code><span class="hljs-keyword">import</span> java.io.BufferedReader;
<span class="hljs-keyword">import</span> java.io.FileReader;
<span class="hljs-keyword">import</span> java.io.IOException;

public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AutoCloseExample</span> </span>{
    public <span class="hljs-keyword">void</span> readFile(<span class="hljs-built_in">String</span> path) throws IOException {
        <span class="hljs-keyword">try</span> (BufferedReader br = <span class="hljs-keyword">new</span> BufferedReader(<span class="hljs-keyword">new</span> FileReader(path))) {
            <span class="hljs-comment">// Read file...</span>
        }
    }
}
</code></pre><h3 id="heading-inner-classes-handling">Inner Classes Handling:</h3>
<ul>
<li><strong>Static Inner Classes</strong>: Prefer static inner classes over non-static to avoid the implicit reference to the outer class instance, which can prevent the outer instance from being garbage-collected.</li>
</ul>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OuterClass</span> </span>{
    private <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">InnerClass</span> </span>{
        <span class="hljs-comment">// Static inner class does not hold an implicit reference to the outer class</span>
    }
}
</code></pre><h3 id="heading-profiling-and-leak-detection">Profiling and Leak Detection:</h3>
<ul>
<li><strong>Heap Dump Analysis</strong>: Regularly analyze heap dumps in tools like Eclipse Memory Analyzer (MAT) to detect large objects and potential memory leaks.</li>
<li><strong>Java Flight Recorder</strong>: Use Java Flight Recorder for runtime analysis and monitoring, which can help identify memory leaks.</li>
</ul>
<pre><code><span class="hljs-comment">// Example of heap dump analysis or Java Flight Recorder would be more of a tool usage </span>
<span class="hljs-comment">// demonstration than a code snippet.</span>
</code></pre><h3 id="heading-threadlocal-variables-management"><code>ThreadLocal</code> Variables Management:</h3>
<ul>
<li><strong>Explicit Removal</strong>: Always remove <code>ThreadLocal</code> variables after use, particularly in thread-pooled environments like servlet containers or application servers.</li>
</ul>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadLocalExample</span> </span>{
    private <span class="hljs-keyword">static</span> final ThreadLocal&lt;<span class="hljs-built_in">String</span>&gt; threadLocalVar = <span class="hljs-keyword">new</span> ThreadLocal&lt;&gt;();

    public <span class="hljs-keyword">void</span> doWork() {
        threadLocalVar.set(<span class="hljs-string">"Value"</span>);
        <span class="hljs-comment">// Work with threadLocalVar</span>
        threadLocalVar.remove(); <span class="hljs-comment">// Important to prevent memory leaks</span>
    }
}
</code></pre><h3 id="heading-classloader-leaks"><code>ClassLoader</code> Leaks:</h3>
<ul>
<li><strong><code>ClassLoader</code> Lifecycle</strong>: In environments with dynamic class loading/unloading (for example, web servers), ensure that class loaders are garbage collected when not needed. This involves ensuring that classes loaded by these class loaders are no longer referenced.</li>
</ul>
<h3 id="heading-garbage-collection-tuning">Garbage Collection Tuning:</h3>
<ul>
<li><strong>GC Analysis</strong>: Analyze GC logs to understand the garbage collection behavior and identify potential memory leaks.</li>
<li><strong>GC Algorithm Choice</strong>: Choose an appropriate garbage collection algorithm based on application needs, which can be tuned with JVM options for optimal performance.</li>
</ul>
<h3 id="heading-string-interning">String Interning:</h3>
<ul>
<li><strong>Selective Interning</strong>: Be cautious with the <code>String.intern()</code> method. Unnecessary interning of strings can lead to a bloated String pool.</li>
</ul>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StringInterningExample</span> </span>{
    public <span class="hljs-keyword">void</span> useStringIntern() {
        <span class="hljs-built_in">String</span> str = <span class="hljs-keyword">new</span> <span class="hljs-built_in">String</span>(<span class="hljs-string">"Example"</span>).intern(); <span class="hljs-comment">// Use with caution</span>
    }
}
</code></pre><h3 id="heading-static-analysis-tools">Static Analysis Tools:</h3>
<p>Utilize tools like SonarQube, FindBugs, or PMD to statically analyze code for patterns that could lead to memory leaks.</p>
<h3 id="heading-developer-training-and-code-reviews">Developer Training and Code Reviews:</h3>
<p>Regularly train developers on best practices in memory management and conduct thorough code reviews with a focus on potential memory leak patterns.</p>
<p>Memory leak prevention in Java is a sophisticated practice that involves a thorough understanding of Java memory management, careful coding, diligent use of analysis tools, and regular monitoring. </p>
<p>By adopting these advanced practices, developers can significantly mitigate the risk of memory leaks, leading to more robust, efficient, and scalable Java applications.</p>
<h2 id="heading-49-explain-the-purpose-of-javas-synchronized-block">49. Explain the Purpose of Java's Synchronized Block</h2>
<p>The purpose of Java's synchronized block is to ensure thread safety in concurrent programming by controlling access to a shared resource among multiple threads. </p>
<p>In a multithreaded environment, where multiple threads operate on the same object, there's a risk of data inconsistency if the threads simultaneously modify the object. A synchronized block in Java is used to lock an object for exclusive access by a single thread.</p>
<h3 id="heading-thread-safety-and-data-consistency">Thread Safety and Data Consistency:</h3>
<p>When different threads access and modify shared data, it can lead to unpredictable data states and inconsistencies. The synchronized block ensures that only one thread can execute a particular block of code at a time, thus maintaining data integrity.</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span> </span>{
    private int count = <span class="hljs-number">0</span>;

    public <span class="hljs-keyword">void</span> increment() {
        <span class="hljs-comment">// Synchronized block to ensure only one thread can execute this at a time</span>
        synchronized (<span class="hljs-built_in">this</span>) {
            count++;
            <span class="hljs-comment">// Only the thread holding the lock can modify 'count', ensuring data consistency</span>
        }
    }

    public synchronized int getCount() {
        <span class="hljs-comment">// Synchronized method to safely read the value of 'count'</span>
        <span class="hljs-keyword">return</span> count;
    }
}
</code></pre><h3 id="heading-lock-mechanism">Lock Mechanism:</h3>
<p>In Java, each object has an intrinsic lock or monitor lock. When a thread enters a synchronized block, it acquires the lock on the specified object. Other threads attempting to enter the synchronized block on the same object are blocked until the thread inside the synchronized block exits, thereby releasing the lock.</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SharedResource</span> </span>{
    private final <span class="hljs-built_in">Object</span> lock = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Object</span>();

    public <span class="hljs-keyword">void</span> accessResource() {
        <span class="hljs-comment">// Acquiring the lock on 'lock' object</span>
        synchronized (lock) {
            <span class="hljs-comment">// Critical section: only one thread can access this block at a time</span>
            <span class="hljs-comment">// Other threads attempting to access this block will block until the lock is released</span>
            <span class="hljs-comment">// Code to access and modify shared resources goes here</span>
        }
    }
}
</code></pre><h3 id="heading-syntax-and-usage">Syntax and Usage:</h3>
<p>The synchronized block is defined within a method, and you must specify the object that provides the lock:</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SynchronizedBlockExample</span> </span>{
    private final <span class="hljs-built_in">Object</span> lockObject = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Object</span>();

    public <span class="hljs-keyword">void</span> performTask() {
        <span class="hljs-comment">// Specifying the object to lock on - 'lockObject' in this case</span>
        synchronized (lockObject) {
            <span class="hljs-comment">// Code that requires synchronized access</span>
            <span class="hljs-comment">// This could be a section of code that doesn't need to lock the entire method</span>
        }
    }
}
</code></pre><p>The <code>lockObject</code> is a reference to the object whose lock the synchronized block acquires. It can be <code>this</code> to lock the current object, a class object for class-level locks, or any other object.</p>
<h3 id="heading-advantages-over-synchronized-methods">Advantages Over Synchronized Methods:</h3>
<p>Compared to synchronized methods, synchronized blocks provide finer control over the scope and duration of the lock. </p>
<p>While a synchronized method locks the entire method, a synchronized block can lock only the part of the method that needs synchronization, potentially improving performance.</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MethodVsBlockSynchronization</span> </span>{
    private int sharedState;

    public <span class="hljs-keyword">void</span> synchronizedMethod() {
        synchronized (<span class="hljs-built_in">this</span>) {
            <span class="hljs-comment">// Only a portion of the method needs synchronization</span>
            <span class="hljs-comment">// This approach can lead to better performance compared to synchronizing the entire method</span>
            modifySharedState();
        }
        <span class="hljs-comment">// Other operations that don't need synchronization</span>
    }

    private <span class="hljs-keyword">void</span> modifySharedState() {
        <span class="hljs-comment">// Operations modifying the shared state</span>
    }
}
</code></pre><h3 id="heading-avoiding-deadlocks">Avoiding Deadlocks:</h3>
<p>Take care to avoid deadlocks, a situation where two or more threads are blocked forever, each waiting for the other's lock. This usually occurs when multiple synchronized blocks are locking objects in an inconsistent order.</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DeadlockAvoidanceExample</span> </span>{
    private final <span class="hljs-built_in">Object</span> lock1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Object</span>();
    private final <span class="hljs-built_in">Object</span> lock2 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Object</span>();

    public <span class="hljs-keyword">void</span> method1() {
        synchronized (lock1) {
            <span class="hljs-comment">// Acquiring the first lock</span>

            synchronized (lock2) {
                <span class="hljs-comment">// Acquiring the second lock</span>
                <span class="hljs-comment">// Code that requires both locks</span>
            }
        }
    }

    public <span class="hljs-keyword">void</span> method2() {
        synchronized (lock1) {
            <span class="hljs-comment">// Acquiring the first lock in the same order as in method1 to avoid deadlocks</span>

            synchronized (lock2) {
                <span class="hljs-comment">// Acquiring the second lock</span>
                <span class="hljs-comment">// Code that requires both locks</span>
            }
        }
    }
}
</code></pre><h3 id="heading-memory-visibility-1">Memory Visibility:</h3>
<p>Synchronized blocks also solve memory visibility problems. Changes made by one thread in a synchronized block are visible to other threads entering subsequent synchronized blocks on the same object.</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MemoryVisibility</span> </span>{
    private volatile boolean flag = <span class="hljs-literal">false</span>;

    public <span class="hljs-keyword">void</span> thread1Tasks() {
        synchronized (<span class="hljs-built_in">this</span>) {
            <span class="hljs-comment">// Modifications inside a synchronized block are visible to other threads</span>
            flag = <span class="hljs-literal">true</span>;
        }
    }

    public <span class="hljs-keyword">void</span> thread2Tasks() {
        synchronized (<span class="hljs-built_in">this</span>) {
            <span class="hljs-comment">// The thread sees the most recent value of 'flag' due to synchronization</span>
            <span class="hljs-keyword">if</span> (flag) {
                <span class="hljs-comment">// Perform tasks based on the updated flag value</span>
            }
        }
    }
}
</code></pre><h3 id="heading-best-practices-2">Best Practices</h3>
<ul>
<li><strong>Minimize Lock Contention</strong>: Keep the synchronized sections as short as possible to minimize lock contention and avoid performance bottlenecks.</li>
<li><strong>Consistent Locking Order</strong>: Always acquire locks in a consistent order to prevent deadlocks.</li>
<li><strong>Avoid Locking on Public Objects</strong>: Locking on public objects can lead to accidental and uncontrolled access to the lock, increasing the deadlock risk. Prefer private objects as lock targets.</li>
<li><strong>Complement with Other Concurrency Tools</strong>: In some cases, using higher-level concurrency tools like <code>ReentrantLock</code>, <code>Semaphore</code>, or concurrent collections from <code>java.util.concurrent</code> package might be more appropriate.</li>
</ul>
<p>Java's synchronized block is a critical tool for achieving thread safety in concurrent applications. Its proper use ensures data integrity and consistency by controlling access to shared resources. But, it requires careful consideration to avoid common pitfalls like deadlocks and performance issues due to excessive lock contention. </p>
<p>Understanding and applying these concepts is essential for developers working in a multithreaded environment to create robust and efficient Java applications.</p>
<h2 id="heading-50-explain-the-concept-of-modules-in-java">50. Explain the Concept of Modules in Java</h2>
<p>Modules in Java, introduced in Java 9 with the Java Platform Module System (JPMS), represent a fundamental shift in organizing Java applications and their dependencies. </p>
<p>Understanding modules is essential for modern Java development, as they offer improved encapsulation, reliable configuration, and scalable system architectures.</p>
<h4 id="heading-what-are-java-modules">What are Java modules?</h4>
<p>A module in Java is a self-contained unit of code and data, with well-defined interfaces for communicating with other modules. Each module explicitly declares its dependencies on other modules.</p>
<p>Modules enable better encapsulation by allowing a module to expose only those parts of its API which should be accessible to other modules, while keeping the rest of its codebase hidden. This reduces the risk of unintended usage of internal APIs.</p>
<h4 id="heading-key-components-of-modules">Key Components of modules:</h4>
<p><strong><code>module-info.java</code>:</strong> Each module must have a <code>module-info.java</code> file at its root, which declares the module's name, its required dependencies, and the packages it exports.</p>
<pre><code><span class="hljs-built_in">module</span> com.example.myapp {
    requires java.sql;
    <span class="hljs-built_in">exports</span> com.example.myapp.api;
}
</code></pre><ol>
<li>Here, <code>com.example.myapp</code> is the module name, <code>java.sql</code> is a required module, and <code>com.example.myapp.api</code> is the exported package.</li>
<li><strong>Exports and Requires:</strong> The <code>exports</code> keyword specifies which packages are accessible to other modules, while <code>requires</code> lists the modules on which the current module depends.</li>
</ol>
<h4 id="heading-benefits">Benefits:</h4>
<ol>
<li><strong>Improved Application Structure:</strong> Modules encourage a cleaner, more organized code structure, helping in maintaining large codebases and improving code quality.</li>
<li><strong>Reduced Memory Footprint:</strong> By only loading the required modules, applications can reduce their memory footprint and start-up time, enhancing performance.</li>
<li><strong>Enhanced Security and Maintenance:</strong> Modules reduce the surface area for potential security vulnerabilities. They also simplify dependency management, making it easier to update and maintain libraries without affecting the entire system.</li>
</ol>
<h4 id="heading-practical-example-1">Practical Example:</h4>
<p>Consider a scenario where you are developing a large-scale application with various functionalities like user management, data processing, and reporting. By organizing these functionalities into separate modules (like <code>usermodule</code>, <code>dataprocessmodule</code>, <code>reportmodule</code>), you can maintain them independently, avoiding the complexities of a monolithic application structure.</p>
<pre><code><span class="hljs-comment">// In module-info.java of usermodule</span>
<span class="hljs-built_in">module</span> usermodule {
    requires java.logging;
    <span class="hljs-built_in">exports</span> com.example.usermodule;
}

<span class="hljs-comment">// In module-info.java of dataprocessmodule</span>
<span class="hljs-built_in">module</span> dataprocessmodule {
    requires usermodule;
    <span class="hljs-built_in">exports</span> com.example.dataprocessmodule;
}

<span class="hljs-comment">// In module-info.java of reportmodule</span>
<span class="hljs-built_in">module</span> reportmodule {
    requires dataprocessmodule;
    <span class="hljs-built_in">exports</span> com.example.reportmodule;
}
</code></pre><p>Modules in Java are a powerful feature for building scalable, maintainable, and efficient applications. They offer clear boundaries and contracts between different parts of a system, facilitating better design and architecture. </p>
<p>For developers and teams aiming to build robust Java applications, understanding and leveraging modules is not just a technical skill but a strategic approach to software development. </p>
<p>This modular architecture aligns with modern development practices, enabling Java applications to be more scalable and easier to manage in the long term.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As we wrap up this roundup of Java interview questions, I want to take a moment to thank the freeCodeCamp team. This platform is a fantastic resource for people learning to code, and it's great to have such a supportive community in the tech world.</p>
<p>I also want to thank the editorial team for their help in making this guide possible. Working together has been a great experience, and it's been rewarding to combine our efforts to help others learn Java.</p>
<p>It's important to reflect on the journey we've undertaken together. Java's robustness in Object-Oriented Programming (OOP) is a critical asset for developers at all levels, especially those aspiring to join top-tier tech firms. This handbook has aimed to provide a clear pathway to mastering Java interviews, focusing on the insights and techniques that matter most in the competitive landscape of big tech.</p>
<p>From the fundamentals to the more complex aspects of Java, I've sought to bridge the gap between basic Java knowledge and the sophisticated expertise that industry leaders like Google value. This resource is crafted not just for those new to Java, but also for those revisiting key concepts, offering a comprehensive understanding of the language in a practical context.</p>
<p>As you continue to explore the depths of Java, remember that mastering this language is not just about enhancing coding skills, but also about expanding your professional horizons. Java's significant role in IoT and its presence in billions of devices worldwide make it a language that can truly shape your career.</p>
<p>In closing, I hope this handbook has provided you with valuable insights and a strong foundation for your future endeavors in Java programming and beyond. Whether you're preparing for a big tech interview or simply looking to refine your software development skills, this guide is a stepping stone towards achieving those goals.</p>
<h2 id="heading-resources">Resources</h2>
<p>If you're keen on furthering your Java knowledge, here's a guide to help you <a target="_blank" href="https://join.lunartech.ai/java-fundamentals">conquer Java and launch your coding career</a>. It's perfect for those interested in AI and machine learning, focusing on effective use of data structures in coding. This comprehensive program covers essential data structures, algorithms, and includes mentorship and career support.</p>
<p>Additionally, for more practice in data structures, you can explore these resources:</p>
<ol>
<li><strong><a target="_blank" href="https://join.lunartech.ai/six-figure-data-science-bootcamp">Java Data Structures Mastery - Ace the Coding Interview</a></strong>: A free eBook to advance your Java skills, focusing on data structures for enhancing interview and professional skills.</li>
<li><a target="_blank" href="https://join.lunartech.ai/java-fundamentals"><strong>Foundations of Java Data Structures - Your Coding Catalyst</strong></a>: Another free eBook, diving into Java essentials, object-oriented programming, and AI applications.</li>
</ol>
<p>Visit LunarTech's website for these resources and more information on the <a target="_blank" href="https://lunartech.ai/">bootcamp</a>.</p>
<h3 id="heading-connect-with-me"><strong>Connect with Me:</strong></h3>
<ul>
<li><a target="_blank" href="https://ca.linkedin.com/in/vahe-aslanyan">Follow me on LinkedIn for a ton of Free Resources in CS, ML and AI</a></li>
<li><a target="_blank" href="https://vaheaslanyan.com/">Visit my Personal Website</a></li>
<li>Subscribe to my <a target="_blank" href="https://tatevaslanyan.substack.com/">The Data Science and AI Newsletter</a></li>
</ul>
<h3 id="heading-about-the-author"><strong>About the Author</strong></h3>
<p>I'm Vahe Aslanyan, deeply engaged in the intersecting worlds of computer science, data science, and AI. I invite you to explore my portfolio at vaheaslanyan.com, where I showcase my journey in these fields. My work focuses on blending full-stack development with AI product optimization, all fueled by a passion for innovative problem-solving.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.vaheaslanyan.com/">https://www.vaheaslanyan.com/</a></div>
<p>I've had the privilege of contributing to the launch of a well-regarded data science bootcamp and collaborating with some of the best minds in the industry. My goal has always been to raise the bar in tech education, making it accessible and standard for everyone.</p>
<p>As we conclude our journey here, I want to thank you for your time and engagement. Sharing my professional and academic experiences in this book has been a rewarding experience. I appreciate your involvement and look forward to seeing how it helps you advance in the tech world.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Developer Interview Prep – How to Use a Collaborative Approach to Problem-Solving ]]>
                </title>
                <description>
                    <![CDATA[ By Alberto Gonzalez Rosales No matter how experienced of a developer you are, being interviewed for a new job is always stressful. This is certainly true from my own experience.  In my case, I have been working professionally as a Software Developer ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/collaborative-problem-solving-with-python/</link>
                <guid isPermaLink="false">66d45d5b55db48792eed3f03</guid>
                
                    <category>
                        <![CDATA[ Collaboration ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interview tips ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 19 Apr 2023 21:14:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/michal-czyz-ALM7RNZuDH8-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Alberto Gonzalez Rosales</p>
<p>No matter how experienced of a developer you are, being interviewed for a new job is always stressful. This is certainly true from my own experience. </p>
<p>In my case, I have been working professionally as a Software Developer for two and a half years, and I've had to face developer interviews five times already.</p>
<p>I have seen people focus too much on learning specific algorithmic problems, or training in online platforms specialized in interview challenges. But there is another side to interviews which I think is as important – and people pay less attention to it.</p>
<p>So, if you want to know how I think you should focus your training for interviews, grab a cup of coffee and get comfortable.</p>
<p>It's going to be a bit of a ride ride (but don't worry – Python examples included!).</p>
<h2 id="heading-heres-what-well-cover">Here's what we'll cover:</h2>
<ol>
<li><a class="post-section-overview" href="#heading-do-algorithms-and-data-structures-matter-for-interviews">Do algorithms and data structures matter for interviews?</a></li>
<li><a class="post-section-overview" href="#heading-focus-on-a-collaborative-approach">Focus on a collaborative approach</a></li>
<li><a class="post-section-overview" href="#heading-try-doing-a-mock-interview">Try doing a mock interview</a><br>– <a class="post-section-overview" href="#heading-the-initial-example-interview-problem">The initial example interview problem</a><br>– <a class="post-section-overview" href="#heading-the-second-example-interview-problem">The second example interview problem</a><br>– <a class="post-section-overview" href="#heading-the-hardest-example-interview-problem">The hardest example interview problem</a></li>
<li><a class="post-section-overview" href="#heading-final-words">Final words</a></li>
</ol>
<p>Let's dive in.</p>
<h2 id="heading-do-algorithms-and-data-structures-matter-for-interviews"><strong>Do Algorithms and Data Structures Matter for Interviews?</strong></h2>
<p>The short answer is <strong>Yes</strong>.</p>
<p>Knowing about Data Structures and Algorithms will often help you get a job. Also, the benefits of having a solid algorithmic background include the capacity to make better decisions when faced with a challenging problem.</p>
<p>In real life, algorithmic problems won't appear like the statements in the academic exercises you might study. Still, the more trained you are the most likely you are to be able to recognize an application of a Balanced Binary Tree or a Shortest Path algorithm in disguise.</p>
<p>With this in mind, I would recommend not training Data Structures and Algorithms solely for the interviews that you want to excel at. The design of algorithms and how to use the right data structures are topics beautiful enough to be studied just for the pleasure of knowing.</p>
<p>The scope of an interview is very limited. Instead, focus on the problem-solving part of the issue. Try to understand how to use an algorithm (or variations of it) for similar tasks. Study all the variants, and learn to recognize them in different situations. This will help you face new tasks with an open mind.</p>
<p>Also, don't memorize solutions. It won't take you anywhere. It is very easy for an experienced developer to ask the right questions that will put you on display if you only train for very specific topics.</p>
<p>Take a problem and try to solve it using different methods. Try to solve harder problems every time. Get out of your comfort zone.</p>
<p>It will pay off.</p>
<h2 id="heading-focus-on-a-collaborative-approach"><strong>Focus on a Collaborative Approach</strong></h2>
<p>Most people train for their interviews on websites like <a target="_blank" href="https://leetcode.com/">Leetcode</a>. There is no problem with that. These websites are good for training your problem-solving skills.</p>
<p>I have been participating in Competitive Programming contests for the last eight years at least, and I have always benefited from these online resources.</p>
<p>But there is one thing that's hard to understand for most software engineers wanting to perform well in an interview. They don't train for the most important aspect of software development: <strong>Collaboration</strong>.</p>
<p>Usually, when you are faced with a problem in an online platform, it comes with some constraints on the maximum values for some input. It also might have some time and memory limits that require you to adjust your solutions to be more or less efficient. But this is not how it will be in real life.</p>
<p>It is not obvious how to map these constraints to real-life scenarios. They usually come in the form of very specific requests from a client, or very specific characteristics of the team.</p>
<p>In a real project, the team will <strong>collaborate</strong> to determine what these constraints will be. You have to analyze your use cases, the time you have for the task, who is the final user, how many people will be working on it, and so on...</p>
<p>After a series of discussions, you will reach a consensus and finally start implementing a solution that suits your needs. And this solution doesn't even have to be the more efficient in some cases, but the fastest to implement, for example.</p>
<p>This is what interviewers want to see from candidates during the interviews as well.</p>
<p>You don't jump straight to implementing the best solution you know for the problem you are facing. Instead, you should use your interviewers as a valuable resource, treat them as if they were your teammates (in the end, you want them to be). Ask questions about how the team prefers the solution for the problem to be implemented.</p>
<p>This will lead to a very fruitful discussion where you can showcase your coding abilities and your collaborative skills. You could start proposing simple solutions and walk your interviewers through the process of how the solution can be improved using the best Aces up your sleeve.</p>
<p>As a final note on online training, I would recommend doing individual and team training. Use websites such as <a target="_blank" href="https://codeforces.com/">Codeforces</a> or <a target="_blank" href="https://atcoder.jp/">AtCoder</a>, which have a huge set of interesting (and challenging) problems, and try to compete against yourself every day.</p>
<p>Don't focus on your rating. I have done that before, and it only holds you back.</p>
<h2 id="heading-try-doing-a-mock-interview"><strong>Try Doing a Mock Interview</strong></h2>
<p>If you reached this point in the article, I would like to propose a little exercise. Let's have a mock interview where I will act as the interviewer. I will tell you how I think the candidate (you) should answer every question and perform each task.</p>
<p>Of course, we will focus only on the programming challenge part. Other aspects of interviews, such as talking about previous experiences, are also important, but we will try to cover that in another article.</p>
<p>So, if you feel ready enough, let's go!</p>
<h3 id="heading-the-initial-example-interview-problem">The Initial Example Interview Problem</h3>
<p>Let's start with the task that you will be solving. Keep in mind that if you and I are ever in this situation, I won't be using this same example, but of course, I will be using the same methodology 😉.</p>
<p>The statement of the problem is the following:</p>
<blockquote>
<p>"Given an integer number <code>X</code>, find out if it is a prime number."</p>
</blockquote>
<p>You might be tempted to go for the best solution you know to solve this problem. I think that this approach, as I explained before, isn't always correct.</p>
<p>Instead, what I would like to know are the different approaches to solving this problem. Also, I would like you to ask about the requirements for this task. Something like:</p>
<ul>
<li>Should we aim for performance or to solve it faster?</li>
<li>Should we make a solution that is easy to understand for other developers?</li>
</ul>
<p>Usually, some aspects to consider when creating the first solution for a problem are:</p>
<ul>
<li>Easy vs Hard: Should we make an easy-to-implement solution even if it is not perfect, or should we go for a more robust solution that will be difficult to implement?</li>
<li>Naïve vs Efficient: Should we deliver a working, naïve solution first and then a more efficient one, or should we go straight to efficient?</li>
</ul>
<p>Evaluate what your team wants to optimize for. Reach a consensus, and implement the agreed solution.</p>
<p>In my case, I would be glad if you proposed the easiest, fastest-to-implement, correct solution that you can think of and then guide me through the process of how to improve that solution. </p>
<p>An example of a very good initial solution to this problem is something like the following:</p>
<pre><code class="lang-python"><span class="hljs-comment"># naive.py</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_prime</span>(<span class="hljs-params">x: int</span>) -&gt; bool:</span>
    <span class="hljs-keyword">if</span> x <span class="hljs-keyword">in</span> [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>]:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">2</span>, x):
        <span class="hljs-keyword">if</span> x % i == <span class="hljs-number">0</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
</code></pre>
<p>As you can see, this function is correct. Since a prime number is an integer only divisible by the number <code>1</code> and itself, it makes sense to iterate from <code>2</code> to <code>x - 1</code> looking for a divisor of <code>x</code>. If we find one, we can immediately return <code>False</code>. Otherwise, we return <code>True</code>. As edge cases, the numbers <code>0</code> and <code>1</code> are not prime by definition.</p>
<p>This is a good starting point!</p>
<p>Now, before diving into optimizing this method, you can discuss the style of the code. Is it Pythonic enough? Do we care about it? Is it readable?</p>
<p>All these questions might not seem important at first but, since we work as a team, they do matter. Having a coding style is important because it makes it easier for every team member to understand each other's code, and it will speed up reviews and refactoring. Also, the code is more often read than written, so readability counts!</p>
<p>You might be tempted to show off your Python skills and rewrite the previous function as follows:</p>
<pre><code class="lang-python"><span class="hljs-comment"># pythonic_naive.py</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_prime</span>(<span class="hljs-params">x: int</span>) -&gt; bool:</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span> <span class="hljs-keyword">if</span> x <span class="hljs-keyword">in</span> {<span class="hljs-number">0</span>, <span class="hljs-number">1</span>} <span class="hljs-keyword">else</span> all(x % i != <span class="hljs-number">0</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">2</span>, x))
</code></pre>
<p>I think this is a good, pythonic way to write this function. But, since the team is the most important thing here, this change should be discussed.</p>
<p>It might be the case that some team members are not so skilled in Python. Maybe, in this case, we should optimize for readability instead and keep the function as we first wrote it.</p>
<p>A more interesting addition, before getting into performance, would be adding docstrings to the function. As I said before, this code is most likely to be read by your team members in the future. It is important, then, to make it easier for them (and your future self) to understand what this function is doing.</p>
<p>Maybe changing the function to something like the following will add more value:</p>
<pre><code class="lang-python"><span class="hljs-comment"># naive.py</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_prime</span>(<span class="hljs-params">x: int</span>) -&gt; bool:</span>
    <span class="hljs-string">"""This function takes an integer `x` as
    argument and checks whether is prime or not.

    Args:
        x (int): The integer number to test for primality.

    Returns:
        bool: True if the number `x` is prime, False otherwise.
    """</span>
    <span class="hljs-keyword">if</span> x <span class="hljs-keyword">in</span> [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>]:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">2</span>, x):
        <span class="hljs-keyword">if</span> x % i == <span class="hljs-number">0</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
</code></pre>
<h4 id="heading-first-optimization">First Optimization</h4>
<p>Until this point, we have an initial solution that works. We have discussed important topics such as code styling, readability, and documentation for developers. These are all important things to consider when working as a team.</p>
<p>But we still haven't talked about the performance of the solution! So, it's probably time for that.</p>
<p>At this moment, you should probably bring up that this function can be implemented so it runs much faster. And now is when you showcase all that algorithmic knowledge inside you.</p>
<p>The previous solution has a time complexity of <code>O(x)</code>, where <code>x</code> is the input integer the function takes as an argument. This can be optimized to <code>O(sqrt(x))</code> with the following code:</p>
<pre><code class="lang-python"><span class="hljs-comment"># sqrt.py</span>

<span class="hljs-keyword">import</span> math

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_prime</span>(<span class="hljs-params">x: int</span>) -&gt; bool:</span>
    <span class="hljs-keyword">if</span> x <span class="hljs-keyword">in</span> [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>]:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">2</span>, int(math.sqrt(x)) + <span class="hljs-number">1</span>):
        <span class="hljs-keyword">if</span> x % i == <span class="hljs-number">0</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
</code></pre>
<p>Or even like this, without importing the <code>math</code> library:</p>
<pre><code class="lang-python"><span class="hljs-comment"># sqrt.py</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_prime</span>(<span class="hljs-params">x: int</span>) -&gt; bool:</span>
    <span class="hljs-keyword">if</span> x <span class="hljs-keyword">in</span> [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>]:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
    i = <span class="hljs-number">2</span>
    <span class="hljs-keyword">while</span> i**<span class="hljs-number">2</span> &lt;= x:
        <span class="hljs-keyword">if</span> x % i == <span class="hljs-number">0</span>:
            <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>
        i += <span class="hljs-number">1</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
</code></pre>
<p>I would be ok with either alternative.</p>
<p>I omitted the docstrings in the previous implementation for the sake of making the actual code changes clearer. But, it would be great to include the time complexity of the function in the documentation for developers. The more information you can give about your code, the better it will be for your team members and yourself.</p>
<p>You are doing great so far. Let's continue!</p>
<h3 id="heading-the-second-example-interview-problem">The Second Example Interview Problem</h3>
<p>So far, I have been able to evaluate that you have the necessary collaborative skills to take on easy tasks with the team. Now it's time to complicate things a little.</p>
<p>This is the statement of the second problem I would propose:</p>
<blockquote>
<p>"Given two integer numbers <code>L</code> and <code>R</code>, count how many prime integers are in the interval <code>[L, R]</code>."</p>
</blockquote>
<p>Once again, I would recommend discussing what priorities the team has set regarding this task. Start simple and walk through the process of improving an initial solution. Emphasize that premature optimization is not a good practice.</p>
<p>Also, discuss the possibility of using the solution that you implemented for the previous task to solve this one. It makes sense that if we have a function that tells whether an integer is a prime number or not we can use it for every number in a range.</p>
<p>And this is something that you will have to do in real life. Usually, when a new task shows up, the team should look into the maintained projects to see what can be reused to speed up the implementation process. If you don't do this, you might end up coding duplicated functionalities.</p>
<p>That being said, a good initial solution for this task could be something like this:</p>
<pre><code class="lang-python"><span class="hljs-comment"># range_primes.py</span>

<span class="hljs-keyword">from</span> sqrt <span class="hljs-keyword">import</span> is_prime

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">count_primes</span>(<span class="hljs-params">l: int, r: int</span>) -&gt; int:</span>
    primes = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(l, r + <span class="hljs-number">1</span>):
        <span class="hljs-keyword">if</span> is_prime(i):
            primes += <span class="hljs-number">1</span>
    <span class="hljs-keyword">return</span> primes
</code></pre>
<p>This is perfectly fine, and you have shown that you can reuse previous functionality to build new ones. As in the first example, you might be tempted to show off your Python skills and write this function like this:</p>
<pre><code class="lang-python"><span class="hljs-comment"># range_primes.py</span>

<span class="hljs-keyword">from</span> sqrt <span class="hljs-keyword">import</span> is_prime

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">count_primes</span>(<span class="hljs-params">l: int, r: int</span>) -&gt; int:</span>
    <span class="hljs-keyword">return</span> sum(bool(is_prime(i)) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(l, r + <span class="hljs-number">1</span>))
</code></pre>
<p>I recommend not going for this Pythonic implementation as your first option. Leave it for discussion, evaluate the readability of the code, and maybe analyze the differences in performance. Don't forget the docstrings!</p>
<p>The next section is when things get interesting. Keep reading. We are on the final step...</p>
<h3 id="heading-the-hardest-example-interview-problem">The Hardest Example Interview Problem</h3>
<p>Remember when I said previously that the constraints present in competitive programming websites are hard to map to real-life requirements?</p>
<p>Here is how I would present a difficult challenge for you to determine those constraints and implement the best solution that you can:</p>
<blockquote>
<p>"Suppose a client wants us to provide the functionality of calculating prime numbers in a range as a service. They want the focus to be on performance because they plan to use this service very often. How would you implement it?"</p>
</blockquote>
<p>If you have been practicing your algorithmic skills for interviews, you have probably solved problems similar to this one a few times. The main difference here is the change in context.</p>
<p>Instead of giving you precise instructions, numeric constraints, and input or output formats, I gave you a broader description of the task. And my goal here is the same as before: get you to interact with me as if we were teammates figuring out how to solve this problem from the little information we know.</p>
<p>Hopefully, after exchanging a few questions and answers, we can translate the previous, more ambiguous statement into something much more familiar:</p>
<blockquote>
<p>"Given a set of queries of the form <code>[L, R]</code>, answer, for each query, how many integer numbers inside that range are prime."</p>
</blockquote>
<p>And this makes sense because the client wanted to use this service very often, as stated in the description.</p>
<p>We want to focus on performance. That should be our main concern when implementing the solution. But still, the best way to get to an optimal solution is to start with a simple one, analyze if we meet our performance requirements, and keep improving gradually. Let's see the entire example.</p>
<p>We could start by using the solution we implemented in the previous step. Is it good enough?</p>
<p>Let's assume that the maximum range of numbers we will have as an argument to our function is <code>[1, 10^6]</code>. Also, realistically, let's assume that the number of queries our service will answer per minute is around <code>10^5</code>.</p>
<p>Our previous solution has a time complexity of <code>O(sqrt(n))</code> to determine if a number is a prime. If we were to do that for every number in the range, the complexity goes up to <code>O(n * sqrt(n))</code>. On top of that, if we do that for every query, we will end up with an even higher time complexity of <code>O(q * n * sqrt(n))</code>.</p>
<p>Substitute the previous variables with the highest possible values they can have, and you will get that this solution will take around <code>10^14</code> operations to answer all the queries. Assuming that a computer can perform around <code>10^8</code> elementary operations per second, it will take approximately <code>10^6</code> seconds to complete all of them.</p>
<blockquote>
<p>Note: Convert 10^6 seconds to days. You will be amazed 🤯.</p>
</blockquote>
<p>This solution is unfeasible if the goal is to prioritize the performance of our solution. Let's see how we can improve it.</p>
<p>At this point, what I would expect is for you to take out the best of the training that you've had on all those online platforms, and show me an impressive solution. This is the time to showcase all your analytical and algorithmic skills.</p>
<p>But only now, because I know that you are a team player.</p>
<h4 id="heading-the-final-solution">The Final Solution</h4>
<p>Since this is a mock interview, I am very interested in knowing your approach to solving this last problem efficiently. Let me know how you would implement the solution or share your code on GitHub – don't be shy.</p>
<p>I guarantee you one thing: if you can make it to this point in real interviews, probably it won't matter too much if you don't know the optimal solution to this problem. It doesn't mean that you shouldn't try your best to solve it, but rest assured that you have done a very good job already.</p>
<p>That's it! Now I want to see your code.</p>
<h2 id="heading-final-words"><strong>Final Words</strong></h2>
<p>In this article, I tried to summarize some of the aspects I consider to be the most important in coding interviews. I placed special emphasis on the collaborative part because I think most people underestimate how important this skill is. It is a must, especially if you want to work on a team with other developers.</p>
<p>I tried to guide you through a mock interview where I explained the thought process I would follow when faced with a standard coding task in an interview. I hope this exercise was useful and that it can help you in your next interview (as a candidate or as an interviewer).</p>
<p>Share your thoughts on this mock interview, and let's start a fruitful discussion.</p>
<p>See you soon! 👋</p>
<h2 id="heading-sources"><strong>Sources</strong></h2>
<ul>
<li>Code examples used in the article can be found <a target="_blank" href="https://github.com/albexl/a-problem-solving-oriented-approach">here</a>.</li>
<li>Hint for the last problem: implementation of the <a target="_blank" href="https://github.com/albexl/data-structures-for-teaching/blob/dev/algorithms/number_theory/eratosthenes_sieve.py">Sieve of Eratosthenes</a> algorithm.</li>
</ul>
<p>👋 Hello, I'm Alberto, Software Developer at <a target="_blank" href="https://dowhile.se/">doWhile</a>, Competitive Programmer, Teacher, and Fitness Enthusiast.</p>
<p>🧡 If you liked this article, consider sharing it.</p>
<p>🔗 <a target="_blank" href="https://bio.link/albexl">All links</a> | <a target="_blank" href="https://twitter.com/albe_xl">Twitter</a> | <a target="_blank" href="https://www.linkedin.com/in/albexl/">LinkedIn</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ AWS Lambda Interview Questions and Answers ]]>
                </title>
                <description>
                    <![CDATA[ By Mugilan Ragupathi In this article, I'll go over some of the most commonly asked questions that come up in interviews about AWS Lambda.  Note that this is not an exhaustive list – but you can use this guide as a reference to refresh your knowledge ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/aws-lambda-interview-questions/</link>
                <guid isPermaLink="false">66d46040d7a4e35e3843498f</guid>
                
                    <category>
                        <![CDATA[ aws lambda ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 07 Dec 2022 20:54:49 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/12/AWS-Lambda-Interview-Questions.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Mugilan Ragupathi</p>
<p>In this article, I'll go over some of the most commonly asked questions that come up in interviews about AWS Lambda. </p>
<p>Note that this is not an exhaustive list – but you can use this guide as a reference to refresh your knowledge and get pointers for further study.</p>
<p>Most of the questions will be based on your experience or on certain scenarios. The questions are in the headings and you'll find the notes for the rationale behind asking the questions just below them.</p>
<h2 id="heading-explain-your-last-project-involving-aws-lambda">Explain your last project involving AWS Lambda</h2>
<p><em>The interviewer wants to know about your real-life experience using AWS Lambda. Don't bluff here, as the interviewer may ask further questions based on the answers to this question.</em> </p>
<p>You might have built a serverless API, systems involving microservices, image/video conversion, log analysis, and many more. Just explain your project in detail and tell about the business benefits of that project so that the interviewer knows you're seeing the big picture.</p>
<h2 id="heading-what-services-have-you-integrated-with-aws-lambda">What services have you integrated with AWS Lambda?</h2>
<p><em>This is an extension of the previous question. This is not a laundry list of all event sources that can connect to AWS Lambda. Only tell about the services that you've really used.</em> </p>
<p>You may have used S3, SNS, SQS, Kinesis, DynamoDB, SES, or others. Not all projects will be completely serverless. </p>
<p>If you've used any non-serverless component along with AWS Lambda, mention those too. For example, you might've used AWS Lambda with RDS. If you've used such a configuration,  you can explain about that along with your reasoning.</p>
<h2 id="heading-explain-the-concept-of-cold-and-warm-starts-in-aws-lambda">Explain the concept of cold and warm starts in AWS Lambda</h2>
<p><em>There are 2 reasons for asking this question. They want to know the runtimes that you've used, and they want to know if you know the other runtimes that could cause a cold start.</em></p>
<p>Lambda services receive a request to run a lambda function. The service prepares the execution environment by downloading the handler function code and by allocating memory along with other configuration. </p>
<p>Even though you're not billed for this <code>execution environment</code> preparation time, you'll have to face the delay in invoking your lambda function. This delay is called a "cold start".</p>
<p>The cold start timing is less significant for TypeScript and Python runtime environments, whereas it's a bit higher for Java or C# runtime environments.</p>
<p>To improve performance, the lambda service will keep the execution environment for some time. When you receive the request for the same lambda function again during this period, your handler can start executing immediately. This type of invocation is called a "<em>warm start</em>".</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/image-18.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://aws.amazon.com/blogs/compute/operating-lambda-performance-optimization-part-1/">Image source</a></em></p>
<h2 id="heading-whats-the-difference-between-synchronous-and-asynchronous-invocation-in-aws-lambda">What's the difference between synchronous and asynchronous invocation in AWS Lambda?</h2>
<p><em>Even though this seems to be straightforward question, this has many implications for your design and error handling.</em> </p>
<p>In synchronous invocation, the caller will wait for the execution to complete. But in asynchronous invocation, the caller will put the event in an internal queue which will later be processed in the lambda function.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/image-19.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html">Image source</a></em></p>
<p>An important point to note here is that you can't dictate the type of invocation and it depends on the service that you use with AWS Lambda.</p>
<p>For example, if you're building serverless APIs using API Gateway, it'll be a synchronous invocation. But if you're using S3, it'll be an asynchronous invocation.</p>
<h2 id="heading-how-do-you-implement-error-handling-and-retry-logic-in-lambda">How do you implement error handling and retry logic in Lambda?</h2>
<p><em>Any component in event driven system that may fail will fail. So interviewer wants to know how you've handled the error and how you retried in your previous projects. Below are some examples. Always explain with concrete examples.</em></p>
<p>This depends on the service that you're using with AWS Lambda. Let's discuss this with some examples.</p>
<p>If you're building a serverless API, it is better to return that error to the calling client (could be a front end app in this case). Then you let your front end logic decide what to display to the user based on the type of the error.</p>
<p>If you're using Lambda with SQS, it is better to use a Dead Letter Queue so that you know what messages have failed to process. For this same reason, many of the systems that use SNS may use SQS, too.</p>
<p>In the below code, we're using a dead letter queue. If any message fails to process after a certain number of times (as specified by <code>maxReceiveCount</code>), it's sent to the dead letter queue. This behaviour is specific to lambda when used along with queues.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> queue = <span class="hljs-keyword">new</span> sqs.Queue(<span class="hljs-built_in">this</span>, <span class="hljs-string">'AwsLambdaSqsQueue'</span>, {
      visibilityTimeout: cdk.Duration.seconds(<span class="hljs-number">300</span>),
      receiveMessageWaitTime: cdk.Duration.seconds(<span class="hljs-number">20</span>),
      deadLetterQueue: {
        queue: <span class="hljs-keyword">new</span> sqs.Queue(<span class="hljs-built_in">this</span>, <span class="hljs-string">'AwsLambdaDlq'</span>),
        maxReceiveCount: <span class="hljs-number">5</span>,
      },
    });
</code></pre>
<p>When lambda is invoked with any other services, you can configure the number of retries with a maximum value of 2. This means that you can have maximum of 2 retries apart from the initial invocation. For example, you want to trigger based on the S3 object upload and your lambda will try at most 3 times.</p>
<h2 id="heading-explain-your-workflows-for-development-and-deployment-of-aws-lambda-functions">Explain your workflows for development and deployment of AWS Lambda functions</h2>
<p><em>Talk about the frameworks that you've used. The interviewer may expect you to talk about testing lambda functions as well.</em> </p>
<p>You can explain which framework(s) you've used to develop and deploy lambda functions. You can also talk about any IaC (Infrastructure as Code) tool that you've used. </p>
<p>Below is non-exhaustive list of the most commonly used frameworks:</p>
<ul>
<li>Serverless</li>
<li>AWS CDK</li>
<li>AWS SAM</li>
<li>CloudFormation</li>
<li>Pulumi</li>
</ul>
<p>If you've used Terraform, you can talk about that as well.</p>
<h2 id="heading-can-lambda-be-invoked-when-you-get-an-email-to-a-particular-support-email-address-if-yes-design-that-system-if-not-explain-why">Can Lambda be invoked when you get an email to a particular support email address? If yes, design that system. If not, explain why.</h2>
<p>Yes, you can. You can create receipt rule set and add a rule which triggers the lambda function.</p>
<p>You should store the email to S3 and trigger the lambda after that so that you can have the copy of the email for any further reference.</p>
<p>You can refer to <a target="_blank" href="https://www.freecodecamp.org/news/how-to-receive-emails-via-your-sites-contact-us-form-with-aws-ses-lambda-api-gateway/">this article</a> on how to receive emails from a contact form.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/image-20.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.freecodecamp.org/news/how-to-receive-emails-via-your-sites-contact-us-form-with-aws-ses-lambda-api-gateway/">Image source</a></em></p>
<h2 id="heading-can-one-lambda-function-call-another-lambda-function">Can one lambda function call another lambda function?</h2>
<p><em>The interviewer wants to know whether you know this anti-pattern.</em></p>
<p>You can do this, but it is not recommended. If you want to design a workflow which involves multiple lambda functions, you can use step functions. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/image-21.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://aws.amazon.com/step-functions/">Image source</a></em></p>
<p>You can read more about step functions <a target="_blank" href="https://aws.amazon.com/step-functions/">here</a>.</p>
<p>Another standard approach is to emit an event and trigger a lambda based on the event. You can use SQS, SNS, or EventBridge as intermediary for these events.</p>
<h2 id="heading-can-you-execute-queries-on-an-rds-instance-in-a-private-subnet-using-lambda">Can you execute queries on an RDS instance (in a private subnet) using Lambda?</h2>
<p>Yes, you can execute the query in RDS using AWS Lambda. For that you can have your lambda inside the same VPC. </p>
<p>There may be some performance implications if you use AWS Lambda directly with RDS because of the database connection creation time. To avoid those, you can use an RDS Proxy.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/image-22.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.freecodecamp.org/news/aws-lambda-rds/">Image source</a></em></p>
<p>Here's a <a target="_blank" href="https://www.freecodecamp.org/news/aws-lambda-rds/">detailed step by step guide</a> that shows you how to do that.</p>
<h2 id="heading-aws-lambda-provides-many-benefits-what-are-the-cons-of-using-aws-lambda">AWS Lambda provides many benefits. What are the cons of using AWS Lambda?</h2>
<p><em>The interviewer wants to know about your thought process. Don't say AWS Lambda solves all the problems :-)</em> </p>
<p>Yeah, Lambda provides many benefits such as cost and scalability without any need to maintain the servers. But it's not the answer to everything – like any service, it has its own problems (and you should be able to discuss them):</p>
<ul>
<li>Debugging: If you're using serverless architectures using Lambda, you might have to rely on logging to find the root cause of the issue. This is because your application will be distributed across many services/ lambda functions. </li>
<li>Testing: You can mock AWS services in your local testing. But it is better to have a separate environment in AWS to test your lambdas. This makes testing a bit complex.</li>
<li>Background jobs: Lambda has a timeout limit of 15 minutes. If you want any particular task to take more than 15 minutes, you might have to move to Fargate or some other solution.</li>
<li>Cost: If you're running a high traffic application which processes the requests 24/7, using lambda can be expensive. It is better to use Fargate, EC2 or other services, if you have constant high traffic.</li>
</ul>
<h2 id="heading-how-do-you-manage-concurrency-and-scaling-in-aws-lambda">How do you manage concurrency and scaling in AWS Lambda?</h2>
<p><em>Bonus points if you talk about the issues that you've faced in these situations.</em></p>
<p>Concurrency is the ability to execute multiple lambda functions at the same time. Scaling is the process of increasing the number of copies of your lambda function to handle the incoming requests.</p>
<p>You can control concurrency by setting the value of <code>reserved concurrency</code> so that only the mentioned number of lambda functions will be invoked.</p>
<p>Below is the high level diagram of how lambda scales in accordance with number of messages in the queue.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/image-23.png" alt="AWS Lambda with SQS" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.cloudtechsimplified.com/aws-lambda-sqs/">Image source</a></em></p>
<p>Note: There is some <a target="_blank" href="https://www.cloudtechsimplified.com/aws-lambda-sqs/#weird-behavior">weird behavior</a> if you try to throttle AWS Lambda when used with SQS standard queue. You can use a FIFO queue to solve that issue.</p>
<h2 id="heading-how-do-you-pass-environment-variables-to-aws-lambda">How do you pass environment variables to AWS Lambda?</h2>
<p><em>The interviewer might want to know how you pass sensitive information, for example.</em></p>
<p>There are different ways to pass environment variables to AWS Lambda, and it depends on the type of value is getting passed.</p>
<p><strong>Non-sensitive data</strong>: If you want to pass any non-sensitive information, you can pass the values directly to your lambda function environment variables. But these values would be visible in the AWS console in the Lambda service.  </p>
<p>In the below code example, we're passing the name of the DynamoDB table directly as environment variable, as it is not sensitive data:</p>
<pre><code>   <span class="hljs-keyword">const</span> readDDBLambdaFn = <span class="hljs-keyword">new</span> NodejsFunction(<span class="hljs-built_in">this</span>, <span class="hljs-string">'readDDBLambdaFn'</span>, {
      <span class="hljs-attr">entry</span>: path.join(__dirname, <span class="hljs-string">'../src/lambdas'</span>, <span class="hljs-string">'read-ddb.ts'</span>),
      ...nodeJsFunctionProps,
      <span class="hljs-attr">functionName</span>: <span class="hljs-string">'readDDBLambdaFn'</span>,
      <span class="hljs-attr">environment</span>: {
        <span class="hljs-attr">tableName</span>: table.tableName,
      },
    });
</code></pre><p><strong>Sensitive data</strong>: If you want to pass sensitive data such as passwords and API keys, you can use either a Secret Manager or Parameter store. But, you need to make sure you provide necessary roles to Lambda for accessing and decrypting secrets from the respective services.</p>
<p>In the below code snippet, we're NOT passing the actual secret. Instead, we're just passing the ARN (Amazon Resource Name) of the secret.  </p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> rdsLambdaFn = <span class="hljs-keyword">new</span> NodejsFunction(<span class="hljs-built_in">this</span>, <span class="hljs-string">'rdsLambdaFn'</span>, {
      entry: path.join(__dirname, <span class="hljs-string">'../src/lambdas'</span>, <span class="hljs-string">'rds-lambda.ts'</span>),
      ...nodeJsFunctionProps,
      functionName: <span class="hljs-string">'rdsLambdaFn'</span>,
      environment: {
        DB_ENDPOINT_ADDRESS: dbInstance.dbInstanceEndpointAddress,
        DB_NAME: databaseName,
        DB_SECRET_ARN: dbInstance.secret?.secretFullArn || <span class="hljs-string">''</span>,
      },
      vpc,
      vpcSubnets: vpc.selectSubnets({
        subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
      }),
    });
</code></pre>
<p>Then, in lambda you can get the actual secret dynamically within the lambda function as shown below:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> handler = <span class="hljs-keyword">async</span> (event: <span class="hljs-built_in">any</span>, context: <span class="hljs-built_in">any</span>): <span class="hljs-built_in">Promise</span>&lt;<span class="hljs-built_in">any</span>&gt; =&gt; {
    <span class="hljs-keyword">const</span> host = process.env.DB_ENDPOINT_ADDRESS || <span class="hljs-string">''</span>;
    <span class="hljs-keyword">const</span> database = process.env.DB_NAME || <span class="hljs-string">''</span>;
    <span class="hljs-keyword">const</span> dbSecretArn = process.env.DB_SECRET_ARN || <span class="hljs-string">''</span>;
    <span class="hljs-keyword">const</span> secretManager = <span class="hljs-keyword">new</span> AWS.SecretsManager({
      region: <span class="hljs-string">'us-east-1'</span>,
    });
    <span class="hljs-keyword">const</span> secretParams: AWS.SecretsManager.GetSecretValueRequest = {
      SecretId: dbSecretArn,
    };
    <span class="hljs-keyword">const</span> dbSecret = <span class="hljs-keyword">await</span> secretManager.getSecretValue(secretParams).promise();
    <span class="hljs-keyword">const</span> secretString = dbSecret.SecretString || <span class="hljs-string">''</span>;

    <span class="hljs-keyword">const</span> { password } = <span class="hljs-built_in">JSON</span>.parse(secretString);

}
</code></pre>
<p>I've written a detailed tutorial <a target="_blank" href="https://www.cloudtechsimplified.com/environment-variables-secrets-database-password-aws-lambda/">here</a> on the same topic.</p>
<h2 id="heading-say-you-have-a-windows-dependent-executable-sometoolexe-you-can-upload-it-into-an-s3-bucket-can-you-execute-this-binary-with-some-parameters-using-aws-lambda">Say you have a Windows-dependent executable sometool.exe. You can upload it into an S3 bucket. Can you execute this binary with some parameters using AWS Lambda?</h2>
<p><em>This is more of a question to make sure you understand the AWS Lambda execution environment – specifically the operating system it uses.</em></p>
<p>No, you would not be able to do that as AWS Lambda uses Linux as its operating system. Linux would not be able to execute a Windows-dependent binary.</p>
<h2 id="heading-how-do-you-re-use-code-across-aws-lambda-functions">How do you re-use code across AWS Lambda functions?</h2>
<p>There are 2 ways to re-use code across many AWS Lambda functions:</p>
<ul>
<li>Use Lambda Layers: You can store your code or logic in lambda layers, which you can re-use across different lambda functions. </li>
</ul>
<p>Below is some high level code for creating and consuming lambda layers using <code>aws cdk</code>:</p>
<pre><code>    <span class="hljs-keyword">const</span> logicLayer = <span class="hljs-keyword">new</span> lambda.LayerVersion(<span class="hljs-built_in">this</span>, <span class="hljs-string">'logic-layer'</span>, {
      <span class="hljs-attr">compatibleRuntimes</span>: [
        lambda.Runtime.NODEJS_14_X,
        lambda.Runtime.NODEJS_16_X,
      ],
      <span class="hljs-attr">layerVersionName</span>: <span class="hljs-string">'business-logic-layer'</span>,
      <span class="hljs-attr">code</span>: lambda.Code.fromAsset(<span class="hljs-string">'src/layers/business-logic'</span>),
      <span class="hljs-attr">description</span>: <span class="hljs-string">'Business logic layer'</span>,
    });


    <span class="hljs-keyword">const</span> lambdaWithLayer = <span class="hljs-keyword">new</span> NodejsFunction(<span class="hljs-built_in">this</span>, <span class="hljs-string">'lambdaWithLayer'</span>, {
      <span class="hljs-attr">entry</span>: path.join(__dirname, <span class="hljs-string">'../src/lambdas'</span>, <span class="hljs-string">'lambda.ts'</span>),
      ...nodeJsFnProps,
      <span class="hljs-attr">functionName</span>: <span class="hljs-string">'lambdaWithLayer'</span>,
      <span class="hljs-attr">handler</span>: <span class="hljs-string">'handler'</span>,
      <span class="hljs-attr">layers</span>: [logicLayer, utilsLayer],
    });
</code></pre><ul>
<li>Use <code>monorepo</code>: You can use mono repo and dynamically build packages at deploy time.</li>
</ul>
<h2 id="heading-what-happens-to-your-lambda-functions-if-you-delete-a-lambda-layer">What happens to your lambda functions if you delete a Lambda Layer?</h2>
<p><em>In this question, the interviewer wants to see how well you understand lambda layers.</em> </p>
<p>Existing lambda functions which use that deleted layer will continue to work – as lambda layers are merged with lambda functions at deployment time. </p>
<p>But you can't create a new lambda function using that deleted lambda layer.</p>
<p>You can learn more about Lambda layers <a target="_blank" href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">here</a> and I've written a guide on the same topic <a target="_blank" href="https://www.cloudtechsimplified.com/aws-lambda-layers/">here</a>.</p>
<h2 id="heading-can-you-increase-the-size-of-a-deployment-package-if-you-use-lambda-layers">Can you increase the size of a deployment package if you use Lambda Layers?</h2>
<p>No, you can't increase the size of the deployment package if you use Lambda Layers. The maximum deployment size of 50 MB zipped includes both the size of the lambda function and its associated lambda layers.</p>
<p>If you have a large codebase and want to increase the deployment, you can run containers in AWS Lambda.</p>
<h2 id="heading-can-i-take-my-existing-dockerized-web-application-and-run-it-using-lambda">Can I take my existing dockerized web application and run it using Lambda?</h2>
<p>Nope. You can't take any Express, Springboot, or .NET Core application (or any other application for that matter) as they are and put them inside lambda. </p>
<p>But that being said, there are a few libraries which allow you to put applications that use these web frameworks into AWS Lambda. Internally, those libraries convert those web applications into AWS lambda-compatible APIs. You can see one such example <a target="_blank" href="https://aws.amazon.com/blogs/aws/running-express-applications-on-aws-lambda-and-amazon-api-gateway/">here</a>.</p>
<p>By using these frameworks, the size of your lambda functions will be bigger and will result in longer start up times.</p>
<p>Remember that even when using containers with Lambda, the existing runtime API of Lambda remains the same. Lambda will still:</p>
<ul>
<li>be a single function </li>
<li>be invoked by an event or manually</li>
<li>have a timeout of 15 minutes.</li>
</ul>
<p>As you can see in the below code, there will be no change to the lambda API. The advantage of using Docker is that you would be able to use large packages without worrying about size.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { Context, APIGatewayProxyResult, APIGatewayEvent } <span class="hljs-keyword">from</span> <span class="hljs-string">'aws-lambda'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> handler = <span class="hljs-keyword">async</span> (
  event: APIGatewayEvent,
  context: Context
): <span class="hljs-built_in">Promise</span>&lt;APIGatewayProxyResult&gt; =&gt; {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Event: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(event, <span class="hljs-literal">null</span>, <span class="hljs-number">2</span>)}</span>`</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Context: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(context, <span class="hljs-literal">null</span>, <span class="hljs-number">2</span>)}</span>`</span>);
  <span class="hljs-keyword">return</span> {
    statusCode: <span class="hljs-number">200</span>,
    body: <span class="hljs-built_in">JSON</span>.stringify({
      message: <span class="hljs-string">'Running this handler from docker'</span>,
    }),
  };
};
</code></pre>
<p>And, this is how you use it:</p>
<pre><code> <span class="hljs-keyword">const</span> repo = ecr.Repository.fromRepositoryName(
      <span class="hljs-built_in">this</span>,
      <span class="hljs-string">'dockerLambda'</span>,
      <span class="hljs-string">'docker-lambda'</span>
    );

    <span class="hljs-keyword">const</span> dockerLambda = <span class="hljs-keyword">new</span> lambda.DockerImageFunction(
      <span class="hljs-built_in">this</span>,
      <span class="hljs-string">'DockerLambdaFunction'</span>,
      {
        <span class="hljs-attr">code</span>: lambda.DockerImageCode.fromEcr(repo),
      }
    );
</code></pre><p>I wrote a step-by-step tutorial on running Docker containers for your application in <code>aws lambda</code> <a target="_blank" href="https://www.cloudtechsimplified.com/run-docker-containers-images-from-ecr-in-aws-lambda-along-with-cicd/">here</a>.</p>
<h2 id="heading-how-do-you-share-large-files-between-lambda-functions">How do you share large files between lambda functions?</h2>
<p>You can use the Elastic File System (EFS) to share large files between different functions.  </p>
<p>You can create an <code>access point</code> in the created EFS with the appropriate permissions and use that <code>access point</code> in your <code>mount path</code> in your lambda. </p>
<p>Any files written on that mount path will be accessible to all other lambda functions provided they have the mount path with appropriate permissions.</p>
<p>Below is the high level logical diagram on how to use AWS Lambda with Elastic File System (EFS):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/12/image-24.png" alt="Using EFS with Lambda" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.cloudtechsimplified.com/elastic-file-system-efs-aws-lambda/">Image source</a></em></p>
<p>You can read about this <a target="_blank" href="https://aws.amazon.com/blogs/compute/using-amazon-efs-for-aws-lambda-in-your-serverless-applications/">here</a> (bit old). I wrote a more recent practical step-by-step guide <a target="_blank" href="https://www.cloudtechsimplified.com/elastic-file-system-efs-aws-lambda/">here</a> on EFS with Lambda functions.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>I hope this article helped you to prepare for interviews involving AWS Lambda.</p>
<p>Thanks for reading to this point. I write about <code>aws</code> and serverless technologies at <a target="_blank" href="https://www.cloudtechsimplified.com/">https://www.cloudtechsimplified.com</a>. If you're interested, you can <a target="_blank" href="https://www.cloudtechsimplified.com/">subscribe</a> to my blog.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Big O Cheat Sheet – Time Complexity Chart ]]>
                </title>
                <description>
                    <![CDATA[ An algorithm is a set of well-defined instructions for solving a specific problem. You can solve these problems in various ways. This means that the method you use to arrive at the same solution may differ from mine, but we should both get the same r... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/big-o-cheat-sheet-time-complexity-chart/</link>
                <guid isPermaLink="false">66d45f6551f567b42d9f845f</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ #big o notation ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Wed, 05 Oct 2022 15:00:53 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/cover-template--12-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>An algorithm is a set of well-defined instructions for solving a specific problem. You can solve these problems in various ways.</p>
<p>This means that the method you use to arrive at the same solution may differ from mine, but we should both get the same result.</p>
<p>Because there are various ways to solve a problem, there must be a way to evaluate these solutions or algorithms in terms of performance and efficiency (the time it will take for your algorithm to run/execute and the total amount of memory it will consume).</p>
<p>This is critical for programmers to ensure that their applications run properly and to help them write clean code.</p>
<p>This is where Big O Notation enters the picture. Big O Notation is a metric for determining the efficiency of an algorithm. It allows you to estimate how long your code will run on different sets of inputs and measure how effectively your code scales as the size of your input increases.</p>
<h2 id="heading-what-is-big-o">What is Big O?</h2>
<p>Big O, also known as Big O notation, represents an algorithm's worst-case complexity. It uses algebraic terms to describe the complexity of an algorithm.</p>
<p>Big O defines the runtime required to execute an algorithm by identifying how the performance of your algorithm will change as the input size grows. But it does not tell you how fast your algorithm's runtime is.</p>
<p>Big O notation measures the efficiency and performance of your algorithm using time and space complexity.</p>
<h3 id="heading-what-is-time-and-space-complexity">What is Time and Space Complexity?</h3>
<p>One major underlying factor affecting your program's performance and efficiency is the hardware, OS, and CPU you use.</p>
<p>But you don't consider this when you analyze an algorithm's performance. Instead, the time and space complexity as a function of the input's size are what matters.</p>
<p>An algorithm's time complexity specifies how long it will take to execute an algorithm <strong>as a function of its input size</strong>. Similarly, an algorithm's space complexity specifies the total amount of space or memory required to execute an algorithm <strong>as a function of the size of the input</strong>.</p>
<p>We will be focusing on time complexity in this guide. This will be an in-depth cheatsheet to help you understand how to calculate the time complexity for any algorithm.</p>
<h3 id="heading-why-is-time-complexity-a-function-of-its-input-size">Why is time complexity a function of its input size?</h3>
<p>To perfectly grasp the concept of "as a function of input size," imagine you have an algorithm that computes the sum of numbers based on your input. If your input is 4, it will add 1+2+3+4 to output 10; if your input is 5, it will output 15 (meaning 1+2+3+4+5).</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> calculateSum = <span class="hljs-function">(<span class="hljs-params">input</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt;= input; i++) {
    sum += i;
  }
  <span class="hljs-keyword">return</span> sum;
};
</code></pre>
<p>In the code above, we have three statements:</p>
<p><img src="https://paper-attachments.dropbox.com/s_2D428973624E7FC84C7D69D11421DE762BEA6B6F3361231FCDCAE0425D14526F_1664881245657_Untitled.drawio+16.png" alt="s_2D428973624E7FC84C7D69D11421DE762BEA6B6F3361231FCDCAE0425D14526F_1664881245657_Untitled.drawio+16" width="600" height="400" loading="lazy"></p>
<p>Looking at the image above, we only have three statements. Still, because there is a loop, the second statement will be executed based on the input size, so if the input is four, the second statement (statement 2) will be executed four times, meaning the entire algorithm will run six (4 + 2) times.</p>
<p>In plain terms, the algorithm will run <strong>input + 2</strong> times, where input can be any number. This shows that <strong>it's expressed in terms of the input. In other words, it is a function of the input size</strong>.</p>
<p>In Big O, there are six major types of complexities (time and space):</p>
<ul>
<li><p>Constant: O(1)</p>
</li>
<li><p>Linear time: O(n)</p>
</li>
<li><p>Logarithmic time: O(n log n)</p>
</li>
<li><p>Quadratic time: O(n^2)</p>
</li>
<li><p>Exponential time: O(2^n)</p>
</li>
<li><p>Factorial time: O(n!)</p>
</li>
</ul>
<p>Before we look at examples for each time complexity, let's understand the Big O time complexity chart.</p>
<h2 id="heading-big-o-complexity-chart">Big O Complexity Chart</h2>
<p>The Big O chart, also known as the Big O graph, is an asymptotic notation used to express the complexity of an algorithm or its performance as a function of input size.</p>
<p>This helps programmers identify and fully understand the worst-case scenario and the execution time or memory required by an algorithm.</p>
<p>The <a target="_blank" href="bigocheatsheet.com">following graph</a> illustrates Big O complexity:</p>
<p><img src="https://paper-attachments.dropbox.com/s_2D428973624E7FC84C7D69D11421DE762BEA6B6F3361231FCDCAE0425D14526F_1664885448372_Untitled.drawio+17.png" alt="Image from bigocheatsheet.com" width="600" height="400" loading="lazy"></p>
<p>The Big O chart above shows that O(1), which stands for constant time complexity, is the best. This implies that your algorithm processes only one statement without any iteration. Then there's O(log n), which is good, and others like it, as shown below:</p>
<ul>
<li><p><strong>O(1)</strong> - Excellent/Best</p>
</li>
<li><p><strong>O(log n)</strong> - Good</p>
</li>
<li><p><strong>O(n)</strong> - Fair</p>
</li>
<li><p><strong>O(n log n)</strong> - Bad</p>
</li>
<li><p><strong>O(n^2)</strong>, <strong>O(2^n)</strong> and <strong>O(n!)</strong> - Horrible/Worst</p>
</li>
</ul>
<p>You now understand the various time complexities, and you can recognize the best, good, and fair ones, as well as the bad and worst ones (always avoid the bad and worst time complexity).</p>
<p>The next question that comes to mind is how you know which algorithm has which time complexity, given that this is meant to be a cheatsheet 😂.</p>
<ul>
<li><p>When your calculation is not dependent on the input size, it is a constant time complexity (O(1)).</p>
</li>
<li><p>When the input size is reduced by half, maybe when iterating, handling <a target="_blank" href="https://joelolawanle.com/posts/recursion-in-javascript-explained-for-beginners">recursion</a>, or whatsoever, it is a logarithmic time complexity (O(log n)).</p>
</li>
<li><p>When you have a single loop within your algorithm, it is linear time complexity (O(n)).</p>
</li>
<li><p>When you have nested loops within your algorithm, meaning a loop in a loop, it is quadratic time complexity (O(n^2)).</p>
</li>
<li><p>When the growth rate doubles with each addition to the input, it is exponential time complexity (O2^n).</p>
</li>
</ul>
<p>Let's begin by describing each time's complexity with examples. It's important to note that I'll use JavaScript in the examples in this guide, but the programming language isn't important as long as you understand the concept and each time complexity.</p>
<h2 id="heading-big-o-time-complexity-examples">Big O Time Complexity Examples</h2>
<h3 id="heading-constant-time-o1">Constant Time: O(1)</h3>
<p>When your algorithm is not dependent on the input size n, it is said to have a constant time complexity with order O(1). This means that the run time will always be the same regardless of the input size.</p>
<p>For example, if an algorithm is to return the first element of an array. Even if the array has 1 million elements, the time complexity will be constant if you use this approach:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> firstElement = <span class="hljs-function">(<span class="hljs-params">array</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> array[<span class="hljs-number">0</span>];
};

<span class="hljs-keyword">let</span> score = [<span class="hljs-number">12</span>, <span class="hljs-number">55</span>, <span class="hljs-number">67</span>, <span class="hljs-number">94</span>, <span class="hljs-number">22</span>];
<span class="hljs-built_in">console</span>.log(firstElement(score)); <span class="hljs-comment">// 12</span>
</code></pre>
<p>The function above will require only one execution step, meaning the function is in constant time with time complexity O(1).</p>
<p>But as I said earlier, there are various ways to achieve a solution in programming. Another programmer might decide to first loop through the array before returning the first element:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> firstElement = <span class="hljs-function">(<span class="hljs-params">array</span>) =&gt;</span> {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; array.length; i++) {
    <span class="hljs-keyword">return</span> array[<span class="hljs-number">0</span>];
  }
};

<span class="hljs-keyword">let</span> score = [<span class="hljs-number">12</span>, <span class="hljs-number">55</span>, <span class="hljs-number">67</span>, <span class="hljs-number">94</span>, <span class="hljs-number">22</span>];
<span class="hljs-built_in">console</span>.log(firstElement(score)); <span class="hljs-comment">// 12</span>
</code></pre>
<p>This is just an example – likely nobody would do this. But if there is a loop, this is no longer constant time but now linear time with the time complexity O(n).</p>
<h3 id="heading-linear-time-on">Linear Time: O(n)</h3>
<p>You get linear time complexity when the running time of an algorithm increases linearly with the size of the input. This means that when a function has an iteration that iterates over an input size of n, it is said to have a time complexity of order O(n).</p>
<p>For example, if an algorithm is to return the factorial of any inputted number. This means if you input 5 then you are to loop through and multiply 1 by 2 by 3 by 4 and by 5 and then output 120:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> calcFactorial = <span class="hljs-function">(<span class="hljs-params">n</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> factorial = <span class="hljs-number">1</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">2</span>; i &lt;= n; i++) {
    factorial = factorial * i;
  }
  <span class="hljs-keyword">return</span> factorial;
};

<span class="hljs-built_in">console</span>.log(calcFactorial(<span class="hljs-number">5</span>)); <span class="hljs-comment">// 120</span>
</code></pre>
<p>The fact that the runtime depends on the input size means that the time complexity is linear with the order O(n).</p>
<h3 id="heading-logarithm-time-olog-n">Logarithm Time: O(log n)</h3>
<p>This is similar to linear time complexity, except that the runtime does not depend on the input size but rather on half the input size. When the input size decreases on each iteration or step, an algorithm is said to have logarithmic time complexity.</p>
<p>This method is the second best because your program runs for half the input size rather than the full size. After all, the input size decreases with each iteration.</p>
<p>A great example is binary search functions, which divide your sorted array based on the target value.</p>
<p>For example, suppose you use a binary search algorithm to find the index of a given element in an array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> binarySearch = <span class="hljs-function">(<span class="hljs-params">array, target</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> firstIndex = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">let</span> lastIndex = array.length - <span class="hljs-number">1</span>;
  <span class="hljs-keyword">while</span> (firstIndex &lt;= lastIndex) {
    <span class="hljs-keyword">let</span> middleIndex = <span class="hljs-built_in">Math</span>.floor((firstIndex + lastIndex) / <span class="hljs-number">2</span>);

    <span class="hljs-keyword">if</span> (array[middleIndex] === target) {
      <span class="hljs-keyword">return</span> middleIndex;
    }

    <span class="hljs-keyword">if</span> (array[middleIndex] &gt; target) {
      lastIndex = middleIndex - <span class="hljs-number">1</span>;
    } <span class="hljs-keyword">else</span> {
      firstIndex = middleIndex + <span class="hljs-number">1</span>;
    }
  }
  <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;
};

<span class="hljs-keyword">let</span> score = [<span class="hljs-number">12</span>, <span class="hljs-number">22</span>, <span class="hljs-number">45</span>, <span class="hljs-number">67</span>, <span class="hljs-number">96</span>];
<span class="hljs-built_in">console</span>.log(binarySearch(score, <span class="hljs-number">96</span>));
</code></pre>
<p>In the code above, since it is a binary search, you first get the middle index of your array, compare it to the target value, and return the middle index if it is equal. Otherwise, you must check if the target value is greater or less than the middle value to adjust the first and last index, reducing the input size by half.</p>
<p>Because for every iteration the input size reduces by half, the time complexity is logarithmic with the order O(log n).</p>
<h3 id="heading-quadratic-time-on2">Quadratic Time: O(n^2)</h3>
<p>When you perform nested iteration, meaning having a loop in a loop, the time complexity is quadratic, which is horrible.</p>
<p>A perfect way to explain this would be if you have an array with n items. The outer loop will run n times, and the inner loop will run n times for each iteration of the outer loop, which will give total n^2 prints. If the array has ten items, ten will print 100 times (10^2).</p>
<p>Here is an example by <a target="_blank" href="https://jarednielsen.com/big-o-quadratic-time-complexity/">Jared Nielsen</a>, where you compare each element in an array to output the index when two elements are similar:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> matchElements = <span class="hljs-function">(<span class="hljs-params">array</span>) =&gt;</span> {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; array.length; i++) {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> j = <span class="hljs-number">0</span>; j &lt; array.length; j++) {
      <span class="hljs-keyword">if</span> (i !== j &amp;&amp; array[i] === array[j]) {
        <span class="hljs-keyword">return</span> <span class="hljs-string">`Match found at <span class="hljs-subst">${i}</span> and <span class="hljs-subst">${j}</span>`</span>;
      }
    }
  }
  <span class="hljs-keyword">return</span> <span class="hljs-string">"No matches found 😞"</span>;
};

<span class="hljs-keyword">const</span> fruit = [<span class="hljs-string">"🍓"</span>, <span class="hljs-string">"🍐"</span>, <span class="hljs-string">"🍊"</span>, <span class="hljs-string">"🍌"</span>, <span class="hljs-string">"🍍"</span>, <span class="hljs-string">"🍑"</span>, <span class="hljs-string">"🍎"</span>, <span class="hljs-string">"🍈"</span>, <span class="hljs-string">"🍊"</span>, <span class="hljs-string">"🍇"</span>];
<span class="hljs-built_in">console</span>.log(matchElements(fruit)); <span class="hljs-comment">// "Match found at 2 and 8"</span>
</code></pre>
<p>In the example above, there is a nested loop, meaning that the time complexity is quadratic with the order O(n^2).</p>
<h3 id="heading-exponential-time-o2n">Exponential Time: O(2^n)</h3>
<p>You get exponential time complexity when the growth rate doubles with each addition to the input (n), often iterating through all subsets of the input elements. Any time an input unit increases by 1, the number of operations executed is doubled.</p>
<p>The recursive Fibonacci sequence is a good example. Assume you're given a number and want to find the nth element of the Fibonacci sequence.</p>
<p>The Fibonacci sequence is a mathematical sequence in which each number is the sum of the two preceding numbers, where 0 and 1 are the first two numbers. The third number in the sequence is 1, the fourth is 2, the fifth is 3, and so on... (0, 1, 1, 2, 3, 5, 8, 13, …).</p>
<p>This means that if you pass in 6, then the 6th element in the Fibonacci sequence would be 8:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> recursiveFibonacci = <span class="hljs-function">(<span class="hljs-params">n</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (n &lt; <span class="hljs-number">2</span>) {
    <span class="hljs-keyword">return</span> n;
  }
  <span class="hljs-keyword">return</span> recursiveFibonacci(n - <span class="hljs-number">1</span>) + recursiveFibonacci(n - <span class="hljs-number">2</span>);
};

<span class="hljs-built_in">console</span>.log(recursiveFibonacci(<span class="hljs-number">6</span>)); <span class="hljs-comment">// 8</span>
</code></pre>
<p>In the code above, the algorithm specifies a growth rate that doubles every time the input data set is added. This means the time complexity is exponential with an order O(2^n).</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this guide, you have learned what time complexity is all about, how performance is determined using the Big O notation, and the various time complexities that exists with examples.</p>
<p>You can learn more via freeCodeCamp's <a target="_blank" href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/">JavaScript Algorithms and Data Structures curriculum</a>.</p>
<p>Happy learning!</p>
<p>You can access over 200 of my articles by <a target="_blank" href="https://joelolawanle.com/contents">visiting my website</a>. You can also use the search field to see if I've written a specific article.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Prepare for React Interviews – Front-End Technical Interview Guide ]]>
                </title>
                <description>
                    <![CDATA[ By Manu Arora A front-end technical interview is an opportunity for a potential employer to assess your skills and knowledge in web development.   The interviewer will ask you questions about your experience and skills in HTML, CSS, and JavaScript. T... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/prepare-for-react-technical-interviews/</link>
                <guid isPermaLink="false">66d46021787a2a3b05af43dc</guid>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interviewing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 08 Sep 2022 00:29:16 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/08/Build-a-React-Code-Editor-That-Compiles-and-Executes-in-10--Languages--2-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Manu Arora</p>
<p>A front-end technical interview is an opportunity for a potential employer to assess your skills and knowledge in web development.  </p>
<p>The interviewer will ask you questions about your experience and skills in HTML, CSS, and JavaScript. They'll also likely ask you some framework specific questions about React, Angular, Vue, or whatever framework they use.  </p>
<p>They may also give you a coding challenge to test your abilities in a particular domain.  </p>
<p>Today, we are going to look at the most common problems asked in a front-end technical interview round, focusing on React and JavaScript.</p>
<h2 id="heading-what-interviewers-are-looking-for">What Interviewers Are Looking For</h2>
<p>When interviewing for a front-end web development position, be prepared to discuss your skills and experience with various programming languages, tools, and frameworks.  </p>
<p>Interviewers will also want to see that you have a strong understanding of the latest trends and technologies in web development.  </p>
<p>Be prepared to talk about your past projects and how you approached solving various challenges.  </p>
<p>Be sure to showcase your problem-solving skills by discussing how you tackled various challenges during your development process.  </p>
<p>Finally, don’t forget to highlight your strengths.</p>
<h2 id="heading-most-commonly-asked-questions-in-a-front-end-technical-interview">Most Commonly Asked Questions in a Front-End Technical Interview</h2>
<p>Front-end technical interview problems are pretty straightforward and common. If you have been actively coding for at least 6 months, you will be familiar with most of the concepts that are asked about.</p>
<p>Once you practice the right questions with a time based approach, you should be able to clear the interviews.</p>
<p>Let's look at the most common questions asked.</p>
<h2 id="heading-map-foreach-filter-and-reduce">Map, ForEach, Filter and Reduce</h2>
<p>The most commonly asked questions (generally at the start of the interviews) are about <code>array methods</code>. The interviewer wants to asses how comfortable you are with array manipulation.</p>
<h4 id="heading-the-map-method">The <code>.map()</code> method</h4>
<p>The <code>.map()</code> methods iterates over an array, computes whatever logic you write inside the map body, and returns a <strong>NEW</strong> array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">12</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Manu'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">24</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Quincy'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">22</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Abbey'</span> },
]

<span class="hljs-keyword">let</span> names = arr.map(<span class="hljs-function">(<span class="hljs-params">el</span>) =&gt;</span> el.name)
<span class="hljs-built_in">console</span>.log(names)
<span class="hljs-comment">// Output: [ 'Manu', 'Quincy', 'Abbey' ]</span>
</code></pre>
<h4 id="heading-the-foreach-method">The <code>.forEach()</code> method</h4>
<p>ForEach is similar to <code>.map()</code> but it DOES NOT return an array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">12</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Manu'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">24</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Quincy'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">22</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Abbey'</span> },
]

arr.forEach(<span class="hljs-function">(<span class="hljs-params">el</span>) =&gt;</span> el.age+= <span class="hljs-number">10</span>);
<span class="hljs-built_in">console</span>.log(arr);

<span class="hljs-comment">// Output: 22 32 44</span>
</code></pre>
<h4 id="heading-the-filter-method">The <code>.filter()</code> method</h4>
<p>The filter method, as the name suggests, helps in filtering out the values inside of an array based on a Boolean condition. </p>
<p>If the boolean condition is true, the result will be returned and added in the final array. If not, it will be skipped. Filter also returns an array, just like the <code>.map()</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">12</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Manu'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">24</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Quincy'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">22</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Abbey'</span> },
]

<span class="hljs-keyword">let</span> tooYoung = arr.filter(<span class="hljs-function">(<span class="hljs-params">el</span>) =&gt;</span> el.age &lt;= <span class="hljs-number">14</span>);
<span class="hljs-built_in">console</span>.log(tooYoung);

<span class="hljs-comment">// Output: [ { id: 1, age: 12, name: 'Manu' } ]</span>
</code></pre>
<h4 id="heading-the-reduce-method">The <code>.reduce()</code> method</h4>
<p>In simple terms, the <code>.reduce()</code> method takes into account a <code>previous value</code> , current value and an <code>accumulator</code>. </p>
<p>The return type of the <code>.reduce()</code> method is always a single value. It is useful when you want to process all the values of the array and want to derive some accumulated result.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Calculates the total age of all the three persons.</span>
<span class="hljs-keyword">let</span> arr = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">12</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Manu'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">24</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Quincy'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">22</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Abbey'</span> },
]

<span class="hljs-keyword">let</span> totalAge = arr.reduce(<span class="hljs-function">(<span class="hljs-params">acc, currentObj</span>) =&gt;</span> acc + currentObj.age, <span class="hljs-number">0</span>)
<span class="hljs-built_in">console</span>.log(totalAge)

<span class="hljs-comment">// Output: 57</span>
</code></pre>
<p>Here, the <code>currentObj</code> is the object that is being iterated over. Also, the <code>acc</code> value stores the result and is outputted finally into the totalAge array.</p>
<h2 id="heading-how-to-implement-polyfills">How to Implement Polyfills</h2>
<p>Another important interview question is <a target="_blank" href="https://www.algochurn.com/frontend/polyfills">How to implement polyfills</a> of the map and filter array methods.</p>
<p>A polyfill is a code snippet (in terms of JavaScript web architecture) used for modern world functionalities on older browsers that do not implement it natively.</p>
<p>Simply put, a polyfill is a custom implementation of native JavaScript functions. Sort of a create your own <code>.map()</code> or <code>.filter()</code> method.</p>
<h4 id="heading-how-to-use-the-map-polyfill">How to use the <code>.map()</code> polyfill</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> data = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-built_in">Array</span>.prototype.myMap = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">cb</span>) </span>{
  <span class="hljs-keyword">let</span> arr = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.length; i++) {
    arr.push(cb(<span class="hljs-built_in">this</span>[i], i, <span class="hljs-built_in">this</span>));
  }
  <span class="hljs-keyword">return</span> arr;
};
<span class="hljs-keyword">const</span> mapLog = data.myMap(<span class="hljs-function">(<span class="hljs-params">el</span>) =&gt;</span> el * <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(mapLog);
</code></pre>
<p>the <code>myMap</code> method takes in a <code>callback</code> that gets executed inside the <code>myMap</code> body. We basically have a native <code>for</code> loop inside the myMap body, which iterates over the <code>this.length</code>. This is nothing but the length of the array through which the <code>myMap</code> function is called.</p>
<p>Since the syntax of <code>map()</code> is <code>arr.map(currentElement, index, array)</code>, and the <code>myMap()</code> function takes into account exactly that.</p>
<p>Also since <code>map()</code> returns a new array, we create an empty array and push the results into it. In the end we return it.</p>
<h4 id="heading-how-to-use-the-filter-polyfill">How to use the <code>.filter()</code> polyfill</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> data = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-built_in">Array</span>.prototype.myFilter = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">cb</span>) </span>{
  <span class="hljs-keyword">let</span> arr = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.length; i++) {
    <span class="hljs-keyword">if</span> (cb(<span class="hljs-built_in">this</span>[i], i, <span class="hljs-built_in">this</span>)) {
      arr.push(<span class="hljs-built_in">this</span>[i]);
    }
  }
  <span class="hljs-keyword">return</span> arr;
};
<span class="hljs-keyword">const</span> filterLog = data.myFilter(<span class="hljs-function">(<span class="hljs-params">el</span>) =&gt;</span> el &lt; <span class="hljs-number">4</span>);
<span class="hljs-built_in">console</span>.log(filterLog);
</code></pre>
<p><code>.filter()</code> is very similar to <code>.map()</code> in terms of implementation. But since <code>filter</code> filters out the results based on a boolean value, we have an additional <code>if()</code> condition to filter out results and conditionally push inside the array.</p>
<h2 id="heading-what-is-debouncing">What is Debouncing?</h2>
<p>This is a famous interview question with a lot of practical real world usage and implementations.</p>
<p><code>Debouncing</code> is a method of preventing a function from being invoked too often, and instead waiting a certain amount of time until it was last called before invoking it.  </p>
<p>Think of Amazon in this case. Whenever you type anything in the search bar, when you stop for AT LEAST 0.5 seconds, then the results are fetched. This is exactly what debouncing is.</p>
<p>In order to implement debouncing, let's take an example: Generating a username for a user based on the user input.</p>
<div class="embed-wrapper"><iframe src="https://codesandbox.io/embed/proud-surf-uiu2v?fontsize=14&amp;hidenavigation=1&amp;theme=dark" style="width:100%;height:500px;border:0;border-radius:4px;overflow:hidden" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" title="Embedded content" loading="lazy"></iframe></div>

<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">"./styles.css"</span>;
<span class="hljs-keyword">let</span> inputEle = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"inputElement"</span>);
<span class="hljs-keyword">let</span> username = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"username"</span>);

<span class="hljs-keyword">let</span> generateUsername = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  username.innerHTML = e.target.value.split(<span class="hljs-string">" "</span>).join(<span class="hljs-string">"-"</span>);
};
<span class="hljs-keyword">let</span> debounce = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">cb, delay</span>) </span>{
  <span class="hljs-keyword">let</span> timer;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> context = <span class="hljs-built_in">this</span>;
    <span class="hljs-built_in">clearTimeout</span>(timer);
    timer = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      cb.apply(context, <span class="hljs-built_in">arguments</span>);
    }, delay);
  };
};

inputEle.addEventListener(<span class="hljs-string">"keyup"</span>, debounce(generateUsername, <span class="hljs-number">300</span>));
</code></pre>
<p>Here, we are trying to create a custom username based on the user input. Now if the user starts typing, we don't want to immediately create it, but actually wait for 300 milliseconds before creating the username. We are trying to mimic an API call here, so assume the user types anything and it has to make an API call to the backend and fetch a response.</p>
<p>The <code>debounce()</code> function takes in two values, <code>cb</code> and <code>delay</code> . <code>cb</code> is the callback function that gets executed when the timer runs out.  </p>
<p>We use <code>setTimeout()</code> to create a timeout timer, which means the function inside the setTimeout body will be executed after a certain amount of time.</p>
<p>The <code>apply</code> method is used to call the callback function with the <code>object</code> that it was initially called with, applying the arguments and context to it.</p>
<h2 id="heading-what-are-closures">What are Closures?</h2>
<p>According to the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">mdn docs for closures</a>,</p>
<blockquote>
<p>A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.</p>
</blockquote>
<p>To simplify this, let's take an example and understand how closures work.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">start</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> name = <span class="hljs-string">"Manu"</span>; <span class="hljs-comment">// name is a local variable created by start()</span>
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayName</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// displayName() is the inner function, a `closure`</span>
    alert(name); <span class="hljs-comment">// use variable declared in the parent function</span>
  }
  displayName();
}
start(); <span class="hljs-comment">// "Manu" alert box is displayed</span>
</code></pre>
<p>Here, a closure is formed between the <code>start()</code> and the <code>displayName()</code> function. The <code>displayName()</code> function has access to the <code>name</code> variable present in the <code>start()</code> function.</p>
<p>In simple terms, the inner function will know its surroundings (the lexical environment).</p>
<p>I have written a whole blog on <a target="_blank" href="https://manuarora.in/blog/ace-the-javascript-interview#closures">how to clear JavaScript interviews</a>. Have a look at that if you want to know more about in depth JavaScript interview process.</p>
<h2 id="heading-react-hooks">React Hooks</h2>
<p>The most popular questions asked in a front-end coding interview when it comes to React hooks are:</p>
<ol>
<li><code>useState()</code></li>
<li><code>useReducer()</code></li>
<li><code>useEffect()</code></li>
<li><code>useRef()</code></li>
<li>Custom Hooks and their implementation.</li>
</ol>
<h3 id="heading-how-the-usestate-hook-works">How the <code>useState()</code> hook works</h3>
<p>To manage a state inside of your component, the <code>useState()</code> hook is your go-to hook.  </p>
<p>Let's take an example and understand:</p>
<div class="embed-wrapper"><iframe src="https://codesandbox.io/embed/thirsty-lewin-uo8ylh?fontsize=14&amp;hidenavigation=1&amp;theme=dark" style="width:100%;height:500px;border:0;border-radius:4px;overflow:hidden" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" title="Embedded content" loading="lazy"></iframe></div>

<pre><code class="lang-javscript">import { useState } from "react";
import "./styles.css";

export default function App() {
  const [title, setTitle] = useState("freeCodeCamp");
  const handleChange = () =&gt; {
    setTitle("FCC");
  };
  return (
    &lt;div className="App"&gt;
      &lt;h1&gt;{title} useState&lt;/h1&gt;
      &lt;button onClick={handleChange}&gt;Change Title&lt;/button&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>The <code>useState()</code> methods gives us two values, the <code>state</code> variable and <code>a function to change</code> that state variable.</p>
<p>In the above code snippet, we are creating a <code>title</code> state to store the title of the page. The initial state is passed as <code>freeCodeCamp</code>.</p>
<p>On button click, we can use the <code>setTitle()</code> method to change the state variable to <code>FCC</code>.</p>
<p><code>useState()</code> method is your go-to resource for state management in a functional component.</p>
<h3 id="heading-how-the-usereducer-hook-works">How the <code>useReducer()</code> hook works</h3>
<p>In simple terms, <code>useReducer()</code> is the cool way of managing state in your application. It is more structured and helps you maintain complex state in your application.</p>
<p>Let's take an example to understand the useReducer hook:</p>
<div class="embed-wrapper"><iframe src="https://codesandbox.io/embed/ecstatic-marco-o8wh00?fontsize=14&amp;hidenavigation=1&amp;theme=dark" style="width:100%;height:500px;border:0;border-radius:4px;overflow:hidden" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" title="Embedded content" loading="lazy"></iframe></div>

<pre><code class="lang-javscript">import "./styles.css";
import { useReducer } from "react";

const initialState = { title: "freeCodeCamp", count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case "change-title":
      return { ...state, title: "FCC" };
    case "increment-counter":
      return { ...state, count: state.count + 1 };
    default:
      throw new Error();
  }
}

export default function App() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    &lt;&gt;
      &lt;div className="App"&gt;
        &lt;h1&gt;{state.title} CodeSandbox&lt;/h1&gt;
        &lt;button onClick={() =&gt; dispatch({ type: "change-title" })}&gt;
          Change Title
        &lt;/button&gt;
        &lt;button onClick={() =&gt; dispatch({ type: "increment-counter" })}&gt;
          Increment Counter
        &lt;/button&gt;
      &lt;/div&gt;
      &lt;p style={{ textAlign: "center" }}&gt;{state.count}&lt;/p&gt;.
    &lt;/&gt;
  );
}
</code></pre>
<p>The <code>useReducer()</code> hook takes two parameters, the <code>reducer</code> function and an <code>initialState</code> value.  </p>
<p>The reducer function is a <code>switch-case</code> based implementation that returns the final state value that <code>useReduer()</code> internally uses to supply back to the component.</p>
<p>The values returned from the <code>useReducer()</code> function are <code>state</code> and <code>dispatch</code>. The <code>state</code> is the actual <code>state</code> value that can be used inside of the component. In our case, the state has two values: <code>title and count</code>. This title and count can be manipulated using the <code>dispatch()</code> method which is returned by the <code>useReducer()</code> method.</p>
<p>In the above case, to change the title, we have written a case of <code>change-title</code> inside the reducer function. This can be triggered with the help of the <code>dispatch({ type: "change-title" })</code> function. This will trigger the change title function and it will change the state of the <code>title</code> attribute.  </p>
<p>Similarly, the same happens for the <code>count</code> part that is there in the application.  </p>
<p>Like I said earlier, it is a cool way of implementing state inside your application. 😉</p>
<h3 id="heading-how-the-useeffect-hook-works">How the <code>useEffect()</code> hook works</h3>
<p>Think of it this way: if you want to have a <code>side effect</code> to a state variable that changes, you can use the <code>useEffect()</code> hook to trigger it.  </p>
<p>For example, let's say if the <code>input value</code> of your input box changes, and you want to call an API after it has changed. You can write the logic of the <code>API handle</code> in the <code>useEffect()</code> block.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, {useState, useEffect} <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> [value, setValue] = useState(<span class="hljs-string">''</span>);
    useEffect(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'value changed: '</span>, value);
    }, [value])
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setValue(e.target.value)} /&gt;
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
}
</code></pre>
<p>Here, we have an <code>input box</code> that has a state value of <code>value</code> attached to it. This value will change when the user tries to input anything.  </p>
<p>Once the value has been updated and has been rendered, the <code>useEffect()</code> block will kick in and the <code>console</code> statement will be triggered, outputting the latest state value which is there.  </p>
<p>Here, one good use case of the <code>useEffect()</code> can be to implement <code>API calls</code>. Let's assume you want to call an API with the input field value. The useEffect function block will be the best way to do it.</p>
<p>Another part of this is the <code>dependency array</code> which is the second argument to the <code>useEffect()</code> hook. In our case, we mentioned <code>[value]</code> as the second argument.</p>
<p>This basically means that EVERY TIME THE <code>value</code> CHANGES, the function inside the useEffect gets triggered. If you don't pass anything in the <code>dependency array</code>, the function block gets triggered once.</p>
<h3 id="heading-how-the-useref-hook-works">How the <code>useRef()</code> hook works</h3>
<p>The useRef hook gives us the ability to mutate the DOM (but this is not the only implication of useRef).</p>
<p>According to the docs:</p>
<blockquote>
<p>useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.</p>
</blockquote>
<p>In simple terms, we are going to useRef if we want to persist the value of something for the entire component lifecycle. The basic implementation of useRef comes with DOM elements. Let's take an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TextInputWithFocusButton</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> inputEl = useRef(<span class="hljs-literal">null</span>);
  <span class="hljs-keyword">const</span> onButtonClick = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// `current` points to the mounted text input element</span>
    inputEl.current.focus();
  };
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputEl}</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onButtonClick}</span>&gt;</span>Focus the input<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre>
<p>Here, we are assigning a <code>ref</code> property to the <code>input</code> block. This will be associated with the <code>inputEl</code> reference that we created.</p>
<p>Now this <code>input</code> element can be manipulated however we want. We can modify the <code>style</code> attribute and make it beautiful, we can take the <code>value</code> property to see what is being help by the input element as the value, and so on.</p>
<p>In the above example, when we click the button, the <code>input</code> is focused and we can immediately start typing. We can do this with the help of <code>inputEl.current.focus()</code> – essentially the <code>focus()</code> method present on the <code>current</code> object.</p>
<h3 id="heading-what-are-custom-hooks">What are custom hooks?</h3>
<p>One of the most commonly asked questions that I've seen in front-end interview rounds is to <a target="_blank" href="https://www.algochurn.com/frontend/usekeypress-custom-hook">create a custom hook for keyboard events</a>.</p>
<p>We saw many different hooks, but the interviewer might ask you to create a hook of your own. This might be challenging for some but with some practice, it becomes much easier.</p>
<p>Let's understand what a <code>Hook</code> is:</p>
<p>The basic usage of a custom hook is to extract a function's logic into its own component.</p>
<p>Imaging what will happen if you have to <code>listen for an enter press</code> inside of each of your components. Instead of writing the logic for <code>listening</code> again and again, we can extract the logic into a component of its own and use it wherever we want (just like we use <code>useState()</code> or <code>useEffect()</code>).</p>
<p>There are a few conditions for a function to be called a <code>Hook</code>:</p>
<ol>
<li>It should always start with the <code>use</code> keyword.</li>
<li>We can decide what it takes as arguments, and what, if anything, it should return.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-comment">// Custom Hook: useAvailable</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useAvailabe</span>(<span class="hljs-params">resource</span>) </span>{
  <span class="hljs-keyword">const</span> [isAvailable, setIsAvailable] = useState(<span class="hljs-literal">null</span>);

  <span class="hljs-comment">// ...</span>

  <span class="hljs-keyword">return</span> isAvailable;
}

<span class="hljs-comment">// Usage:</span>
  <span class="hljs-keyword">const</span> isAvailable = useAvailable(cpu);
</code></pre>
<p>Here, no matter how many times we call <code>useState</code> and <code>useEffects</code> inside the custom hook, they will be completely independent from the function where we use the custom hook.  </p>
<p>Let's take an example of creating a custom hook for <code>storing local storage values</code>.</p>
<h3 id="heading-how-to-create-a-custom-hook-uselocalstorage-example">How to create a custom hook – useLocalStorage example</h3>
<p>The useLocalStorage custom hook is a way to persist data into the local storage. Get and set values inside the local storage using <code>key</code> and <code>value</code> pairs so that whenever the user comes back to your web app, they see the same result they used earlier.</p>
<p>The below implementation is of a simple <code>select</code> tag value that, once changed, persists the data into local storage.</p>
<p><code>useLocalStorage.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Use Local Storage Custom Hook</span>
<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useLocalStorage</span>(<span class="hljs-params">key, initialValue</span>) </span>{
  <span class="hljs-keyword">const</span> [storedValue, setStoredValue] = useState(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">window</span> === <span class="hljs-string">'undefined'</span>) {
      <span class="hljs-keyword">return</span> initialValue;
    }
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> item = <span class="hljs-built_in">window</span>.localStorage.getItem(key);
      <span class="hljs-keyword">return</span> item ? <span class="hljs-built_in">JSON</span>.parse(item) : initialValue;
    } <span class="hljs-keyword">catch</span> (error) {
      <span class="hljs-built_in">console</span>.log(error);
      <span class="hljs-keyword">return</span> initialValue;
    }
  });
  <span class="hljs-keyword">const</span> setValue = <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> valueToStore =
        value <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Function</span> ? value(storedValue) : value;
      setStoredValue(valueToStore);
      <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">window</span> !== <span class="hljs-string">'undefined'</span>) {
        <span class="hljs-built_in">window</span>.localStorage.setItem(key, <span class="hljs-built_in">JSON</span>.stringify(valueToStore));
      }
    } <span class="hljs-keyword">catch</span> (error) {
      <span class="hljs-built_in">console</span>.log(error);
    }
  };
  <span class="hljs-keyword">return</span> [storedValue, setValue] <span class="hljs-keyword">as</span> <span class="hljs-keyword">const</span>;
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> useLocalStorage;
</code></pre>
<p><code>App.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./style.css'</span>;
<span class="hljs-keyword">import</span> useLocalStorage <span class="hljs-keyword">from</span> <span class="hljs-string">'./useLocalStorate'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [storedValue, setStoredValue] = useLocalStorage(
    <span class="hljs-string">'select-value'</span>,
    <span class="hljs-string">'light'</span>
  );

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">select</span>
        <span class="hljs-attr">className</span>=<span class="hljs-string">"select"</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{storedValue}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setStoredValue(e.target.value)}
      &gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"dark"</span>&gt;</span>Dark<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"light"</span>&gt;</span>Light<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"desc"</span>&gt;</span>
        Value from local storage: <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>{storedValue}<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Here, the <code>useLocalStorage</code> hook takes in two parameters, the <code>local storage key name</code> to store, and a <code>default</code> value that has to be there.</p>
<p>The hook returns two values: the <code>local storage value</code> of the key that you're using and a way to <code>change that key value</code> by giving us a <code>setter method</code>. In this case, the <code>setStoredValue</code> method.</p>
<p>In the <code>useLocalStorage.js</code> file, we are trying to first <code>GET</code> the local storage value with that key using <code>localStorage.getItem()</code> method. If that exists, we are setting the value. If found, we <code>JSON.parse()</code> the value and return it. Otherwise, initialValue which was provided is set as the default value.  </p>
<p>The <code>setLocalStorage()</code> function takes into account whether the passed value is a function or a simple variable value. Also it takes care of setting the value of local storage using <code>localStorage.setItem()</code> function.</p>
<h2 id="heading-how-to-stand-out-as-a-developer-by-creating-side-projects">How to Stand Out as a Developer by Creating Side Projects</h2>
<p>The thing that has always worked for me and helped me stand out is my side projects that I've built.  </p>
<p>In my opinion, you don't have to build 10 basic cookie cutter side projects. Instead, try building one or two really good projects where you get to implement all the concepts of React/HTML/CSS/JavaScript and everything that you've been learning.  </p>
<p>Assume the interviewer has 14 interviews in a week and has to review the résumés of 14 candidates. They'll be more likely interested in your profile because you have created a <code>link shortener website that charges $1 after every 1000 link visits</code> instead of an Amazon / Netflix clone.</p>
<p>Again, there's nothing wrong with creating clones and practicing your skills. But it's always good to have at least 1 unique project that helps you stand out from the crowd.  </p>
<p>Also, creating side projects will help you upskill as a developer. It is not likely possible to know everything beforehand when creating a project from scratch. Along the way, you'll have to learn many different skills and get good at that.</p>
<h2 id="heading-practice-practice-practice">Practice, Practice, Practice.</h2>
<p>There's a famous saying that goes like this:</p>
<div class="embed-wrapper">
        <blockquote class="twitter-tweet">
          <a href="https://twitter.com/mannupaaji/status/1566350128767987712"></a>
        </blockquote>
        <script defer="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></div>
<p>and this is true to a great extent. </p>
<p>I myself have failed 100s of times before landing my first job. It's the constant feedback and iterations that you have to make in order to get what you want.  </p>
<p>In our case, getting a front-end job becomes easy when:</p>
<ul>
<li>You have in depth knowledge of your skills – React in this case (along with HTML, CSS, and JS).</li>
<li>You have a set of projects to showcase, making you stand out.</li>
<li>You're willing to put in the time and the effort to learn more and challenge yourself.</li>
<li>You read the freeCodeCamp blog regularly and practice questions there (😉)</li>
</ul>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>There are a lot of questions to practice for a machine-coding round. The interviewer can ask different sets of questions to test your skills.  </p>
<p>You can use <a target="_blank" href="https://algochurn.com"><strong>Algochurn</strong></a> to practice the most popular <a target="_blank" href="https://www.algochurn.com/blog/top-5-react-front-end-questions-to-practice-before-a-technical-interview-round">JavaScript interview questions</a>, <a target="_blank" href="https://algochurn.com/frontend">React Interview Questions</a>, and <a target="_blank" href="https://algochurn.com/problems">algorithmic questions</a> asked in a front-end technical interview round along with their solutions and approaches.</p>
<p>If you have any questions, please reach out to me via <a target="_blank" href="https://twitter.com/mannupaaji">Twitter(@mannupaaji)</a> and/or my <a target="_blank" href="https://manuarora.in">website(manuarora.in)</a></p>
<p>Good luck and Happy Coding! 👑🫡</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Coding Interview Practice – Sample Interview Questions and Solutions ]]>
                </title>
                <description>
                    <![CDATA[ By Damla Erkiner David Goggins is an ultramarathon runner, a public speaker, a retired navy SEAL, and the author of the book 'Can't Hurt Me: Master Your Mind and Defy the Odds'. He's one of my role models because of his physical strength and mental r... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-coding-interview-practice/</link>
                <guid isPermaLink="false">66d45e01d1ffc3d3eb89dda9</guid>
                
                    <category>
                        <![CDATA[ coding interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 31 Aug 2022 17:39:28 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/08/david-goggins-quotes-about-hard-work.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Damla Erkiner</p>
<p>David Goggins is an ultramarathon runner, a public speaker, a retired navy SEAL, and the author of the book '<a target="_blank" href="https://www.amazon.com/Cant-Hurt-Me-Master-Your/dp/1544512287"><strong>Can't Hurt Me: Master Your Mind and Defy the Odds</strong></a>'. He's one of my role models because of his physical strength and mental resilience. </p>
<p>You might say: "Wait a second! We get it. This person is obviously the epitome of success. But he has non-technical skills. So why is he relevant to JavaScript coding interviews?" </p>
<p>Well, if you're ready, let's explore this together.</p>
<h3 id="heading-rocky-balboa-as-a-mentor">Rocky Balboa As a Mentor</h3>
<p>In response to a question, David says, 'The Rocky Movie changed my life." In <a target="_blank" href="https://www.youtube.com/watch?v=dse1afiGbx4&amp;t=193s">that pep talk</a>, he refers to <a target="_blank" href="https://www.youtube.com/watch?v=25NmudB2fqg">this scene</a> (min 1.30-1.42) where the fictional character, Rocky - despite being beaten up badly by his opponent in the final boxing round - refuses to give up no matter what. </p>
<p>David describes that particular moment as the time when Rocky - initially depicted as an underdog by the screenwriter - overcomes all the odds and strikes awe in his rival.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-280.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.amazon.com/Eye-Tiger-Rocky/dp/B004GY1FTQ">Illustration Source</a></em></p>
<p>Let's admit it. Being a good programmer is not that easy. And especially if you are at the beginning of your career, technical job interviews can be seriously daunting. In short, it might be nice to reach David's (and Rocky's) mindset. </p>
<p>With that kind of drive and confidence, you're much less likely to consider giving up regardless of the types of challenges you face in your wonderful yet difficult journey of getting a developer job.</p>
<h2 id="heading-why-coding-interviews-are-difficult">Why Coding Interviews Are Difficult</h2>
<p>During coding interviews, you are expected to fix coding problems with some theoretical knowledge. But the caveat is you must do that in real time, which sometimes scares new developers off. </p>
<p>There are several types of coding interviews. But the most challenging one is probably a whiteboard interview. In these types of interviews, you have to code in front of a future employer / a senior software developer.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-319.png" alt="Image" width="600" height="400" loading="lazy">
<em>[Illustration by HackerRank](https://www.hackerrank.com/blog/virtual-whiteboarding-for-system-design-interviews/"&gt;&lt;nr-sentence class="nr-s20" id="nr-s20" page="0)</em></p>
<p>These interviews can be extra stressful because you are typically not allowed to have a computer to google any unknown concepts or to get some code snippets from the internet. You are only given a marker to solve the question on a whiteboard as the name suggests.</p>
<h3 id="heading-do-interviews-reflect-what-youll-do-in-your-job">Do Interviews Reflect What You'll Do in Your Job?</h3>
<p>Not necessarily. So why are they holding these scary coding interviews? Well, the reason is to test your problem solving skills in general. At times, finding the correct answer may not even be that important. </p>
<p>What matters is how you reach that conclusion / solution and which algorithms you prefer to use along the way. In other words, your ability to function well under stress is being tested by tech companies. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-329.png" alt="Image" width="600" height="400" loading="lazy">
_[Image Source](https://www.reddit.com/r/ProgrammerHumor/comments/l6wnvt/interview_vs<em>job/"&gt;&lt;nr-sentence class="nr-s30" id="nr-s30" page="0)</em></p>
<p>Let's face it. You'll come across lots of stressful situations in your future job, and how you deal with certain issues is especially crucial. Therefore, your future employer naturally wants to witness firsthand whether you are the right fit for the job. </p>
<h2 id="heading-what-is-the-purpose-of-this-tutorial">What is the Purpose of This Tutorial?</h2>
<p>In this post, I'll walk you through some popular JavaScript interview concepts through examples. I'll also do my best to show you what recruiters / interviewers might actually be looking for in a candidate while they code in front of them. </p>
<p>To simply put, we'll examine some models and try to solve the related puzzles together. </p>
<p>By the end of this tutorial, you'll hopefully have an idea about a number of important array methods. But most importantly, you'll unlock how to approach some coding challenges in the best way possible.</p>
<h2 id="heading-what-exactly-is-the-memory-palace-method">What Exactly is the Memory Palace Method?</h2>
<p>Before we start, just be aware that in the sample data down below, I've used some late celebrities' names intentionally so that all those details can be catchy in the long run. </p>
<p>An ancient technique called <a target="_blank" href="https://www.wired.co.uk/article/memory-palace-technique-explained">the Memory Palace</a> clearly says that the weirder the details, the easier it is to remember them – and a made-up story / creating context is even more effective. </p>
<p>If you try to visualise the related situation vividly and associate the given programming concepts with some bizarre details in your mind, you might feel less stressed and confused when you see a similar problem next time. This is because it might be easier for you to create specific links and as such remember things easily. This is how our brains work. </p>
<p>Well, even the fictional figure '<a target="_blank" href="https://www.smithsonianmag.com/arts-culture/secrets-sherlocks-mind-palace-180949567/">Sherlock Holmes</a>', the smartest guy on the planet, benefits from this method when solving complicated crimes – so why shouldn't we?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-321.png" alt="Image" width="600" height="400" loading="lazy">
<em>[Illustration by Savanahcat](https://www.deviantart.com/savanahcat/art/Mind-Palace-387601041"&gt;&lt;nr-sentence class="nr-s43" id="nr-s43" page="0)</em></p>
<h2 id="heading-how-to-approach-coding-problems">How to Approach Coding Problems</h2>
<p>In our imaginary interview, you'll see that four extraordinary musicians from the past are listed as passengers on a flight. We have their food choices and the number of connecting flights they need to take after their incredible performances on stage in different parts of the world.</p>
<p>Let's say just for the sake of argument our phenomenal figures (Freddie Mercury, Amy Winehouse, Kurt Cobain, and Michael Jackson) are about to fly from different destinations to Los Angeles just to be able to dine out together at a swanky restaurant, as they enjoy each other's company so much. </p>
<p>After all, this is our own private memory palace, so we can absolutely do whatever we want to do in our minds. Remember unusual details will stick better. That's why I'm trying to add more to spice things up. </p>
<p>This method explicitly suggests describing every single detail with some vivid adjectives so that you can associate them with the things you plan to learn in the long run. </p>
<p><a target="_blank" href="https://www.medicalnewstoday.com/articles/memory-loss#:~:text=Short%2Dterm%20memory%20is%20the,from%20a%20longer%20time%20ago.">Scientists</a> say short term memory and long term memory function very differently. To put it simply, we need a way to put all those core concepts (not necessarily the syntax) about programming in our long term memory. That's why it can be nice to benefit from the memory palace method in our journey.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-326.png" alt="Image" width="600" height="400" loading="lazy">
<em>[Image Source](https://www.nme.com/news/music/producer-goes-viral-for-mixing-nirvana-and-michael-jackson-songs-with-drill-beats-2747204"&gt;&lt;nr-sentence class="nr-s56" id="nr-s56" page="0)</em></p>
<p>Plus, I feel like you get to picture this unusual scenario with a smile on your face. Well, wouldn't it be great if these awesome souls could have seen that they are now helping us / the programming community as the guests of a freeCodeCamp article? </p>
<h3 id="heading-sample-interview-questions">Sample Interview Questions</h3>
<p>Let's get back to the real life now though. Remember you're still in the interview and as you see below, three questions in a row are waiting for you.</p>
<pre><code class="lang-js">
<span class="hljs-comment">// Main Question: Get the passengers' names using the data provided </span>
<span class="hljs-comment">// Bonus Part (a)- Return vegetarians/vegans</span>
<span class="hljs-comment">// Bonus Part (b)- Sort passengers by the number of connected flights in descending order</span>
</code></pre>
<h3 id="heading-the-data">The Data</h3>
<p>To solve the puzzles, you're expected to use the data inside the following array of objects in practical ways. </p>
<p>You'll certainly need to come up with the right algorithms and try to find the most effective solution that can satisfy the interviewer. </p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> passengers = [
  {
    <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">passengerName</span>: <span class="hljs-string">"Freddie Mercury"</span>,
    <span class="hljs-attr">isVegetarianOrVegan</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">connectedFlights</span>: <span class="hljs-number">2</span>,
  },
  {
    <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>,
    <span class="hljs-attr">passengerName</span>: <span class="hljs-string">"Amy Winehouse"</span>,
    <span class="hljs-attr">isVegetarianOrVegan</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">connectedFlights</span>: <span class="hljs-number">4</span>,
  },
    {
    <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>,
    <span class="hljs-attr">passengerName</span>: <span class="hljs-string">"Kurt Cobain"</span>,
    <span class="hljs-attr">isVegetarianOrVegan</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">connectedFlights</span>: <span class="hljs-number">3</span>,
  },
     {
    <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>,
    <span class="hljs-attr">passengerName</span>: <span class="hljs-string">"Michael Jackson"</span>,
    <span class="hljs-attr">isVegetarianOrVegan</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">connectedFlights</span>: <span class="hljs-number">1</span>,
  },
];
</code></pre>
<p>The above questions are in fact not that hard. But, how we'll handle them is a great opportunity to compare alternative solutions for a single problem. At the end of the day, quality is what counts for recruiters / interviewers. </p>
<h3 id="heading-interview-question-1-how-to-get-passengers-names">Interview Question 1: How to Get Passengers' Names</h3>
<p>Let's get the passengers' names as requested. The first solution is through a <a target="_blank" href="https://www.freecodecamp.org/news/javascript-for-loop-how-to-loop-through-an-array-in-js/">'for loop'</a> method. So we first need to use an empty array to push the passengers' names right inside it at the end of the loop. </p>
<p>Below, <code>[i]</code> represents the current passenger and we simply loop through the 'passengers' array to access the names of the passengers. Then, we need to lock them up in our empty array / passengerNames.</p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> passengerNames = [];
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; passengers.length; i++) {
    passengerNames.push(passengers[i].passengerName)
}
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"passengers"</span>, passengerNames);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-331.png" alt="Image" width="600" height="400" loading="lazy">
<em>RESULT - using 'for loop'</em></p>
<p>Alright, we solved the puzzle, but is it enough? Or might the interviewers expect you to come up with a better solution?</p>
<h3 id="heading-alternative-solution-1">Alternative Solution #1:</h3>
<p>We can reach the desired result by using the '<a target="_blank" href="https://www.freecodecamp.org/news/javascript-foreach-how-to-loop-through-an-array-in-js/">forEach</a>' function as well. This solution is even a bit better than the previous one because there is no index expression in this one. </p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> passengerNames = [];
passengers.forEach(<span class="hljs-function">(<span class="hljs-params">passenger</span>) =&gt;</span> {
    passengerNames.push(passenger.passengerName);
})
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-332.png" alt="Image" width="600" height="400" loading="lazy">
<em>RESULT - using 'forEach'</em></p>
<p>To benefit from 'forEach', we need <a target="_blank" href="https://www.freecodecamp.org/news/what-is-a-callback-function-in-javascript-js-callbacks-example-tutorial/">a callback function</a>. With this arrangement, we are able to reach every passenger in the list. However, just like in the previous solution, we first need an empty array to push the items / passengers' names. </p>
<p>Even though the result is the same, this piece of code is shorter. Writing neater codes is what is – in fact – expected from you. </p>
<p>In other words, not only the solution matters, but also how you reach it is being evaluated by the recruiters. For this reason, it is a good idea to plan your action rather than writing the first idea in your mind on the whiteboard.</p>
<h3 id="heading-alternative-solution-2">Alternative Solution 2:</h3>
<p>Here comes the best solution. We can also utilise the '<a target="_blank" href="https://www.freecodecamp.org/news/javascript-map-how-to-use-the-js-map-function-array-method/">map</a>' function to tackle the same problem. Let's see how.</p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> passengerNames = passengers.map(<span class="hljs-function">(<span class="hljs-params">passenger</span>) =&gt;</span> passenger.passengerName);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-333.png" alt="Image" width="600" height="400" loading="lazy">
<em>RESULT - using 'map'</em></p>
<p>The map function also loops through the array and returns a new array for every item in the list. With this set-up, we simply return a single element, not an object. </p>
<p>The result will again be the same in the console, but your code will even be better than the first and second one because this time, we don't need to create an empty array before the actual task. </p>
<p>Here is the food for thought on this topic. Those who say 'less is more' have a point when it comes to writing codes. </p>
<h3 id="heading-interview-question-2-how-to-get-vegetarianvegan-singers">Interview Question 2: How to Get Vegetarian/Vegan Singers</h3>
<p>Let's now take a look at the next challenge. The new task asks us to obtain only the vegetarian / vegan singers from the passengers' list by also keeping the first argument in the main question section. </p>
<h3 id="heading-how-to-solve-with-a-for-loop">How to Solve With a 'For Loop'</h3>
<p>Again, we can use the same old 'for loop' for this one as well. All we need to do is to check whether there are any vegetarian / vegan singers in our passenger list through an 'if' statement inside our existing function.</p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> passengerNames = [];
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; passengers.length; i++) {
    <span class="hljs-keyword">if</span>(passengers[i].isVegetarianOrVegan) {
    passengerNames.push(passengers[i].passengerName)
    }
}
<span class="hljs-built_in">console</span>.log(passengerNames);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-334.png" alt="Image" width="600" height="400" loading="lazy">
<em>RESULT - using 'for loop'</em></p>
<p>We do that with the <code>isVegetarianOrVegan</code> property in our object. Basically, what we say is this: if the relevant statement is true (if there are any vegan / vegetarian passengers in the list), just push those items into our new array. The result will give us three singers' names as those are listed as  'vegetarian or vegan' in the data part. </p>
<h3 id="heading-how-to-solve-with-foreach">How to Solve with 'forEach'</h3>
<p>As a matter of fact, the 'forEach' function handles the problem similarly. But once again, it has too many lines of codes as you see below, so it isn't the ideal version. </p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> passengerNames = [];
passengers.forEach(<span class="hljs-function">(<span class="hljs-params">passenger</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (passenger.isVegetarianOrVegan)
        passengerNames.push(passenger.passengerName);
});

<span class="hljs-built_in">console</span>.log(passengerNames);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-335.png" alt="Image" width="600" height="400" loading="lazy">
<em>RESULT / 'forEach'</em></p>
<h3 id="heading-how-to-solve-with-filter-amp-map">How to Solve with 'Filter' &amp; 'Map'</h3>
<p>To come up with the best option, this time, we will use two different methods. The '<a target="_blank" href="https://www.freecodecamp.org/news/javascript-array-filter-tutorial-how-to-iterate-through-elements-in-an-array/">filter</a>' and the 'map' functions will – in a way – collaborate to create better logic when solving the given problem. Let's examine the following code snippet closely now.</p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> passengerNames = passengers.filter(<span class="hljs-function">(<span class="hljs-params">passenger</span>) =&gt;</span> passenger.isVegetarianOrVegan).map(<span class="hljs-function">(<span class="hljs-params">passenger</span>) =&gt;</span> passenger.passengerName);

<span class="hljs-built_in">console</span>.log(passengerNames);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-336.png" alt="Image" width="600" height="400" loading="lazy">
<em>RESULT / 'filter' + 'map'</em></p>
<p>With the filter method, we only get the vegetarian / vegan passengers from our array in the first place. If it finds some non-vegetarian / vegan passengers (like our beloved 'Freddie'), it will get rid of them automatically. </p>
<p>Briefly, the first part of the equation, the 'filter' method will simply work through 'yes' or 'no' model. </p>
<p>Then, the 'map' function will come in, eventually giving us a brand new array showing the vegetarian / vegan passengers only. </p>
<p>This final solution will prove your future employer that you genuinely know what you're doing and you are really taking the right steps to be a hotshot developer.</p>
<h3 id="heading-interview-question-3-how-to-sort-passengers-by-connecting-flights">Interview Question #3: How to Sort Passengers by Connecting Flights</h3>
<p>The last section asks us to sort the list of our super cool passengers by the number of the connecting flights they'll take to eventually reach LA. Let's see who has more and as such, will be pretty exhausted. </p>
<p>Spoiler alert! Amy with four connecting flights in total might be a bit sleepy in the get-together at that fancy restaurant. But there is no doubt that she will somehow rock where ever she goes. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-322.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://variety.com/2022/music/global/amy-winehouse-freddie-mercury-john-lennon-tupac-shakur-bbc-studios-sales-1235196177/">Image Source</a></em></p>
<p>Anyway, what we need for this task is to know how the '<a target="_blank" href="https://www.freecodecamp.org/news/javascript-array-sort-tutorial-how-to-use-js-sort-methods-with-code-examples/">sort</a>' function operates.</p>
<p>Primarily, it compares items one by one and returns something as a result. In our case, it will be the number of connected flights. But how does it make that comparison? What is the logic behind that?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-343.png" alt="Image" width="600" height="400" loading="lazy">
_[Source Code: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global<em>Objects/Array/sort"&gt;&lt;nr-sentence class="nr-s149" id="nr-s149" page="0)</em></p>
<p>The above lines of code are pretty clear in general. Thanks to the 'sort' function, we list those months in alphabetical order. </p>
<p>Well, here comes the big question. How does the code / system know that 'a' is the first letter of the alphabet and as such, the list starts with the 'd' letter (December)?</p>
<p>The reason is that the 'sort function' lists things in ascending order by default. But can't we change this setting? Perhaps, we need to list items in descending order. Of course, we can. </p>
<p>Let's see how. To achieve what we want, we may utilise 'a' and 'b' letters as parameters leading to different directions.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-338.png" alt="Image" width="600" height="400" loading="lazy">
_[Source Code: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global<em>Objects/Array/sort"&gt;&lt;nr-sentence class="nr-s160" id="nr-s160" page="0)</em></p>
<p>Simultaneously, we can benefit from the assistance of three numbers: -1,+1, 0 as seen above. When sorting items in descending or ascending order or finding the equal values, they can be quite handy. </p>
<h3 id="heading-tricky-bit-of-the-sort-function">Tricky Bit of the 'Sort' Function</h3>
<p>In the following example, the list is sorted in ascending order. Why is it like that? Here is the reason. When we return those 'a' and 'b' parameters, we use this order:  'a - b' . That gives us ascending values by default. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-339.png" alt="Image" width="600" height="400" loading="lazy">
_[Source Code: MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global<em>Objects/Array/sort"&gt;&lt;nr-sentence class="nr-s169" id="nr-s169" page="0)</em></p>
<p>However, if we swap them and say 'b - a', the list will be seen in descending order this time. That's the tricky bit when it comes to the 'sort' function.</p>
<p>In the above example, the first version (regular function) and the second one (arrow function) are in essence the same, but just be aware that <a target="_blank" href="https://www.freecodecamp.org/news/arrow-function-javascript-tutorial-how-to-declare-a-js-function-with-the-new-es6-syntax/">arrow functions</a> came with <a target="_blank" href="https://www.freecodecamp.org/news/these-are-the-features-in-es6-that-you-should-know-1411194c71cb/">ES6</a>. </p>
<p>Although arrow functions help developers to write less code, you cannot use them everywhere. (Read <a target="_blank" href="https://www.freecodecamp.org/news/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26/">this</a> to find out when to use them.)</p>
<h3 id="heading-testing-our-new-knowledge">Testing Our New Knowledge</h3>
<p>Shall we now analyse the situation of our passengers through our new perspective? We know that the last task asks us to sort the number of flights in descending order. But the following set-up does the opposite. </p>
<p>It can only give us the list in ascending order. Why? It's simply because of the pre-defined order (passenger1.connectedFlights - passenger2.connectedFlights) as in the case of a - b example.</p>
<pre><code class="lang-js">
 <span class="hljs-keyword">const</span> numberOfFlights = passengers.sort(
  <span class="hljs-function">(<span class="hljs-params">passenger1, passenger2</span>) =&gt;</span>
    passenger1.connectedFlights -  passenger2.connectedFlights 
); 
<span class="hljs-built_in">console</span>.log(numberOfFlights);
</code></pre>
<p>Once we swap the order (passenger2.connectedFlights - passenger1.connectedFlights) as you see in the following code snippet, our problem will be solved and the list will come in descending order. </p>
<pre><code class="lang-js">
 <span class="hljs-keyword">const</span> numberOfFlights = passengers.sort(
  <span class="hljs-function">(<span class="hljs-params">passenger1, passenger2</span>) =&gt;</span>
    passenger2.connectedFlights -  passenger1.connectedFlights 
); 
<span class="hljs-built_in">console</span>.log(numberOfFlights);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-342.png" alt="Image" width="600" height="400" loading="lazy">
<em>RESULT - Descending Order by the Number of Connected Flights / Michael is the luckiest :-)</em></p>
<h3 id="heading-can-we-also-use-for-loop-or-foreach">Can We Also Use 'for loop' or 'forEach'?</h3>
<p>Well, yes and no. Both would be low-level solutions for this question. </p>
<p>We should keep in mind that the sort function mutates an array. This is a kind of side effect which changes the original array and that might be a problem if we use 'for loop' or 'forEach' as a solution. </p>
<p>There are of course <a target="_blank" href="http://www.buginit.com/javascript/javascript-sort-without-mutating-array/">ways</a> to avoid mutation in the sort function, but in our example, it will lead to more lines of codes, which is not practical at all.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>We've started the article with David Goggins, the symbol of resilience and grit, so let's end it with his inspiring presence and ideas. </p>
<p>If you happen to read this modern day hero's book or listen to one of those famous podcast episodes (For example, <a target="_blank" href="https://www.youtube.com/watch?v=5tSTk1083VY">this one</a>) where he was a guest speaker, you'll immediately understand that he wasn't born that way. Rather, his secret lies in the fact that he never gives up, against all odds. </p>
<p>Coding interviews are tough, but if you keep going after your goals by visualising the scene of success in your mind over and over again, it will -  sooner or later - be yours. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-328.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://castromarina.info/david-goggins-inspirational-quotes">Image Source</a></em></p>
<p>Many thanks for reading this post. If you've liked this article, one of the best ways to support me is to share it. Should you have any questions or comments, you can always contact me via <a target="_blank" href="https://www.linkedin.com/in/damla-erkiner-000b76227/">LinkedIn</a>. I'll be more than happy to help you out with your queries.</p>
<p>Happy coding!</p>
<p><strong>“Knowledge is power.” – Francis Bacon</strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Most Popular Coding Challenge Websites ]]>
                </title>
                <description>
                    <![CDATA[ If you want to improve your analytical skills, there's no better way to do that than solving problems.  If you are a programmer, then this is something you should do for yourself. Programmers need to deal with all sorts of problems almost every day. ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-most-popular-coding-challenge-websites/</link>
                <guid isPermaLink="false">66b90316941d2f900bad52aa</guid>
                
                    <category>
                        <![CDATA[ coding challenge ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interviewing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Job Hunting ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Md. Fahim Bin Amin ]]>
                </dc:creator>
                <pubDate>Wed, 15 Jun 2022 22:23:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/fCC-Banner.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you want to improve your analytical skills, there's no better way to do that than solving problems. </p>
<p>If you are a programmer, then this is something you should do for yourself. Programmers need to deal with all sorts of problems almost every day. </p>
<p>Most importantly, solving problems in an efficient manner can make you much more productive. And solving challenging problems helps us do that.</p>
<h2 id="heading-you-can-watch-this-complete-video-on-youtube-as-well-if-you-like">You can watch this complete video on YouTube as well if you like 🎥</h2>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/45wrQ-RAefI" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-why-should-you-develop-your-problem-solving-skills">Why Should You Develop Your Problem-Solving Skills?</h2>
<p>These days, technology is developing rapidly, and we are seeing some amazing changes and improvements almost every day. </p>
<p>Whenever we talk about technology, a buzzword appears in our mind – and that is coding or programming. Now, coding/programming isn't just about solving different kinds of problems using different programming languages, but it's a large part of what you'll do as a developer.</p>
<p>The fields of Web development, Machine Learning, Artificial Intelligence, Augmented Reality, App Development, and many others require strong problem-solving skills. </p>
<p>There are many popular websites that help you do that by providing various types of problems where you need to apply your analytical and mathematical skills to solve each problem using programming languages.</p>
<p>I am going to provide you with a list of coding challenge websites that will help you become more advanced day by day. </p>
<p>Keep in mind that these websites are useful for everybody, whether you are new to coding challenges or you are a professional programmer and so on.</p>
<h1 id="heading-contents">Contents</h1>
<ol>
<li><a class="post-section-overview" href="#heading-1-beecrowd-formerly-uri-1">beecrowd</a></li>
<li><a class="post-section-overview" href="#heading-2-hackerrank-2">HackerRank</a></li>
<li><a class="post-section-overview" href="#heading-3-codeforces-1">Codeforces</a></li>
<li><a class="post-section-overview" href="#heading-4-leetcode-1">LeetCode</a></li>
<li><a class="post-section-overview" href="#heading-5-kaggle-1">Kaggle</a></li>
<li><a class="post-section-overview" href="#heading-6-codechef-1">CodeChef</a></li>
<li><a class="post-section-overview" href="#heading-7-atcoder-1">AtCoder</a></li>
<li><a class="post-section-overview" href="#heading-8-topcoder">Topcoder</a></li>
<li><a class="post-section-overview" href="#heading-9-coderbyte">Coderbyte</a></li>
<li><a class="post-section-overview" href="#heading-10-project-euler">Project Euler</a></li>
<li><a class="post-section-overview" href="#heading-11-codewars">Codewars</a></li>
<li><a class="post-section-overview" href="#heading-12-spoj">SPOJ</a></li>
<li><a class="post-section-overview" href="#heading-13-codingame">CodinGame</a></li>
<li><a class="post-section-overview" href="#heading-14-geeksforgeeks-popularly-known-as-gfg-1">GeeksforGeeks</a></li>
<li><a class="post-section-overview" href="#heading-15-toph">Toph</a></li>
<li><a class="post-section-overview" href="#heading-16-lightoj-1">LightOJ</a></li>
<li><a class="post-section-overview" href="#heading-17-exercism">Exercism</a></li>
<li><a class="post-section-overview" href="#heading-18-online-judge-commonly-known-as-uva">Online Judge</a></li>
<li><a class="post-section-overview" href="#heading-19-hackerearth">HackerEarth</a></li>
<li><a class="post-section-overview" href="#heading-20-code-jam-googles-coding-competitions-1">Code Jam - Google's Coding Competitions</a></li>
<li><a class="post-section-overview" href="#heading-21-icpc-international-collegiate-programming-contest-1">ICPC</a></li>
</ol>
<h1 id="heading-best-coding-challenge-websites">Best Coding Challenge Websites</h1>
<h2 id="heading-1-beecrowdhttpswwwbeecrowdcombrjudgeenlogin-formerly-uri">1. <a target="_blank" href="https://www.beecrowd.com.br/judge/en/login">beecrowd</a> (Formerly URI)</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/zwnoz97xawck4unafkbz.png" alt="beecrowd banner" width="600" height="400" loading="lazy"></p>
<p>beecrowd is perfect for those who have just started solving coding challenges and are looking for a beginner-friendly website. It used to be named <strong>URI</strong>, so there is a chance that you are already familiar with this site as URI.</p>
<p>If you want to solve problems in a specific category, then you're in luck as this website also offers that.</p>
<figure>
  <img src="https://www.freecodecamp.org/news/content/images/2022/07/chodi765ql8li7b9yia6-resized.jpeg" class="kg-image" alt="A dropdown showing the different challenge categories on beercrowd" width="600" height="400" loading="lazy">
</figure>

<p>Here is an image of a <strong>Strings</strong> problem set. You can also filter the problems by the ID (#), name (NAME), Subject (SUBJECT), solved (SOLVED), and so on. Beginners like these features very much.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/2afljp6rrtm1c4co62vr.png" alt="2afljp6rrtm1c4co62vr" width="600" height="400" loading="lazy"></p>
<p>On this website, you can also take part in different programming contests, and check your global ranking, country-wide ranking, and university-wide ranking.</p>
<p>Also, you can check your progress, how many days have passed after signing up, how many problems you have solved, how many points you have got, and more.</p>
<p>You will also get a nice profile page that looks beautiful as well. 😊 I used to practice solving problems on this website when I was just starting out my CP (Competitive Programming) journey. Not to mention, I got the 3rd position among 1250 students back then at my university. 🎉 </p>
<p>You can also check out my <a target="_blank" href="https://www.beecrowd.com.br/judge/en/profile/436965">beecrowd profile here</a>.</p>
<h2 id="heading-2-hackerrankhttpswwwhackerrankcom">2. <a target="_blank" href="https://www.hackerrank.com/">HackerRank</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/wla1ho0uoz9xuvp5iuwi.png" alt="wla1ho0uoz9xuvp5iuwi" width="600" height="400" loading="lazy"></p>
<p>HackerRank is one of the most popular coding practice websites out there. This is a nice platform for everyone, especially beginners. </p>
<p>The website looks nice and polished, and the users who come here the first time don't struggle when navigating throughout the website, so that is definitely a positive thing here.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/wr0o61pq2ngfwil3ys9d.png" alt="Login page" width="600" height="400" loading="lazy"></p>
<p>HackerRank offers different portals for companies and developers. If you are learning to solve problems, then you will choose the <strong>For Developers</strong> section.</p>
<p>If you want to learn any specific topics or programming languages, then this website is the perfect place to get started in that. You can prepare yourself by topics. You can also take their certification exam and stand out from the crowd. I have already passed their Python (Basic) certification exam.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/k3j4sfp9tovx9ifphf0a.png" alt="Prep" width="600" height="400" loading="lazy"></p>
<p>You can also choose preparation kits from there, and prepare yourself before your interview if you want. Moreover, you can take part in programming contests.</p>
<p>Here, you will also get a nice personal profile page. You can check out my profile from HackerRank <a target="_blank" href="https://www.hackerrank.com/FahimFBA">here</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/sfp2rcqtx9b4fs8wv3m8.png" alt="My HackerRank profile" width="600" height="400" loading="lazy"></p>
<h2 id="heading-3-codeforceshttpscodeforcescom">3. <a target="_blank" href="https://codeforces.com/">Codeforces</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/8wtc4xnpohe9yr6j2eij.png" alt="Codeforces Banner" width="600" height="400" loading="lazy"></p>
<p>Codeforces is one of the most used and well-known coding challenge and practice websites in the world, and it is sponsored by Telegram. Especially if you know about CP (Competitive Programming), then there is a high chance you have heard a lot about this website.</p>
<p>Although the website might look a little bit different to newcomers, you won't need much time to get used to it. You can train yourself by solving problems of different categories, difficulty levels, and so on. </p>
<p>Competitive programmers have ranks based on their successful results in programming contests. If you have heard about the <strong>RED</strong> coder / <strong>PURPLE</strong> coder, etc, then it is definitely from Codeforces.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/17fansawmwowcvhyc639.png" alt="Codeforces Ranking System" width="600" height="400" loading="lazy"></p>
<p>You can get the idea of the ranking system on Codeforces from the image above. For more details, you can check out <a target="_blank" href="https://codeforces.com/blog/entry/68288">this blog entry</a>.</p>
<p>Codeforces arranges contests regularly each week, and they are categorized into div 1, div 2, div 3 and div 4. They also arrange global round and educational round contests. You can get the timeline of the contests directly from <a target="_blank" href="https://codeforces.com/contests">here</a>.</p>
<p>Codeforces also provides a nice user profile on their website. You can check mine <a target="_blank" href="https://codeforces.com/profile/FahimFBA">here</a> as well.</p>
<h2 id="heading-4-leetcodehttpsleetcodecom">4. <a target="_blank" href="https://leetcode.com/">LeetCode</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/jk9l09bi3ku5d0op2x7j.png" alt="Leetcode banner" width="600" height="400" loading="lazy"></p>
<p>If you are familiar with the <strong>FAANG</strong> (Facebook, Apple, Amazon, Netflix, Google) buzzword, then you should definitely know about this website! If you want to practice for your coding interview for the big giant tech companies like FAANG, then they all do <strong>leetcoding</strong>.</p>
<p>You might think that I have made a typo in the above paragraph. No, I didn't. LeetCode has become this popular among people who target FAANG and those who are working on their problem solving skills. Taking part in contests on LeetCode has become common, and people call it leetcoding! </p>
<p>Here, you can solve a lot of problems, and filter the problems by the lists, difficulty levels, status, and tags.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/tphf8k817fbz0vsge9d3.png" alt="LeetCode ProblemSet1" width="600" height="400" loading="lazy"></p>
<p>You can also choose problems regarding Arrays, Strings, Hash Tables, Dynamic Programming, and many other categories.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/0y0ov1fxzvxwiv5bglri.png" alt="LeetCode ProblemSet2" width="600" height="400" loading="lazy"></p>
<p>As I mentioned above, you can also take part in programming contests. The only thing that makes LeetCode different is that it is based on Algorithm practice. Yeah, LeetCode is not like any other coding website, because it focuses on algorithm practice alone. </p>
<p>You do not need to provide the full code for solving a problem here, you just need to crack the solution by providing a valid algorithm using any popular language that can solve the problem.</p>
<p>You also get to see how your code performs among others, how much space and time it takes, and so on. </p>
<p>Most importantly, LeetCode has an amazing discussion group where people talk about their problems, solutions, how to improve their algorithms, how to improve the efficiency of their code, and so on. This is one of the most powerful features of LeetCode.</p>
<p>One sad part about LeetCode is that you will not get every feature for free! Yeah, it's true. You have to pay for it monthly or yearly to unlock all its features. There are a lot of problems you will find locked on the website. You can not unlock them if you do not purchase the premium plan.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/tvww5ogj3eq5qw23ss8m.png" alt="LeetCode pricing" width="600" height="400" loading="lazy"></p>
<p>If you are just starting your algorithm journey on LeetCode, then actually you don't need to worry about their premium plans as the free version will be more than enough for you. </p>
<p>Later, if you want to become more serious, then paying for their premium subscription will be a big deal actually as you'll get a ton more features. This is very much helpful, and includes things like top interview questions, top FAANG questions, video explanations, and more.</p>
<p>You also get a nice profile page on LeetCode. You can check out mine <a target="_blank" href="https://leetcode.com/FBA/">here</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/7rv0yyw75le21sndymru.png" alt="My LeetCode profile" width="600" height="400" loading="lazy"></p>
<h2 id="heading-5-kagglehttpswwwkagglecom">5. <a target="_blank" href="https://www.kaggle.com/">Kaggle</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/28oqgu17gaiczlsv0k2t.png" alt="Kaggle banner" width="600" height="400" loading="lazy"></p>
<p>I was pretty confused before writing this section, as Kaggle is not a typical website for coding practice. This website is basically for Data Science, and it's one of the most popular websites out there for this. </p>
<blockquote>
<p>Kaggle is an online community platform for data scientists and machine learning enthusiasts. </p>
<p>It is a popular crowd-sourced platform to attract, nurture, train, and challenge Data Science and Machine Learning enthusiasts from all around the world to come together and solve numerous Data Science, Predictive Analytics, and Machine Learning problems.</p>
</blockquote>
<p>So if you are interested in Data Science, then you should check this website. Here you can check others' notebooks, submit your notebook, join in the contests, improve datasets, and so on.</p>
<blockquote>
<p>Kaggle allows users to collaborate with other users, find and publish datasets, use GPU integrated notebooks, and compete with other data scientists to solve data science challenges.</p>
</blockquote>
<p>Also, if you are interested in data science, but don't know where to start, then don't worry! Kaggle has got you covered. You can check their <a target="_blank" href="https://www.kaggle.com/learn">learning section</a> where they have many free courses which will teach you a lot of stuff from the beginning.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/b2jgodslps0qrx6txu59.png" alt="kaggle free courses" width="600" height="400" loading="lazy"></p>
<p>✨ BONUS: If you want to learn more then I'd suggest that you complete the <a target="_blank" href="https://www.youtube.com/playlist?list=PLWKjhJtqVAblQe2CCWqV4Zy3LY01Z8aF1">data science playlist</a> from freeCodeCamp's YouTube channel.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/voyp7nxuepo7azxw6syk.png" alt="fcc courses" width="600" height="400" loading="lazy"></p>
<p>Kaggle also provides rankings and a nice user profile. You can check out my profile <a target="_blank" href="https://www.kaggle.com/mdfahimbinamin">here</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/lqcwsixdumi4bxc670s9.png" alt="FBA kaggle" width="600" height="400" loading="lazy"></p>
<h2 id="heading-6-codechefhttpswwwcodechefcom">6. <a target="_blank" href="https://www.codechef.com/">CodeChef</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/8ma2hdum4nd1eo8zmjek.png" alt="CodeChef banner image" width="600" height="400" loading="lazy"></p>
<p>CodeChef is another popular Indian website like <a class="post-section-overview" href="#heading-2-hackerrank-2">HackerRank</a> where you can solve a lot of problems, take part in contests, and so on.</p>
<p>You can filter the problems based on different categories and solve them using any of the most popular programming languages. </p>
<p>They also have a learning section on their website where you can learn how to solve problems in a systematic way. This is super helpful, especially for beginners.</p>
<p>In their learning section, you can choose self-learning, mentored learning, and doubt support. Some of them are free of charge, but in some courses, you have to pay before you can start them.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/qyfzttpt7eq78zdqkdt9.png" alt="mentor price" width="600" height="400" loading="lazy"></p>
<p>This website also provides user ranking including the global ranking and country-wide ranking. They also provide a user profile on their website. You can check out mine <a target="_blank" href="https://www.codechef.com/users/fahimfba">here</a> although I am not active on most of the websites right now. 😅</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/vhq0agb1ijtdbsj3s7gu.png" alt="codechef fba" width="600" height="400" loading="lazy"></p>
<h2 id="heading-7-atcoderhttpsatcoderjp">7. <a target="_blank" href="https://atcoder.jp/">AtCoder</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/rqsw6hjecf5fqpqoxowp.png" alt="AtCoder banner image" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>AtCoder is a programming contest website based in Japan. Makoto Soejima (rng_58) who is one of the former admins and problem writers from Topcoder is a founding member of AtCoder.</p>
</blockquote>
<p>On this website, you can take part in different programming contests. They held regular programming contests on Saturdays and Sundays. Also, you can solve problems from previously held programming contests. </p>
<p>I have seen a lot of people regularly participate in the programming contests and solve problems previously used in the contests regularly by solving problems on AtCoder. I also tried that for a while to check the efficiency, and truth to be told, it was really effective.</p>
<p>Here you can also check the global ranking. Here you will also get your own profile page where you and others can see your global ranking and so on.</p>
<h2 id="heading-8-topcoderhttpswwwtopcodercom">8. <a target="_blank" href="https://www.topcoder.com/">Topcoder</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/89rcnewgpzfxbsb37inz.png" alt="Topcoder banner image" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>Topcoder (formerly TopCoder) is a crowdsourcing company with an open global community of designers, developers, data scientists, and competitive programmers. Topcoder pays community members for their work on the projects and sells community services to corporate, mid-size, and small-business clients.</p>
</blockquote>
<p>Here you can earn, learn, and do a lot more in their MVP program. For earning, you can participate in five different tracks, become a copilot, become a reviewer, and also get a freelance contract gig through <a target="_blank" href="https://www.topcoder.com/community/member-programs/gigs">Topcoder Gig Work</a>.</p>
<p>Personally, I feel this website is a little bit overwhelming for beginners. You can get more details in the YouTube videos I have made for you.</p>
<h2 id="heading-9-coderbytehttpscoderbytecom">9. <a target="_blank" href="https://coderbyte.com/">Coderbyte</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/5vm2yrbrsuhfi6lvsc1c.png" alt="Coderbyte banner image" width="600" height="400" loading="lazy"></p>
<p>Coderbyte has a huge collection of problems that you can solve. They also offer a challenging library, starter courses, interview kits, career resources and so on. </p>
<p>To get all the features, you need to buy a subscription plan from them. I personally liked their interview kit a lot.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/qnrvl8ja8rqwb6zun4e0.png" alt="Interview kits" width="600" height="400" loading="lazy"></p>
<p>Here you will also get a personal profile page.</p>
<h2 id="heading-10-project-eulerhttpsprojecteulernet">10. <a target="_blank" href="https://projecteuler.net/">Project Euler</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/howuvtc16ehu8lqbw520.png" alt="Project Euler banner image" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve.</p>
</blockquote>
<p>Project Euler is a great website for solving mathematical challenging problems. But solving a problem on this website requires more than just simple mathematical knowledge. </p>
<p>If you want to solve mathematical problems in a more analytical way, then this website will come in handy.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/94mguaui3nj6s7pcw942.png" alt="Problem set" width="600" height="400" loading="lazy"></p>
<h2 id="heading-11-codewarshttpswwwcodewarscom">11. <a target="_blank" href="https://www.codewars.com/">Codewars</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/ygf3uzjmuiycbu34fv5l.png" alt="Codewars banner image" width="600" height="400" loading="lazy"></p>
<p>Codewars is a coding challenge website for people of all programming levels. It claims to have a community of over 3 million developers. </p>
<p>One of the biggest benefits of this website is that it is highly focused on algorithms like LeetCode. Moreover, if your goal is to get very good at writing clean and efficient programs, then this website can be a great asset to you.</p>
<p>In Codewars, you will see <strong>Kata</strong> and <strong>Kyu</strong> a lot. </p>
<blockquote>
<p>Kyu (or Kyū) indicates the number of degrees away from master level (Dan). This is why they count downward. Once you reach master level, we count upward. Black belts in martial arts are Dan level.</p>
<p>On Codewars, kata are code challenges focused on improving skill and technique. Some train programming fundamentals, while others focus on complex problem solving. Others are puzzles meant to test your creative problem solving, while others are based on real world coding scenarios.</p>
</blockquote>
<p>If you want to know more about how the ranking system works on Codewars, then simply check their docs <a target="_blank" href="https://docs.codewars.com/gamification/ranks/">here</a>.</p>
<p>On Codewars you will also get a nice profile page like <a target="_blank" href="https://www.codewars.com/users/FBA">mine</a>. Keep in mind that I haven't solved that much on this website; therefore my profile page would seem empty. 😅</p>
<p>Additionally, I find their <a target="_blank" href="https://www.codewars.com/users/leaderboard">leaderboard page</a> quite amusing.</p>
<h2 id="heading-12-spojhttpswwwspojcom">12. <a target="_blank" href="https://www.spoj.com/">SPOJ</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/4awf6fpql913onx0111u.png" alt="SPOJ banner image" width="600" height="400" loading="lazy"></p>
<p>SPOJ is a website that contains huge problems for solving. It claims to have 315,000 registered users and over 20,000 problems.</p>
<p>According to GFG,</p>
<blockquote>
<p>You can start solving problems with maximum submission and follow or check the submission of good coders here. Once you solved around 50-70 problems and build some confidence, you can participate in different contests.</p>
</blockquote>
<p>Their problem set is also quite amusing.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/tm5g46f3qie8kr9aizwk.png" alt="SPOJ problem set" width="600" height="400" loading="lazy"></p>
<p>You will also get a nice user profile page here which you can use to showcase your problem solve skills.</p>
<h2 id="heading-13-codingamehttpswwwcodingamecom">13. <a target="_blank" href="https://www.codingame.com/">CodinGame</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/ybatrql4wgi7l45v0j57.png" alt="CodinGame banner image" width="600" height="400" loading="lazy"></p>
<p>In CodinGame, you can improve your coding skills with fun exercises in more than 25 programming languages. </p>
<p>It is a good website for intermediate and advanced software engineers to have fun while continuing to keep their skills sharp. Also, the challenges are gamified and the multiplayer access means that users can challenge friends and coworkers.</p>
<h2 id="heading-14-geeksforgeekshttpswwwgeeksforgeeksorg-popularly-known-as-gfg">14. <a target="_blank" href="https://www.geeksforgeeks.org/">GeeksforGeeks</a> (Popularly known as GFG)</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/wo3e2tzi15abavql5c9w.png" alt="GeeksforGeeks banner Image" width="600" height="400" loading="lazy"></p>
<p>You might wonder why I am including GFG in this article as it only provides algorithms, tutorials, and so on. </p>
<p>Well, that's not all they offer. Yes, GFG is pretty popular for its tutorials, algorithms, and so on, but they also provide a nice problem-solving platform <a target="_blank" href="https://practice.geeksforgeeks.org/">here</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/m8g6z50xvemt64t4pwvw.png" alt="practice GFG" width="600" height="400" loading="lazy"></p>
<p>You can also filter the problems as you see fit for yourself.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/iyajkn39wvqiqzpk52ba.png" alt="GFG filter" width="600" height="400" loading="lazy"></p>
<p>You will also get your profile page where you can show your progress in problem solving on the GFG website.</p>
<h2 id="heading-15-tophhttpstophco">15. <a target="_blank" href="https://toph.co/">Toph</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/5x4jgisa0oeaso2h2lu4.png" alt="Toph banner image" width="600" height="400" loading="lazy"></p>
<p>Competitive programmers participate in programming contests and solve many problems on this website. This website is kind of special to the Bangladeshi people as the Bangladeshi universities arrange many programming contests through it.</p>
<p>You can solve problems in different categories on this website, and they also offer you a nice profile page. They also provide rankings based on your performance in the programming contests.</p>
<p>If you are a complete beginner in problem solving, then this website can help you a lot in starting your problem solving journey.</p>
<h2 id="heading-16-lightojhttpslightojcom">16. <a target="_blank" href="https://lightoj.com/">LightOJ</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/anla94vgv2zsjw4a4woy.png" alt="LightOJ banner image" width="600" height="400" loading="lazy"></p>
<p>In LightOJ, you can solve a lot of categorized problems. It is highly based on solving algorithmic problems. Their problems are categorized as below:</p>
<ul>
<li>LightOJ Volumes</li>
<li>Warm-Up</li>
<li>Advanced Search Techniques</li>
<li>Database</li>
<li>Data Structures</li>
<li>Divide And Conquer</li>
<li>Dynamic Programming</li>
<li>Fast Fourier Transform</li>
<li>Flow/Matching</li>
<li>Game Theory</li>
<li>Geometry</li>
<li>Graph Theory</li>
<li>Greedy</li>
<li>Math</li>
<li>Matrix</li>
<li>Parsing/Grammar</li>
<li>Recursion/Branch and Bound</li>
<li>String</li>
</ul>
<p>They also provide you with a nice profile page where you can see your activities. It might seem odd, but sometimes I find this website better than LeetCode in some cases. Moreover, everything you do on this website is completely free of cost!</p>
<h2 id="heading-17-exercismhttpsexercismorg">17. <a target="_blank" href="https://exercism.org/">Exercism</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/mik6ovwsb4vsej25gtfg.png" alt="Exercism banner image" width="600" height="400" loading="lazy"></p>
<p>You can develop your programming fluency in 57 different programming languages with their unique blend of learning, practice and mentoring. </p>
<p>Exercism is completely free of cost, and it's built by people like us. You can also contribute or donate to them to support their amazing service for free.</p>
<p>They also provide a very nice user profile page which also shows everything you have done on their website, starting from publishing to maintaining.</p>
<p>On their <a target="_blank" href="https://exercism.org/tracks">tracks</a> page, you will get a list of 57 different programming languages where you can start your practice. </p>
<p>Solving problems on their website seems super fun to me. I really liked the way they manage their website.</p>
<h2 id="heading-18-online-judgehttpsonlinejudgeorg-commonly-known-as-uva">18. <a target="_blank" href="https://onlinejudge.org/">Online Judge</a> (Commonly known as UVa)</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/fat4pnmszr5xo5yqus73.png" alt="Online Judge banner image" width="600" height="400" loading="lazy"></p>
<p>This is one of the oldest websites out there for solving programming-related problems. I still find it to be a very hard website for beginners. The UI and navigation of the website are also very old. </p>
<p>All of the questions come with a PDF here. You need to download the PDF file of the problem if you want to solve problems as they do not offer a direct preview of the questions.</p>
<p>They have a lot of problemsets on their <a target="_blank" href="https://onlinejudge.org/index.php?option=com_onlinejudge&amp;Itemid=8">website</a>. I still find a lot of users using this website nowadays. Therefore, I mentioned it here.</p>
<h2 id="heading-19-hackerearthhttpswwwhackerearthcom">19. <a target="_blank" href="https://www.hackerearth.com/">HackerEarth</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/xm0bhrc4ephex78tddj5.png" alt="HackerEarth banner image" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>HackerEarth is an Indian software company headquartered in San Francisco, US, that provides enterprise software that helps organisations with their technical hiring needs. HackerEarth is used by organizations for technical skill assessment and remote video interviewing.</p>
</blockquote>
<p>You can practice your problem solving skills from their <a target="_blank" href="https://www.hackerearth.com/practice/">practice</a> page. Also, you can participate in programming challenges and hackathons from their <a target="_blank" href="https://www.hackerearth.com/challenges/">challenges</a> page.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/fj62qgttmbqgatvcbdzt.png" alt="HackerEarth challenges page" width="600" height="400" loading="lazy"></p>
<p>Their <a target="_blank" href="https://www.hackerearth.com/practice/interviews/">interview prep</a> section is quite amazing. You can take part in the mock assessments for the Adobe Coding Test, Facebook Coding Test, and Amazon Coding Test.</p>
<p>They also provide a nice user profile for everyone.</p>
<h2 id="heading-20-code-jam-googles-coding-competitionshttpscodingcompetitionswithgooglecomcodejam">20. <a target="_blank" href="https://codingcompetitions.withgoogle.com/codejam">Code Jam - Google's Coding Competitions</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/m8l89xfpsqt1yak0d94c.png" alt="Code Jam banner image" width="600" height="400" loading="lazy"></p>
<blockquote>
<p>Google Code Jam is an international programming competition hosted and administered by Google. The competition began in 2003. The competition consists of a set of algorithmic problems which must be solved in a fixed amount of time.</p>
</blockquote>
<p>If you are interested in taking part in the Code Jam contests, then their <a target="_blank" href="https://codingcompetitions.withgoogle.com/codejam/archive">archive section</a> is full of amazing resources for you where you can get the earlier questions and practice them. </p>
<p>They also offer a lot of prize money in their contests. An example can be:</p>
<blockquote>
<p>Out of thousands of participants, only the top 25 will head to the World Finals to compete for the title of World Champion and cash prizes of up to $15,000. And there will be plenty of other prizes to go around — the top 1,000 competitors will win an exclusive Code Jam 2022 t-shirt.</p>
</blockquote>
<h2 id="heading-21-icpchttpsicpcglobal-international-collegiate-programming-contest">21. <a target="_blank" href="https://icpc.global/">ICPC</a> - International Collegiate Programming Contest</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/m8w6ezori7cpgiytzxmi.png" alt="ICPC banner image" width="600" height="400" loading="lazy"></p>
<p>ICPC is one of the most prestigious programming contests in the world.</p>
<blockquote>
<p>The International Collegiate Programming Contest, known as the ICPC, is an annual multi-tiered competitive programming competition among the universities of the world.</p>
</blockquote>
<p>Who is eligible for ICPC?</p>
<blockquote>
<p>ACM/ICPC is a team-based competition with certain requirements to the participants: only post-secondary students and first-year post-graduate students no older than 24 are eligible; each team consists of three members. One can participate in the finals no more than twice and in the regionals no more than five times.</p>
</blockquote>
<h1 id="heading-personal-opinion">Personal Opinion</h1>
<p>If you are a complete beginner, then start with <a class="post-section-overview" href="#1beecrowdformerlyuri">beecrowd</a>. If you want to start problem solving along with learning a specific programming language, then start with <a class="post-section-overview" href="#heading-2-hackerrank-2">HackerRank</a>. </p>
<p>After solving almost 50+ problems on beecrowd or HackerRank, start solving problems on <a class="post-section-overview" href="#heading-3-codeforces-1">Codeforces</a>. The first time, you won't be able to do that well in the programming contests on Codeforces, and that is completely okay – it is natural. You just need to try regularly. The questions might seem pretty hard to you, but it'll become easier day by day after solving problems continuously. </p>
<p>You can participate in <a class="post-section-overview" href="#7atcoder">AtCoder</a> the day you start solving problems on Codeforces. You can also try <a class="post-section-overview" href="#heading-6-codechef-1">CodeChef</a>, but I find Codeforces is enough in this case. </p>
<p>This will prepare you for the <a class="post-section-overview" href="#21icpcinternationalcollegiateprogrammingcontest">ICPC</a> and <a class="post-section-overview" href="#heading-20-code-jam-googles-coding-competitions-1">Code Jam</a>. Don't forget to solve the earlier questions on Code Jam.</p>
<p>If you want to gain expertise in Data Science, then simply go for <a class="post-section-overview" href="#heading-5-kaggle-1">Kaggle</a>.</p>
<p>If you want to gain expertise in Algorithms, then <a class="post-section-overview" href="#4leetcode">LeetCode</a>, and <a class="post-section-overview" href="#16lightoj">LightOJ</a> are your only places. <a class="post-section-overview" href="#heading-14-geeksforgeeks-popularly-known-as-gfg-1">GeeksforGeeoks</a> will also help you in this aspect. </p>
<p>For LeetCode, get some help from <a target="_blank" href="https://twitter.com/nicholaswwhite">Nick White</a>. His <a target="_blank" href="https://www.youtube.com/playlist?list=PLU_sdQYzUj2keVENTP0a5rdykRSgg9Wp-">LeetCode Solution</a> playlist has 189 videos as of today, and you will learn a lot from him, trust me! </p>
<p>Another good resource is <a target="_blank" href="https://neetcode.io/">Neetcode</a> where you can get curated problems and their solutions from LeetCode. The official <a target="_blank" href="https://www.youtube.com/c/NeetCode/featured">YouTube channel of Neetcode</a> is also a great channel.</p>
<h1 id="heading-additional-websites">Additional Websites</h1>
<p>You might find the websites below useful too!</p>
<h2 id="heading-stopstalkhttpswwwstopstalkcom">⭐ <a target="_blank" href="https://www.stopstalk.com/">StopStalk</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/6ixwem6zdmrn6bw29d32.png" alt="StopStalk banner image" width="600" height="400" loading="lazy"></p>
<p>This website retrieves your friends' recent submissions from various competitive websites (Such as Codeforces, SPOJ, HackerRank, Timus, and so on) and shows all of them in one place. You can check my StopStalk profile from <a target="_blank" href="https://www.stopstalk.com/user/profile/FBA">here</a>.</p>
<h2 id="heading-codersrankhttpscodersrankio">⭐ <a target="_blank" href="https://codersrank.io/">CodersRank</a></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/83l29mbplkwx2pf535bi.png" alt="CodersRank banner image" width="600" height="400" loading="lazy"></p>
<p>This is a platform made to help developers in job-seeking and professional growth. Here, your CodersRank profile serves as a proven track record of your coding knowledge. </p>
<p>You have to connect your private and public repositories here from GitHub to generate your true CodersRank profile. You can also check my CodersRank profile from <a target="_blank" href="https://profile.codersrank.io/user/fahimfba/">here</a>.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Thanks for reading the entire article. If it helps you then you can also check out other articles of mine at <a target="_blank" href="https://www.freecodecamp.org/news/author/fahimbinamin/">freeCodeCamp</a>.</p>
<p>If you want to get in touch with me, then you can do so using <a target="_blank" href="https://twitter.com/Fahim_FBA">Twitter</a>, <a target="_blank" href="https://www.linkedin.com/in/fahimfba/">LinkedIn</a>, and <a target="_blank" href="https://github.com/FahimFBA">GitHub</a>. </p>
<p>You can also <a target="_blank" href="https://www.youtube.com/@FahimAmin?sub_confirmation=1">SUBSCRIBE to my YouTube channel</a> (Code With FahimFBA) if you want to learn various kinds of programming languages with a lot of practical examples regularly.</p>
<p>If you want to check out my highlights, then you can do so at my <a target="_blank" href="https://www.polywork.com/fahimbinamin">Polywork timeline</a>.</p>
<p>You can also <a target="_blank" href="https://fahimbinamin.com/">visit my website</a> to learn more about me and what I'm working on.</p>
<p>Thanks a bunch!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React Interview Questions – Interview Prep with Answers and Examples ]]>
                </title>
                <description>
                    <![CDATA[ React is a JavaScript library for creating user interfaces. It's used in over 30,000 live websites and has over 70,000 GitHub stars. According to the 2021 Stack Overflow developer survey, React has surpassed jQuery as the most popular web framework, ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-interview-questions-and-answers/</link>
                <guid isPermaLink="false">66d45feca326133d12440a19</guid>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interviewing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Mon, 06 Jun 2022 21:55:16 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/cover-template.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>React is a JavaScript library for creating user interfaces. It's used in over 30,000 live websites and has over 70,000 GitHub stars.</p>
<p>According to the <a target="_blank" href="https://insights.stackoverflow.com/survey/2021#section-most-popular-technologies-web-frameworks">2021 Stack Overflow developer survey</a>, React has surpassed jQuery as the most popular web framework, and holds approximately 40.14% of the market share. React was also the most sought-after, with one out of every four developers using it.</p>
<p>Over 8,000 industry leaders, including LinkedIn, Twitter, and AirBnB, use React.</p>
<p>A React developer's average annual salary in the United States is $120,000. Many businesses and companies use React, which forces them to constantly look for new talent.</p>
<p>In this article, we will go over some React basics and then look at some interview questions and their proper answers to help you succeed in any React interview you may have.</p>
<h2 id="heading-what-is-react">What is React?</h2>
<p>React is an open-source front-end JavaScript library for creating user interfaces. It is declarative, efficient, and flexible, and it adheres to the component-based approach, which allows us to create reusable UI components.</p>
<p>Developer primarily use React to create Single Page Applications and the library focuses solely on the view layer of MVC. It is also extremely fast.</p>
<h2 id="heading-features-of-react">Features of React</h2>
<p>React has many features that set it apart, but here are a few highlights:</p>
<ul>
<li><p>React employs the Virtual DOM as opposed to a real/browser DOM.</p>
</li>
<li><p>React uses unidirectional one-way data binding.</p>
</li>
<li><p>It is used to develop web applications as well as mobile applications using <a target="_blank" href="https://reactnative.dev/">React Native</a>, which allows us to build cross-platform applications.</p>
</li>
</ul>
<h2 id="heading-how-to-start-a-new-project-in-react">How to Start a New Project in React</h2>
<p>We can create a React app from scratch by initalizing a project and installing all dependencies. But the easiest way is by using <a target="_blank" href="https://reactjs.org/docs/create-a-new-react-app.html#create-react-app">create-react-app</a> via the command below:</p>
<pre><code class="lang-bash">npx create-react-app my-app
</code></pre>
<p><strong>Note:</strong> my-app is the name of the application we are creating, but you can change it to any name of your choice.</p>
<p>You can read more on how to <a target="_blank" href="https://www.freecodecamp.org/news/get-started-with-react-for-beginners/">get started with React in this article</a>.</p>
<h2 id="heading-what-does-dom-stand-for">What Does DOM Stand For?</h2>
<p>The term "DOM" stands for <strong>D</strong>ocument <strong>O</strong>bject <strong>M</strong>odel and refers to the representation of the entire user interface of a web application as a tree data structure.</p>
<h3 id="heading-types-of-dom">Types of DOM</h3>
<p>We have two types of DOM which are the Virual DOM and the Real DOM.</p>
<h2 id="heading-advantages-and-disadvantages-of-react">Advantages and Disadvantages of React</h2>
<p>Here are some of the advantages and disadvantages of React:</p>
<h3 id="heading-advantages-of-react">Advantages of React</h3>
<ol>
<li><p>It has a shorter learning curve for JavaScript developers and a large number of manuals, tutorials, and training materials are available because of its active community.</p>
</li>
<li><p>React is search engine friendly</p>
</li>
<li><p>It makes it easier to create rich UI and custom components.</p>
</li>
<li><p>React has quick rendering</p>
</li>
<li><p>The use of JSX allows us to write code that is simpler, more appealing, and easier to understand.</p>
</li>
</ol>
<h3 id="heading-disadvantages-of-react">Disadvantages of React</h3>
<ol>
<li><p>Because React is a frontend library, other languages and libraries are required to build a complete application.</p>
</li>
<li><p>It can be difficult for inexperienced programmers to understand because it employs JSX.</p>
</li>
<li><p>Existing documentation is quickly out of date due to the short development cycles.</p>
</li>
</ol>
<h2 id="heading-what-is-jsx">What is JSX?</h2>
<p>JavaScript XML is abbreviated as JSX. JSX enables and simplifies the creation of HTML in React, resulting in more readable and understandable markup.</p>
<p>For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>You can read more about <a target="_blank" href="https://www.freecodecamp.org/news/jsx-in-react-introduction/">JSX in React in this article</a>.</p>
<h2 id="heading-why-cant-browsers-read-jsx">Why can't Browsers Read JSX?</h2>
<p>JSX is not a valid JavaScript code, and there is no built-in implementation that allows the browser to read and understand it. We need to transpile the code from JSX into valid JavaScript code that the browser can understand, and we use <a target="_blank" href="https://babeljs.io/">Babel</a>, a JavaScript compiler/transpiler, to accomplish this.</p>
<p>Note: <a target="_blank" href="https://github.com/facebook/create-react-app">create-react-app</a> uses Babel internally for the JSX to JavaScript conversion, but you can also set up your own babel configuration using Webpack.</p>
<p>You can read more about <a target="_blank" href="https://www.freecodecamp.org/news/jsx-in-react-introduction/">JSX in React in this article</a>.</p>
<h2 id="heading-what-are-components">What are Components?</h2>
<p>A component is a self-contained, reusable code block that divides the user interface into smaller pieces rather than building the entire UI in a single file.</p>
<p>There are two kinds of components in React: functional and class components.</p>
<h3 id="heading-what-is-a-class-component">What is a Class Component?</h3>
<p>Class components are ES6 classes that return JSX and necessitate the use of React extensions. Because it was not possible to use state inside functional components in earlier versions of React (16.8), functional components were only used for rendering UI.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
  }
}
</code></pre>
<p>Read more about React <a target="_blank" href="https://www.freecodecamp.org/news/react-components-jsx-props-for-beginners/">components and the types of components</a> in this article.</p>
<h3 id="heading-what-is-a-functional-component">What is a Functional Component?</h3>
<p>A JavaScript/ES6 function that returns a React element is referred to as a functional component (JSX).</p>
<p>Since the introduction of React Hooks, we have been able to use states in functional components, which has led to many people adopting them due to their cleaner syntax.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>Read more about React <a target="_blank" href="https://www.freecodecamp.org/news/react-components-jsx-props-for-beginners/">components and the types of components</a> in this article.</p>
<h3 id="heading-difference-between-functional-and-class-components">Difference between Functional and Class components</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Functional Components</strong></td><td><strong>Class Components</strong></td></tr>
</thead>
<tbody>
<tr>
<td>A functional component is a JavaScript/ES6 function that takes an argument, props, and returns JSX.</td><td>You must extend from React in order to use a class component. Create a component and a render function that returns a React element.</td></tr>
<tr>
<td>There is no render method used in functional components.</td><td>It must have the render() method returning JSX</td></tr>
<tr>
<td>Functional components run from top to bottom and cannot be kept alive once the function is returned.</td><td>The class component is instantiated, and various life cycle methods are kept alive and are run and invoked depending on the phase of the class component.</td></tr>
<tr>
<td>They are also known as stateless components because they only accept data and display it in some form, and they are primarily responsible for UI rendering.</td><td>They are also referred to as Stateful components because they implement logic and state.</td></tr>
<tr>
<td>React lifecycle methods cannot be used in functional components.</td><td>React lifecycle methods can be used inside class components.</td></tr>
<tr>
<td>Hooks like useState() were created to be used in functional components to make them Stateful.</td><td>It requires different syntax inside a class component to implement hooks.</td></tr>
<tr>
<td>Constructors are not used.</td><td>Constructor are used as it needs to store state.</td></tr>
</tbody>
</table>
</div><h2 id="heading-how-to-use-css-in-react">How to Use CSS in React</h2>
<p>There are 3 ways to style a react application with CSS:</p>
<ul>
<li><p>Inline Styles</p>
</li>
<li><p>External Styling</p>
</li>
<li><p>CSS in JS</p>
</li>
</ul>
<p>Read more on <a target="_blank" href="https://www.freecodecamp.org/news/how-to-style-react-apps-with-css/">how to style a React application in this article</a>.</p>
<h2 id="heading-what-is-the-use-of-render-in-react">What is the Use of render() in React?</h2>
<p><code>Render()</code> is used in the class component to return the HTML that will be displayed in the component. It is used to read props and state and return our JSX code to our app's root component.</p>
<h2 id="heading-what-are-props">What are Props?</h2>
<p>Props are also referred to as properties. They are used to transfer data from one component to the next (parent component to child component). They are typically used to render dynamically generated data.</p>
<p>Note: A child component can never send props to a parent component since this flow is unidirectional (parent to child).</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params">{name, hobby}</span>) </span>{
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My name is {name}.<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>My hobby is {hobby}.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>Read more about <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-props-in-react/">how props works in React here</a>.</p>
<h2 id="heading-what-is-state-in-react">What is State in React?</h2>
<p>State is a built-in React Object that is used to create and manage data within our components. It differs from props in that it is used to store data rather than pass data.</p>
<p>State is mutable (data can change) and accessible through <code>this.state()</code>.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-built_in">super</span>(props);
    <span class="hljs-built_in">this</span>.state = {
      <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>
    };
  }

  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My name is {this.state.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}
</code></pre>
<h2 id="heading-how-to-update-the-state-of-a-component-in-react">How to Update the State of a Component in React</h2>
<p>It is important to know that when we update a state directly it won’t re-render the component – meaning we don’t get to see the update.</p>
<p>If we want it to re-render, then we have to use the <code>setState()</code> method which updates the component’s state object and re-reders the component.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-built_in">super</span>(props);
    <span class="hljs-built_in">this</span>.state = {
      <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>
    };
  }
  changeName = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">this</span>.setState({<span class="hljs-attr">name</span>: <span class="hljs-string">"Jane Doe"</span>});
  }
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My {this.state.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span>
          <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.changeName}</span>
        &gt;</span>Change Name<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}
</code></pre>
<p>You can learn more <a target="_blank" href="https://www.freecodecamp.org/news/react-js-for-beginners-props-state-explained/">here</a>.</p>
<h2 id="heading-how-to-differentiate-between-state-and-props">How to Differentiate Between State and Props</h2>
<p>State and props are JavaScript objects with distinct functions.</p>
<p>Props are used to transfer data from the parent component to the child component, whereas state is a local data storage that is only available to the component and cannot be shared with other components.</p>
<h2 id="heading-what-is-an-event-in-react">What is an Event in React?</h2>
<p>In React, an event is an action that can be triggered by a user action or a system generated event. Mouse clicks, web page loading, key press, window resizes, scrolls, and other interactions are examples of events.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// For class component</span>
&lt;button type=<span class="hljs-string">"button"</span> onClick={<span class="hljs-built_in">this</span>.changeName} &gt;Change Name&lt;/button&gt;

<span class="hljs-comment">// For function component</span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{changeName}</span> &gt;</span>Change Name<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
</code></pre>
<h2 id="heading-how-to-handle-events-in-react">How to Handle Events in React</h2>
<p>Events in React are handled similarly to DOM elements. One difference we must consider is the naming of our events, which are named in camelCase rather than lowercase.</p>
<p>Example:</p>
<h3 id="heading-class-component">Class Component</h3>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-built_in">super</span>(props);
    <span class="hljs-built_in">this</span>.handleClick = <span class="hljs-built_in">this</span>.handleClick.bind(<span class="hljs-built_in">this</span>);
  }
  handleClick() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'This button was Clicked'</span>);
  }
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.handleClick}</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
   );
  }
}
</code></pre>
<h3 id="heading-function-component">Function Component</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Click happened'</span>);
   };
   <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
   );
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h2 id="heading-how-to-pass-parameters-to-an-event-handler">How to Pass Parameters to an Event Handler</h2>
<p>In functional components, we can do this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My name is <span class="hljs-subst">${name}</span>`</span>);
   };
   <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> handleClick('John Doe')}&gt;Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
   );
};
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>And in class components we can do this:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  call(name) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My name is <span class="hljs-subst">${name}</span>`</span>);
  }
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>= <span class="hljs-string">{this.call.bind(this,</span>"<span class="hljs-attr">John</span> <span class="hljs-attr">Doe</span>")}&gt;</span>
        Click the button!
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
    );
  }
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h2 id="heading-what-is-redux">What is Redux?</h2>
<p>Redux is a popular open-source JavaScript library for managing and centralizing application state. It is commonly used with React or any other view-library.</p>
<p>Learn more about <a target="_blank" href="https://www.freecodecamp.org/news/redux-tutorial-for-beginners/#:~:text=Redux%20is%20a%20popular%20open,you%20how%20to%20use%20Redux.">redux here</a>.</p>
<h2 id="heading-what-are-react-hooks">What are React Hooks?</h2>
<p>React hooks were added in v16.8 to allow us to use state and other React features without having to write a class.</p>
<p>They do not operate within classes, but rather assist us in hooking into React state and lifecycle features from function components.</p>
<h3 id="heading-when-did-we-begin-to-use-hooks-in-react">When Did We Begin to Use Hooks in React?</h3>
<p>The React team first introduced React Hooks to the world in late October 2018, during React Conf, and then in early February 2019, with React v16. 8.0.</p>
<h2 id="heading-explain-the-usestate-hook">Explain the useState() Hook</h2>
<p>The useState Hook is a store that enables the use of state variables in functional components. You can pass the initial state to this function, and it will return a variable containing the current state value (not necessarily the initial state) and another function to update this value.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      // ...
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-explain-the-useeffect-hook">Explain the useEffect() Hook</h2>
<p>The useEffect Hook allows you to perform side effects in your components like data fetching, direct DOM updates, timers like setTimeout(), and much more.</p>
<p>This hook accepts two arguments: the callback and the dependencies, which allow you to control when the side effect is executed.</p>
<p>Note: The second argument is optional.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, {useState, useEffect} <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [loading, setLoading] = useState(<span class="hljs-literal">false</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    setLoading(<span class="hljs-literal">true</span>);
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      setLoading(<span class="hljs-literal">false</span>);
    }, <span class="hljs-number">2000</span>);
  }, []);

  <span class="hljs-keyword">return</span>(
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      // ...
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h2 id="heading-whats-the-use-of-the-usememo-hook">What's the Use of the useMemo() Hook?</h2>
<p>The <code>useMemo()</code> hook is used in functional components to memoize expensive functions so that they are only called when a set input changes rather than every render.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> result = useMemo(<span class="hljs-function">() =&gt;</span> expensivesunction(input), [input]);
</code></pre>
<p>This is similar to the useCallback hook, which is used to optimize the rendering behavior of your React function components. useMemo is used to memoize expensive functions so that they do not have to be called on every render.</p>
<h2 id="heading-what-is-the-userefs-hook">What Is the useRefs Hook?</h2>
<p>The <code>useRefs()</code> hook, also known as the References hook, is used to store mutable values that do not require re-rendering when they are updated. It is also used to store a reference to a specific React element or component, which is useful when we need DOM measurements or to directly add methods to the components.</p>
<p>When we need to do the following, we use useRefs:</p>
<ul>
<li><p>Adjust the focus, and choose between text and media playback.</p>
</li>
<li><p>Work with third-party DOM libraries.</p>
</li>
<li><p>Initiate imperative animations</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, {useEffect, useRef} <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> inputRef = useRef(<span class="hljs-literal">null</span>)

  useEffect(<span class="hljs-function">()=&gt;</span>{
    inputElRef.current.focus()
  }, [])

  <span class="hljs-keyword">return</span>(
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputRef}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h2 id="heading-what-are-custom-hooks">What are Custom Hooks?</h2>
<p>Custom Hooks are a JavaScript function that you write to allow you to share logic across multiple components, which was previously impossible with React components.</p>
<p>If you're interested in learning how this works, here is a <a target="_blank" href="https://www.freecodecamp.org/news/how-to-create-react-hooks/">step by step guide to help you build your own Custom React Hook</a>.</p>
<h2 id="heading-what-is-context-in-react">What is Context in React?</h2>
<p>Context is intended to share "global" data for a tree of React components by allowing data to be passed down and used (consumed) in whatever component we require in our React app without the use of props. It allows us to share data (state) more easily across our components.</p>
<p>Read more about <a target="_blank" href="https://www.freecodecamp.org/news/react-context-for-beginners/">React Context in this guide</a>.</p>
<h2 id="heading-what-is-react-router">What is React Router?</h2>
<p>React router is a standard library used in React applications to handle routing and allow navigation between views of various components.</p>
<p>Installing this library into your React project is as simple as typing the following command into your terminal:</p>
<pre><code class="lang-bash">npm install – -save react-router-dom
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, we went over some React interview questions to help you prepare for your interviews. All of us at FreeCodeCamp wish you the best of luck and success in your interview.</p>
<p>Instead of attempting to take several courses at once, find a helpful tutorial and complete it if you want to learn more and master React so you can perform well in practical interview sessions. Check out freeCodeCamp's <a target="_blank" href="https://www.freecodecamp.org/news/free-react-course-2022/">Free React Course for 2022</a> or <a target="_blank" href="https://www.freecodecamp.org/news/learn-react-course/">Learn React - Full Course for Beginners</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Program to Print the Fibonacci Sequence ]]>
                </title>
                <description>
                    <![CDATA[ By Sonia Jessica  Questions about the Fibonacci Series are some of the most commonly asked in Python interviews.  In this article, I'll explain a step-by-step approach on how to print the Fibonacci sequence using two different techniques, iteration a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-program-to-print-the-fibonacci-sequence/</link>
                <guid isPermaLink="false">66d461493a8352b6c5a2ab15</guid>
                
                    <category>
                        <![CDATA[ algorithms ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 27 Apr 2022 00:34:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/pexels-jeff-wang-462402.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Sonia Jessica </p>
<p>Questions about the Fibonacci Series are some of the most commonly asked in Python interviews. </p>
<p>In this article, I'll explain a step-by-step approach on how to print the Fibonacci sequence using two different techniques, iteration and recursion. </p>
<p>Before we begin, let's first understand some basic terminology.</p>
<h2 id="heading-what-is-the-fibonacci-sequence">What is the Fibonacci Sequence?</h2>
<p>The <a target="_blank" href="https://en.wikipedia.org/wiki/Fibonacci_number">Fibonacci Sequence</a> is a sequence of numbers in which a given number is the result of adding the 2 numbers that come before it. And adding the previous 2 numbers some number of times forms a series that we call the Fibonacci Series.</p>
<p>The Fibonacci sequence starts with two numbers, that is 0 and 1. Then every following number is made up of adding the previous two numbers together.</p>
<p>For example, take 0 and 1. They're the first two numbers in the sequence. If you add them together, you get 1. So the sequence starts 0, 1, 1,...</p>
<p>Then, to find the next number, you add the last number you have and the number before it. So 1+1 = 2. So the sequence so far is 0, 1, 1, 2, ... Make sense?</p>
<p>We can represent this more mathematically like 0, 1, (1) - [0 + 1]. Similarly, the next Fibonacci number is - 0, 1, 1, (2) - [1 + 1]. And so on. Here's a diagram showing the first 10 Fibonacci numbers:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/Fibonacci-series.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is an example of a Fibonacci series – <strong>0, 1, 1, 2, 3, 5, 8, 13, 21,</strong> <strong>34</strong>. Within this continuous sequence, every individual number is a Fibonacci number. </p>
<p>Mathematically, the Fibonacci Sequence is represented by this formula: </p>
<p><strong>F(n) = F(n-1) + F(n-2)</strong>, where <strong>n &gt; 1</strong>. </p>
<p>We can use this sequence to find any nth Fibonacci number. </p>
<p>This fascinating sequence is widely associated with the mathematician Leonardo Pisano, also known as Fibonacci. He was from the Republic of Pisa, which is why he is also known as Leonardo of Pisa. </p>
<p>Leonardo was known as one of the most talented mathematicians of the middle ages.</p>
<h2 id="heading-how-to-print-the-fibonacci-sequence-in-python">How to Print the Fibonacci Sequence in Python</h2>
<p>You can write a computer program for printing the Fibonacci sequence in 2 different ways:</p>
<ul>
<li>Iteratively, and</li>
<li>Recursively.</li>
</ul>
<p>Iteration means repeating the work until the specified condition is met. Recursion, on the other hand, means performing a single task and proceeding to the next for performing the remaining task. </p>
<h3 id="heading-heres-an-iterative-algorithm-for-printing-the-fibonacci-sequence">Here's an iterative algorithm for printing the Fibonacci sequence:</h3>
<ol>
<li>Create 2 variables and initialize them with 0 and 1 (first = 0, second = 1)</li>
<li>Create another variable to keep track of the length of the Fibonacci sequence to be printed (length)</li>
<li>Loop (length is less than series length)</li>
<li>Print <strong>first + second</strong></li>
<li>Update <strong>first</strong> and <strong>second</strong> variable (first will point to the second, and the second will point to first + second)</li>
<li>Decrement the length variable and repeat from step 3</li>
<li>Once the loop terminates, terminate the program</li>
</ol>
<h3 id="heading-how-the-iterative-algorithm-works">How the iterative algorithm works:</h3>
<p>Consider that we need to print a Fibonacci sequence of length 7. Then the flow of the algorithm will be like this:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Iterations</td><td>Steps Explained</td><td>Output</td></tr>
</thead>
<tbody>
<tr>
<td>Initial</td><td>First = 0, Second = 1</td><td>[0, 1]</td></tr>
<tr>
<td>1</td><td>Print (first + second) = [0+1] Now variable <code>first</code> will point to variable <code>second</code>. And second will point to the next Fibonacci number that we calculated above.</td><td>[0, 1, 1]</td></tr>
<tr>
<td>2</td><td>Print (first + second) = [1+1] Now variable first will point to variable second. And second will point to the next Fibonacci number that we calculated above.</td><td>[0, 1, 1, 2]</td></tr>
<tr>
<td>3</td><td>Print (first + second) = [1+2] Now variable first will point to variable second. And second will point to the next Fibonacci number that we calculated above.</td><td>[0, 1, 1, 2, 3]</td></tr>
<tr>
<td>4</td><td>Print (first + second) = [2+3] Now variable first will point to variable second. And second will point to the next Fibonacci number that we calculatod above.</td><td>[0, 1, 1, 2, 3, 5]</td></tr>
<tr>
<td>5</td><td>Print (first + second) = [3+5] Now variable first will point to variable second. And second will point to the next Fibonacci number that we calculated above.</td><td>[0, 1, 1, 2, 3, 5, 8]</td></tr>
</tbody>
</table>
</div><p>So the final Fibonacci sequence for length 7 will be  <strong>[0, 1, 1, 2, 3, 5, 8]</strong>.</p>
<h3 id="heading-iterative-python-code-for-printing-fibonacci-sequence">Iterative Python Code for printing Fibonacci Sequence:</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">PrintFibonacci</span>(<span class="hljs-params">length</span>):</span>
    <span class="hljs-comment">#Initial variable for the base case. </span>
    first = <span class="hljs-number">0</span>
    second = <span class="hljs-number">1</span>

    <span class="hljs-comment">#Printing the initial Fibonacci number.</span>
    print(first, second, end=<span class="hljs-string">" "</span>)

    <span class="hljs-comment">#decreasing the length by two because the first 2 Fibonacci numbers </span>
    <span class="hljs-comment">#already printed.</span>
    length -= <span class="hljs-number">2</span>

    <span class="hljs-comment">#Loop until the length becomes 0.</span>
    <span class="hljs-keyword">while</span> length &gt; <span class="hljs-number">0</span>:

        <span class="hljs-comment">#Printing the next Fibonacci number.</span>
        print(first + second, end=<span class="hljs-string">" "</span>)

        <span class="hljs-comment">#Updating the first and second variables for finding the next number. </span>
        temp = second
        second = first + second
        first = temp

        <span class="hljs-comment">#Decreasing the length that states the Fibonacci numbers to be </span>
        <span class="hljs-comment">#printed more.</span>
        length -= <span class="hljs-number">1</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    print(<span class="hljs-string">"Fibonacci Series - "</span>)
    PrintFibonacci(<span class="hljs-number">7</span>)
    <span class="hljs-keyword">pass</span>
</code></pre>
<p><a target="_blank" href="https://www.interviewbit.com/snippet/242ec6ca5cec8a2fcaf6/">Output</a> for length 7:</p>
<pre><code class="lang-python">Fibonacci Series - 
<span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">2</span> <span class="hljs-number">3</span> <span class="hljs-number">5</span> <span class="hljs-number">8</span>
</code></pre>
<p><strong>Explanation of the Code:</strong></p>
<p>In the above code, first we have defined a function that will print the Fibonacci series. It accepts a parameter for the length, and the function needs to print the Fibonacci series.</p>
<p>Next, we have created 2 variables that contain the initial 2 Fibonacci values, that is 0 and 1.</p>
<p>Then we printed the first 2 values [0, 1] and decremented the length by 2, because 2 values were already been printed.</p>
<p>We will run a loop for the remaining length time, and each time print the next Fibonacci value by adding the previous 2 terms that are stored in the first and second variables (that we created initially to keep track of the previous 2 values).</p>
<p>Update the first and second values that will point to the previous 2 values [first = second, and second = previous first + second].</p>
<p>The loop will run until the length becomes 0, which states that the required length of the Fibonacci sequence is printed.</p>
<p>Then we call the function defined for printing Fibonacci from the main function by passing the argument of the required length to be printed. And there you have it!</p>
<p>There is another approach for printing the Fibonacci sequence using the help of recursion. So let’s understand that approach, too.</p>
<h3 id="heading-recursive-algorithm-for-printing-the-fibonacci-sequence">Recursive Algorithm for printing the Fibonacci Sequence:</h3>
<ul>
<li>Accept the value of the previous first and second Fibonacci number as the length to be printed.</li>
<li>Check if the length is 0 then terminate the function call.</li>
<li>Print the Fibonacci value by adding the previous 2 values received in the parameter of the function (first and second).</li>
<li>Recursively call the function for the updated value of the first and second, as well as the decreased value of length.</li>
</ul>
<p>For this recursive function call, we need to pass the initial value of Fibonacci, that is (0 and 1), in the first and second variables.</p>
<p>To help you understand this algorithm better, let’s see the Python implementation of the algorithms. Then we'll look at an example so you can see how this recursive algorithm works.</p>
<h3 id="heading-recursive-python-code-for-printing-the-fibonacci-sequence">Recursive Python Code for Printing the Fibonacci Sequence:</h3>
<pre><code>def PrintFibonacci(first, second, length):

    #Stop the printing and recursive calling <span class="hljs-keyword">if</span> length reaches 
    #the end.
    if(length == <span class="hljs-number">0</span>):
        <span class="hljs-keyword">return</span>

    #Printng the next Fibonacci number.
    print(first + second, end=<span class="hljs-string">" "</span>)

    #Recursively calling the <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">by</span> <span class="hljs-title">updating</span> <span class="hljs-title">the</span> <span class="hljs-title">value</span> <span class="hljs-title">and</span> 
    #<span class="hljs-title">decrementing</span> <span class="hljs-title">the</span> <span class="hljs-title">length</span>.
    <span class="hljs-title">PrintFibonacci</span>(<span class="hljs-params">second, first+second, length<span class="hljs-number">-1</span></span>)

<span class="hljs-title">if</span> <span class="hljs-title">__name__</span> == "<span class="hljs-title">__main__</span>":
    #<span class="hljs-title">Print</span> <span class="hljs-title">initial</span> 2 <span class="hljs-title">values</span>.
    <span class="hljs-title">print</span>(<span class="hljs-params"><span class="hljs-number">0</span>,<span class="hljs-number">1</span>,end=<span class="hljs-string">" "</span></span>)

    #<span class="hljs-title">Calling</span> <span class="hljs-title">the</span> <span class="hljs-title">Function</span> <span class="hljs-title">to</span> <span class="hljs-title">print</span> <span class="hljs-title">the</span> <span class="hljs-title">remaining</span> <span class="hljs-title">length</span> 
    #<span class="hljs-title">fibonacci</span> <span class="hljs-title">series</span>
    <span class="hljs-title">PrintFibonacci</span>(<span class="hljs-params"><span class="hljs-number">0</span>,<span class="hljs-number">1</span>,<span class="hljs-number">7</span><span class="hljs-number">-2</span></span>)</span>
</code></pre><p><a target="_blank" href="https://www.interviewbit.com/snippet/1e85af84b1916aed890b/">Output</a>:</p>
<pre><code class="lang-python">For Length <span class="hljs-number">7</span> 
<span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">2</span> <span class="hljs-number">3</span> <span class="hljs-number">5</span> <span class="hljs-number">8</span>

For Length <span class="hljs-number">10</span>
<span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">2</span> <span class="hljs-number">3</span> <span class="hljs-number">5</span> <span class="hljs-number">8</span> <span class="hljs-number">13</span> <span class="hljs-number">21</span> <span class="hljs-number">34</span>
</code></pre>
<p><strong>Explanation of the code:</strong> </p>
<p>First, we created a function and perform recursion on it. In that function, we accepted the value of the previous 2 Fibonacci numbers to calculate the current Fibonacci number. And we have a length that keeps track of the base case.</p>
<p>For the base case of recursion, we are checking if the length reaches 0. If it does, then we will terminate the recursive call.</p>
<p>In other cases, we are printing the Fibonacci number by adding the previous 2 Fibonacci numbers. </p>
<p>And then we recursively call the function to print the next Fibonacci value by updating the previous 2 values and decrementing the length.</p>
<p>Now let’s visualize the recursive calls of this function with the help of a recursion tree. The length we want printed is 7.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/length-to-be-printed-is-7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Before the recursive call is made, the main function prints the initial 2 values, 0 and 1. And then it passes these values to the recursive function.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/main-function-prints-the-initial-2-values.-0-and-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The Recursive function is printing the value (0 + 1) and recursively calls with the next updated value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/Recursive-function-is-printing-the-value--0---1-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Then the recursive function is printing the value <strong>(1 + 1)</strong> and recursively calls with the next updated value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/printfibonacci-1-2-3-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now the recursive function is printing the value <strong>(1 + 2)</strong> and recursively calls with the next updated value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/printfibonacci-2-3-2-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And then the recursive function is printing the value <strong>(2 + 3)</strong> and recursively calls with the next updated value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/printfibonacci-3-5-1-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now the recursive function is printing the value <strong>(3 + 5)</strong> and recursively calls with the next updated value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/printfibonacci-5-8-0-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Finally, the last call is made. And the length is 0, so it will terminate the recursive call again and the series is printed on the console.</p>
<h2 id="heading-time-complexity-analysis">Time Complexity Analysis</h2>
<h3 id="heading-for-the-iterative-approach">For the Iterative Approach</h3>
<p>In the Iterative algorithm, we are looping until the length becomes 0. In the loop, we are performing a constant time operation of printing the value and updating the variables.  </p>
<p>If we consider that length to be n, then the time complexity will be <strong>O(n)</strong>. </p>
<h3 id="heading-for-the-recursive-approach">For the Recursive Approach</h3>
<p>In the recursive approach, we are calling recursive functions up to the given length number of times. We are also doing a simple constant operation of printing.</p>
<p> So in this also if we consider the length to be n numbers, then the time complexity will be <strong>O(n)</strong>.</p>
<h2 id="heading-space-complexity-analysis">Space Complexity Analysis</h2>
<h3 id="heading-for-iterative-approach">For Iterative Approach</h3>
<p>In the iterative approach we haven't taken the extra memory to accept the two variables that keeps track of the previous two Fibonacci numbers and the constant to any number of the series length. So the space complexity will be constant O(1).</p>
<h3 id="heading-for-the-recursive-approach-1">For the Recursive Approach</h3>
<p>In the recursive approach, we are calling the functions of the length number of times. We know that the recursion internally uses a call stack. </p>
<p>So if we consider that to be memory taken by the program, then the recursive call is made the length number of times. Then the space complexity will be O(n). </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The Fibonacci sequence is the series of numbers in which every number is the addition of its previous two numbers. </p>
<p>Fibonacci sequences are found not only in mathematics but all over the natural world – like in the petals of flowers, leaves or spines of a cactus, and so on. </p>
<p>It's also a commonly asked interview question – so it's good to know how it works.</p>
<p>I took inspiration from this post from <a target="_blank" href="https://www.interviewbit.com/python-interview-questions/">InterviewBit</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 10 React Interview Questions You Should Know in 2022 ]]>
                </title>
                <description>
                    <![CDATA[ Feel confident about your React knowledge? Put it to the test! I have selected all of the major questions you should know as a React developer in 2022, whether you are interviewing for a hired position or not. These questions cover everything from th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-interview-questions-to-know/</link>
                <guid isPermaLink="false">66d037c8dcd3a41034854bca</guid>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Job Interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reed ]]>
                </dc:creator>
                <pubDate>Tue, 22 Feb 2022 00:21:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/02/react-interview-questions-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Feel confident about your React knowledge? Put it to the test!</p>
<p>I have selected all of the major questions you should know as a React developer in 2022, whether you are interviewing for a hired position or not.</p>
<p>These questions cover everything from the core concepts of React to a practical understanding of when you should use certain features.</p>
<p>To get the best results out of this guide, make sure to try to answer each question yourself before looking at the answers.</p>
<p>Let's get started!</p>
<h2 id="heading-1-what-is-react-why-use-it">1. What is React? Why Use It?</h2>
<p>React is a JavaScript <strong>library</strong>, not a framework.</p>
<p>We use React because it gives us all the power of JavaScript, but with built-in features that improve the way we build and think about building applications.</p>
<ul>
<li>It gives us a way to <strong>easily create user interfaces</strong> with tools like JSX</li>
<li>It gives us components to easily <strong>share parts of our user interface (UI)</strong>, which static HTML itself cannot do</li>
<li>It allows us to <strong>create reusable behavior</strong> across any of our components with React hooks</li>
<li>React <strong>takes care of updating our UI</strong> when our data changes, without the need to update the DOM manually ourselves</li>
</ul>
<p><strong>Extra Credit</strong>: There are frameworks in React that give you everything you need to build an app (with little to no third-party libraries), like Next.js and Gatsby. </p>
<p>React was created for building single-page apps in particular, but you can make everything from static sites to mobile apps with the same React concepts.</p>
<h2 id="heading-2-what-is-jsx">2. What is JSX?</h2>
<p>JSX is a way of building React user interfaces that uses the simple syntax of HTML, but adds the functionality and dynamic nature of JavaScript.</p>
<p>In short, it is <strong>HTML + JavaScript for structuring our React apps</strong>.</p>
<p>Though JSX looks like HTML, under the hood it is actually <strong>JavaScript function calls</strong>.</p>
<p>If you write a <code>div</code> in JSX, it's actually the equivalent of calling <code>React.createElement()</code>.</p>
<p>We can build our user interfaces by manually calling <code>React.createElement</code>, but as we add more elements, it becomes harder and harder to read the structure we have built.</p>
<p><strong>The browser cannot understand JSX itself,</strong> so we often use a JavaScript compiler called <strong>Babel</strong> to convert what looks like HTML into JavaScript function calls that the browser can understand.</p>
<h2 id="heading-3-how-do-you-pass-data-to-react-components">3. How do you pass data to React components?</h2>
<p>There are 2 main ways of passing data to React components:</p>
<ol>
<li>Props</li>
<li>Context API</li>
</ol>
<p>Props are data passed from a component's immediate parent. Props are declared on the child component, can be named anything, and can accept any valid value.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Blog</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> post = { <span class="hljs-attr">title</span>: <span class="hljs-string">"My Blog Post!"</span> };

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">BlogPost</span> <span class="hljs-attr">post</span>=<span class="hljs-string">{post}</span> /&gt;</span></span>;
}
</code></pre>
<p>Props are consumed within the child component. Props are always available within the child as <strong>properties on an object</strong>.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BlogPost</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{props.post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre>
<p>Since props are plain object properties, they can be destructured for more immediate access.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BlogPost</span>(<span class="hljs-params">{ post }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre>
<p>Context is data passed from a context provider to any component that consumes the context.</p>
<p>Context allows us to access data anywhere in our app (if the provider is passed around the entire component tree), without using props.</p>
<p>Context data is passed down on the <code>value</code> prop using the <code>Context.Provider</code> component. It can be consumed using the Context.Consumer component or the <code>useContext</code> hook.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { createContext, useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> PostContext = createContext()

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> post = { <span class="hljs-attr">title</span>: <span class="hljs-string">"My Blog Post!"</span> };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">PostContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{post}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Blog</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">PostContext.Provider</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Blog</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">BlogPost</span> /&gt;</span></span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BlogPost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> post = useContext(PostContext)

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre>
<h2 id="heading-4-what-is-the-difference-between-state-and-props">4. What is the difference between state and props?</h2>
<p>States are <strong>values we can read and update</strong> in our React components.</p>
<p>Props are <strong>values that are passed to React components and are read only</strong> (they should not be updated).</p>
<p>You can think of props as being similar to arguments for a function that exist outside of our components, while state are values that change over time, but exist and are declared inside our components.</p>
<p>State and props are similar in that changes to them cause the components in which they exist to re-render.</p>
<h2 id="heading-5-what-are-react-fragments-used-for">5. What are React Fragments used for?</h2>
<p>React fragments are a special feature in React that let you write group children elements or components without creating an actual node in the DOM.</p>
<p>The fragment syntax looks like an empty set of tags <code>&lt;&gt;&lt;/&gt;</code> or are tags labeled <code>React.Fragment</code>.</p>
<p>In simpler terms, sometimes we need to put multiple React elements under a single parent, but we don't want to use a generic HTML element like a <code>div</code>.</p>
<p>If you are writing a table, for example, this would be invalid HTML:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Table</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">table</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Columns</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Columns</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Column 1<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Column 2<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>We could avoid this problem by using a fragment instead of a <code>div</code> element in our <code>Columns</code> component.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Columns</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Column 1<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Column 2<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
</code></pre>
<p>Another reason for choosing a fragment is that sometimes adding an additional HTML element may change the way our CSS styles are applied.</p>
<h2 id="heading-6-why-do-we-need-keys-for-react-lists">6. Why do we need keys for React lists?</h2>
<p>Keys are a unique value that we must pass to the <code>key</code> prop when we are using the <code>.map()</code> function to loop over an element or a component. </p>
<p>If we are mapping over an element, it would look like this:</p>
<pre><code class="lang-javascript">posts.map(<span class="hljs-function"><span class="hljs-params">post</span> =&gt;</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{post.id}</span>&gt;</span>{post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>)
</code></pre>
<p>Or like this if we are mapping over a component:</p>
<pre><code class="lang-javascript">posts.map(<span class="hljs-function"><span class="hljs-params">post</span> =&gt;</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{post.id}</span>&gt;</span>{post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>)
</code></pre>
<p>And in both case, we need to add a key that is a unique value, otherwise React will warn us.</p>
<p>Why? Because <strong>keys tell React which element or component is which in a list</strong>. </p>
<p>Otherwise, if we were to try to change items in this list by inserting more or editing them in some way, React wouldn’t know the order to put them in.</p>
<p>This is because React takes care of all of the business of updating the DOM for us (using a virtual DOM), but <strong>keys are necessary for React to update it properly</strong>.</p>
<h2 id="heading-7-what-is-a-ref-how-do-you-use-it">7. What is a ref? How do you use it?</h2>
<p>A ref is a <strong>reference to a DOM element</strong> in React.</p>
<p>Refs are created with the help of the <code>useRef</code> hook and can be immediately placed in a variable.</p>
<p>This variable is then passed to a given React element (not a component) to get a reference to the underlying DOM element (that is, div, span, and so on).</p>
<p>The element itself and its properties are now available on the <strong>.current property</strong> of the ref.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useRef } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> ref = useRef();

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(ref.current) <span class="hljs-comment">// reference to div element</span>
  }, [])

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{ref}</span> /&gt;</span></span>
}
</code></pre>
<p>Refs are often referred to as an "escape hatch" to be able to work with a DOM element directly. They allow us to do certain operations that can't be done through React otherwise, such as clearing or focusing an input.</p>
<h2 id="heading-8-what-is-the-useeffect-hook-used-for">8. What is the useEffect hook used for?</h2>
<p>The <code>useEffect</code> hook is used for performing side effects in our React components.</p>
<p><strong>Side effects</strong> are operations that are performed with the "outside world" or something that exists outside the context of our React app.</p>
<p>Some examples of side effects include making a GET or POST request to an external API endpoint or working with a browser API like <code>window.navigator</code> or <code>document.getElementById()</code>.</p>
<p>We cannot perform operations like these directly within the body of our React component. <code>useEffect</code> gives us a function within which to perform side effects and a dependencies array which lists any external values that the function relies upon.</p>
<p>If any value within the dependencies array changes, the effect function runs again.</p>
<h2 id="heading-9-when-do-you-use-react-context-vs-redux">9. When do you use React Context vs Redux?</h2>
<blockquote>
<p>Redux is probably the most commonly used third-party global state library for React, but you can replace the word "Redux" with any global state library for React.</p>
</blockquote>
<p>React context is a way to provide and consume data throughout our application <strong>without using props</strong>.</p>
<p>React context helps us prevent the problem of "<strong>props drilling</strong>", which is when you are passing data with props through components that don't need it.</p>
<p>Instead, with context we can <strong>consume the data exactly in the component that needs it</strong>.</p>
<p>While we only use Context to get or "read" values globally in our application, Redux and other third-party state libraries <strong>allow us to both read and update state</strong>.</p>
<p>Context is not a replacement for a third-party state library like Redux because <strong>it is not built for state updates</strong>. This is because any time the value provided on Context changes, all of its children will re-render, which can hurt performance.</p>
<h2 id="heading-10-what-are-the-usecallback-amp-usememo-hooks-used-for">10. What are the useCallback &amp; useMemo hooks used for?</h2>
<p>The <code>useCallback</code> and <code>useMemo</code> hooks exist to improve our components' performance.</p>
<p><code>useCallback</code> is to prevent functions that are declared within the body of function components from being recreated on every render.</p>
<p>This can lead to unnecessary performance issues, especially for callback functions that are passed down to child components.</p>
<p><code>useMemo</code>, on the other hand, memoizes an expensive operation that we give it.</p>
<p><strong>Memoization</strong> is a technical term for functions that are able to "remember" past values they have computed if their arguments have not changed. If so, the function returns the "remembered" value.</p>
<p>In other words, we may have a calculation that takes a significant amount of computing resources and we want it to be performed as sparingly as possible.</p>
<p>If that case, we use the <code>useMemo</code> hook, which differs from the <code>useCallback</code> hook in that it returns a value, not a function. </p>
<h2 id="heading-become-a-professional-react-developer">Become a Professional React Developer</h2>
<p>React is hard. You shouldn't have to figure it out yourself.</p>
<p>I've put everything I know about React into a single course, to help you reach your goals in record time:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><strong>Introducing: The React Bootcamp</strong></a></p>
<p><strong>It’s the one course I wish I had when I started learning React.</strong></p>
<p>Click below to try the React Bootcamp for yourself:</p>
<p><a target="_blank" href="https://www.thereactbootcamp.com"><img src="https://reedbarger.nyc3.digitaloceanspaces.com/reactbootcamp/react-bootcamp-cta-alt.png" alt="Click to join the React Bootcamp" width="600" height="400" loading="lazy"></a>
<em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ 10 Common Coding Interview Problems [Solved] ]]>
                </title>
                <description>
                    <![CDATA[ Are you preparing for coding interviews? Or competitive programming? It can take a lot of study and practice to get good at solving coding problems often used in interviews.   We just published a course on the freeCodeCamp.org YouTube channel that wi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/10-common-coding-interview-problems-solved/</link>
                <guid isPermaLink="false">66b2004827569435a9255a77</guid>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Tue, 11 Jan 2022 16:08:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/01/codinginterview.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Are you preparing for coding interviews? Or competitive programming? It can take a lot of study and practice to get good at solving coding problems often used in interviews.  </p>
<p>We just published a course on the freeCodeCamp.org YouTube channel that will teach you how to solve 10 common coding problems and improve your problem-solving skills.</p>
<p>This course was developed Inside code. He is an experienced developer and has a good understanding of the types of coding challenges often used in programmer interviews.</p>
<p>The course uses graphics and animation to help you understand the theory behind the solutions. You will be able to apply what you learn to all sorts of coding challenges.</p>
<p>You will learn how to solve the following problems. </p>
<ul>
<li>Valid anagram</li>
<li>First and last index in sorted array</li>
<li>Kth largest element</li>
<li>Symmetric tree</li>
<li>Generate parentheses</li>
<li>Gas station</li>
<li>Course schedule</li>
<li>Kth permutation</li>
<li>Minimum window substring</li>
<li>Largest rectangle in histogram</li>
</ul>
<p>Watch the full course below or on <a target="_blank" href="https://youtu.be/Peq4GCPNC5c">the freeCodeCamp.org YouTube channel</a> (2-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Peq4GCPNC5c" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Senior Software Engineer Interview Questions – Tips to Help You Prepare for a Job Interview ]]>
                </title>
                <description>
                    <![CDATA[ By Ankit Sharma I just joined Cisco Systems, India as a Senior Software Engineer (SDE III) on July 28, 2021. I am working with the Cisco Customer Experience team as a UI developer. The entire journey from applying for the job to accepting the offer w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/senior-software-engineer-interview-questions-how-i-got-a-job-as-an-sde-3-and-how-you-can-prepare-for-the-rounds/</link>
                <guid isPermaLink="false">66d45dcd33b83c4378a517ca</guid>
                
                    <category>
                        <![CDATA[ career advice ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Interview tips ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Job Interview ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 30 Aug 2021 17:56:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/08/pexels-tima-miroshnichenko-5439140.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ankit Sharma</p>
<p>I just joined <a target="_blank" href="https://www.cisco.com/">Cisco Systems</a>, India as a Senior Software Engineer (SDE III) on July 28, 2021. I am working with the <a target="_blank" href="https://www.cisco.com/c/m/en_us/customer-experience/index.html">Cisco Customer Experience</a> team as a UI developer.</p>
<p>The entire journey from applying for the job to accepting the offer was two months long. I wish to share my interview experience which will help you prepare for a senior-level UI engineer role.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Cisco-logo-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-what-you-will-get-out-of-this-article">What you will get out of this article?</h2>
<p>In this article, I will talk about my journey, from getting the job referral to accepting the offer. </p>
<p>I will talk about the different rounds of the interview process that I went through and the questions I was asked in them. The questions I share here will help you get ready for Angular development roles. </p>
<p>I will also share some of the questions you can ask the interviewer and the HR rep which will help you to know more about the company and the project.</p>
<p>So, lets’ get started!</p>
<h2 id="heading-how-i-discovered-the-job-posting">How I Discovered the Job Posting</h2>
<p>The first part of a job search is to get your résumé selected for the role you are looking for. I found out about this opportunity from a tweet shared by <a target="_blank" href="https://twitter.com/AlexOkrushko">Alex Okrushko</a>.</p>
<div class="embed-wrapper">
        <blockquote class="twitter-tweet">
          <a href="https://twitter.com/AlexOkrushko/status/1365064874599079947"></a>
        </blockquote>
        <script defer="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></div>
<p>I have been following Alex for the last two years. He used to work with the <a target="_blank" href="https://firebase.google.com/">Firebase</a> team at Google and he is also a part of the <a target="_blank" href="https://ngrx.io/">NgRx</a> team. I admire him for his immense contribution to the Angular community.</p>
<p>Alex is currently working as the Principal UI Architect at Cisco.</p>
<p>When he shared that they were looking for a UI developer, I realized that it would be the best opportunity to work directly with him. I sent a message over Twitter and he asked me to share my résumé. He was primarily looking for developers with strong Angular skills.</p>
<h2 id="heading-the-first-round-of-interviews">The First Round of Interviews</h2>
<p>One week after sharing my résumé with Alex, I received an email for the first round of interviews. </p>
<p>The first step in the interview process was a take-home assignment via <a target="_blank" href="https://devskiller.com/">Devskiller</a>. The invitation from Devskiller mentioned that I had seven days to complete the assignment. The total time allotted for this round was 2.5 hours. Once the test starts, you cannot stop it, so it has to be a single sitting of 2.5 hours.</p>
<p>I was given an Angular project with some bugs in it. There was a total of 11 unit test cases in the project. I was expected to fix all the bugs and make all the test cases green.</p>
<p>I started the test around 10:30pm (after my dinner) and finished it around 12:45am. I am most productive at night, so I chose that time. I was able to fix all the bugs and all the 11 test cases were green too. I slept happily that night 😊</p>
<h3 id="heading-angular-concepts-covered-in-this-round">Angular Concepts Covered in this Round</h3>
<p>The first round of interviews was majorly based around the following Angular concepts:</p>
<ul>
<li>Data binding</li>
<li>Event handling</li>
<li>State ownership and flows</li>
<li>Forms and form validations</li>
<li>Observables</li>
<li>Unit tests using Jasmine</li>
<li>Attribute directives</li>
<li>Structural directives - NgIf &amp; NgFor</li>
</ul>
<p>Alex verified my solution based on bug fixes, unit test status, and coding style. He was impressed with my performance in the first round and so I moved on to round two of the interview.</p>
<h2 id="heading-the-second-round-of-the-interview">The Second Round of the Interview</h2>
<p>I got the email asking for my availability for the second round of the interview. I was facing some health issues at that time, so I asked to schedule a week later and the interviewer was happy to do so.</p>
<p>The second round was also a project-based interview via Devskiller. I was given an Angular project and there are four questions based on that. All the questions are based on debugging and bug fixes. The total time allotted for this round was 1 hour.</p>
<p>The difference compared to the first round was that this time I was supposed to do a live coding session by sharing my screen with Alex. I was expected to explain the What, Why, and How of the code I was writing and talk through the solution. The thought process to approach the problem was given importance over the implementation. </p>
<p>This round was more of a pair-programming session with me in the driver's seat. Out of the four questions, I was able to solve the first three in 30 mins. The last one was based on the concept of Content child/view child. I struggled a bit with this question but a small hint from Alex helped me solve it.</p>
<p>I started the test at 10:30pm and finished it around 11:20pm.</p>
<blockquote>
<p>I was allowed to use online resources during the interview. But the condition was that I had to explain what I was looking for and why.</p>
</blockquote>
<p>At the end of the test, I was able to solve all four questions successfully. The feedback from Alex mentioned that I was struggling with a few of the concepts of RxJS and I need to work on that. But he was happy with my overall performance and I was promoted to the third round of the interview.</p>
<h3 id="heading-angular-concepts-covered-in-this-round-1">Angular Concepts Covered in this Round</h3>
<p>The second round of the interview was primarily based around the following Angular concepts:</p>
<ul>
<li>ViewChild and ViewChildren</li>
<li>ContentChild and ContentChildren</li>
<li>Content projection</li>
<li>Usage of Async pipe</li>
<li>Multicast observables</li>
<li>Parent-child relation of the components</li>
<li>Services</li>
</ul>
<h2 id="heading-the-third-round-of-the-interview">The Third Round of the Interview</h2>
<p>I got a call from my manager, Vaibhav, and he informed me that they were happy with my performance in first two rounds and wanted to schedule another round of technical discussion. </p>
<p>He asked me for my availability and I replied to him to schedule the call for the next day at 10 am IST. This round of interviews is conducted by the team in India so it has to be during IST working hours.</p>
<p>Two interviewers joined the call, and after the introduction, I was informed that this round would be divided into two sections, one for Angular and another one for JavaScript. </p>
<p>They started with the questions about Angular. This round had a mix of theoretical as well as scenario-based questions. The Angular interview continued for around 45 mins and I aced it. I answered all but one question.</p>
<p>After 45 mins they switched to the JS side. They started with the core concepts of JS and I answered those questions easily. Then they moved deeper into JS and I was asked few output-based questions. I struggled a bit here. </p>
<p>Then came more output-based questions and I was unable to answer a few of them. The JS interview also continued for 45 mins. I was not happy with my performance in the JS part of the interview. It was pretty average.</p>
<blockquote>
<p>The interview was originally scheduled for 1 hr, but it got stretched to 1.5 hrs.</p>
</blockquote>
<h3 id="heading-angular-concepts-covered-in-this-round-2">Angular Concepts Covered in this Round</h3>
<p>The third round of the interview was based around the following Angular concepts:</p>
<ul>
<li>RxJS concepts such as mergeMap &amp; switchMap</li>
<li>Directives</li>
<li>How does the ngIf directive work internally? How does it add DOM elements dynamically on the page?</li>
<li>How can we create a custom directive (with practical example)</li>
<li>What is Input and Output in a component?</li>
<li>Few theoretical questions around services, lazy loading of modules, and component communication</li>
</ul>
<h3 id="heading-javascript-concepts-covered-in-this-round">JavaScript Concepts Covered in this Round</h3>
<p>The third round of the interview was based around the following JS concepts:</p>
<ul>
<li>What are the different ways to create and call methods in JS?</li>
<li>Closures</li>
<li>Currying</li>
<li>Event bubbling</li>
<li>Output-based questions on closure and various setTimeout scenarios</li>
</ul>
<h2 id="heading-the-fourth-round-of-the-interview">The Fourth Round of the Interview</h2>
<p>Two days after the third round of interviews, I got a call from Vaibhav. He informed me that the interviewers were impressed with my Angular skills but they were not happy with my JS skills. But the overall performance was good, so I was able to move on to the fourth and the final round of interviews. He also suggested that I work on improving my JS skills.</p>
<p>The final round of interviews was scheduled on the Tuesday of the following week from 12:30pm to 1:30pm.</p>
<p>This was a managerial round and Vaibhav was the interviewer along with another senior developer from my team. This round was more focused on my non-technical skills. </p>
<p>He asked me about the project I was working on with my current company. I was also asked questions about Agile methodology since I had mentioned that in my résumé. I told him about my open-source work and he asked few questions about that.</p>
<p>At the end of the interview, Vaibhav shared that he was happy with my performance and wanted to go ahead with the offer. The next step was to update HR so that they could continue with the salary and the offer formalities.</p>
<h3 id="heading-question-asked-in-the-managerial-round-of-the-interview">Question Asked in the Managerial Round of the Interview</h3>
<p>The fourth round of the interview was entirely non-technical. I have mentioned a few of the questions asked in this round, and here are some more:</p>
<ul>
<li>Tell me about the current project and tech stack you're using.</li>
<li>What is your current role and responsibilities?</li>
<li>What are the Agile practices you are following currently?</li>
<li>How does your sprint planning look like?</li>
<li>How does a story refinement happen in your current project?</li>
<li>How can you resolve a conflict of ideas within your team?</li>
<li>Why are you looking for a change?</li>
<li>Why Cisco?</li>
</ul>
<h2 id="heading-salary-negotiations-and-getting-the-job-offer">Salary Negotiations and Getting the Job Offer</h2>
<p>I was waiting patiently for the call from HR after the fourth round of interviews. I got the call after one week. </p>
<p>The HR rep congratulated me on clearing all the rounds of the interview and asked me about my current salary and notice period. She also asked me to share my payslip and compensation details from my current employer.</p>
<p>After two days, I got another call from HR and she informed me about the salary I was being offered. I asked if there was any possibility of negotiating a better offer. She told me that this was the best possible salary as per my employment grade and it was not possible to increase it any further. I asked her for some time to make the final decision.</p>
<blockquote>
<p>I did not want to lose the job offer but at the same time, I also wanted to have a better salary structure than the one offered.</p>
</blockquote>
<p>I discussed the situation with my family as well as a few of my friends. I also had a call with Vaibhav, and a few calls with HR as well.</p>
<p>I was very much confused at this point, so I decided to write down the pros and cons of this role. Here is what I came up with:</p>
<p><strong>Pros</strong>:</p>
<ul>
<li>The project is customer-facing, so I'd get more exposure and increased responsibilities</li>
<li>Working at the scale of Cisco would be a plus</li>
<li>It would be a great learning and growth opportunity</li>
<li>The brand value of Cisco is high</li>
</ul>
<p><strong>Cons</strong>:</p>
<ul>
<li>The salary offered was not up to my expectations</li>
</ul>
<p>Finally, the pros outweighed the cons and I decided to accept the offer. So, I informed HR of my decision. But there was a surprise waiting for me.</p>
<blockquote>
<p>HR informed me that since I had taken a long time (around 10 days) to decide on the offer, they have put my offer on hold. I needed to wait further for the final confirmation from Cisco’s end.</p>
</blockquote>
<p>I panicked and thought that I had lost the opportunity. But I had no option other than to wait. TBH, I had lost any hope of getting the offer at this point.</p>
<p>After two weeks, I got a call from Vaibhav and he asked me if I was still interested to proceed with the job offer. After my confirmation, he informed me that HR was happy to release the offer letter. The next day, HR called me to confirm the same. By the end of the day, I had the offer letter in my inbox.</p>
<p>I gladly accepted the offer letter. I was relieved and ecstatic. All's well that ends well.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/japheth-mast-Ls3yexjyRpk-unsplash.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Job offer accepted</em></p>
<h2 id="heading-how-to-ask-good-questions-in-your-job-interview">How to Ask Good Questions in Your Job Interview</h2>
<p>Whenever you are being interviewed for a job, the interviewer always asks this question at the end – Do you have any questions? </p>
<p>A lot of people are confused about what to ask and what not to ask. Some people do not ask any questions at all. </p>
<p>Well, this is a good opportunity to learn more about the project, the team, and the company. So, you should ask your interviewer as many questions as you can.</p>
<p>Here are a few suggestions from my end.</p>
<h3 id="heading-what-to-ask-the-interviewer-in-a-technical-interview">What to Ask the Interviewer in a Technical Interview</h3>
<ul>
<li>Ask about the details of the project you are being interviewed for</li>
<li>Are you using any third-party tools/libraries in your application? If the answer is yes, ask about them.</li>
<li>How does the code review cycle work?</li>
<li>What are some of the current challenges in the codebase?</li>
<li>What is the ratio of new features vs the bug fixes assigned to a dev?</li>
<li>What testing framework do they use in the application for unit testing as well as E2E testing?</li>
<li>What is the test coverage for the application?</li>
</ul>
<h3 id="heading-what-to-ask-the-interviewer-in-a-managerial-interview">What to Ask the Interviewer in a Managerial Interview</h3>
<ul>
<li>Ask about the details of the project you are being interviewed for</li>
<li>What kind of application it is? Customer-facing or internal?</li>
<li>What will be my roles and responsibilities?</li>
<li>How is the work-life balance in the project?</li>
<li>What are my learning and growth opportunities in the next 1/2/3 years?</li>
<li>What are the current challenges with the project?</li>
<li>Are there any plans to add new features to the application?</li>
<li>Ask about the current team structure and where you will fit in it</li>
<li>How does the team culture look like in the current pandemic situation when we are 100% remote?</li>
<li>What is the working shift for this project? Is it flexible or fixed? Are there any shift allowances provided? This is a very important question and is often neglected by the interviewees.</li>
<li>An extension to the previous question – Does my job require any type of weekend support? If the answer is yes, ask about the timing, frequency per month, and the reimbursement policy around that.</li>
</ul>
<h3 id="heading-what-to-ask-hr-before-accepting-the-offer-or-joining-the-company">What to Ask HR Before Accepting the Offer or Joining the Company</h3>
<ul>
<li>Leave policies</li>
<li>Health insurance policies</li>
<li>WFH policies</li>
<li>What is the timeline of the annual appraisal cycle?</li>
<li>Will I be eligible for the appraisal in the next appraisal cycle?</li>
<li>Do I need to sign any kind of employment bond?</li>
<li>Does this job require me to move to another city/state? </li>
<li>Do I have to serve a probation period upon joining the company? If the answer is yes, ask about the duration and its effect on your employment. Every company has different rules related to probation so ask as many questions as you can around this topic</li>
<li>What are the covid-related benefits company is providing, for example vaccination, medical support, and so on?</li>
</ul>
<h2 id="heading-do-you-want-to-join-the-worlds-best-workplace">Do you Want to Join the World’s Best Workplace?</h2>
<p>Cisco Systems has been ranked number one in Fortune’s list of <a target="_blank" href="https://fortune.com/best-companies/2021/">100 Best Companies to Work For the year 2021</a> and <a target="_blank" href="https://fortune.com/best-workplaces-millennials/2021/">100 Best Large Workplaces for Millennials</a>. Do I need to say anything more about the company’s culture?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Fortune100Best2021.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Cisco provides you with ample learning and growth opportunities. You will get a chance to work on applications used on a worldwide scale. You will be always motivated to grow and explore yourself on a personal and professional level.</p>
<p>So, what are you waiting for? Go to the <a target="_blank" href="https://jobs.cisco.com/">Cisco Careers portal</a> and apply for the role you want.</p>
<p>I hope my interview experience will be helpful for you. Best of luck with your job interview.</p>
<p>If you like the article, share it with your friends. You can also connect with me on <a target="_blank" href="https://twitter.com/ankitsharma_007">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/ankitsharma-007/">LinkedIn</a>. My DMs are always open.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Data Science Interview Questions for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ By Davis David In 2012, Harvard Business Review named data science the sexiest job of the 21st century. But if you want to get a job as a data scientist, you'll need to go through a tough interview process. During data science job interviews, the int... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/23-common-data-science-interview-questions-for-beginners/</link>
                <guid isPermaLink="false">66d84ea592b237d9f6a7c50b</guid>
                
                    <category>
                        <![CDATA[ Artificial Intelligence ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Data Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Deep Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ interview questions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ neural networks ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 25 Aug 2021 21:39:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/08/pexels-tima-miroshnichenko-5439141.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Davis David</p>
<p>In 2012, Harvard Business Review named data science the sexiest job of the 21st century. But if you want to get a job as a data scientist, you'll need to go through a tough interview process.</p>
<p>During data science job interviews, the interviewer will likely ask questions from different data science topics such as statistics, programming, data analysis, data pre-processing, and modeling. </p>
<p>Your skills will be put to the test, and you need to prepare yourself if you want to get through the interview successfully.</p>
<p>In this article, I have compiled a list of common data science interview questions with tips on how you can answer them. I've also shared a list of resources that will help you learn more about the specific topic presented in each interview question.</p>
<h1 id="heading-data-science-interview-questions">Data Science Interview Questions</h1>
<h2 id="heading-what-is-logistic-regression-how-have-you-used-logistic-regression-recently">What is Logistic Regression? How Have You Used Logistic Regression Recently?</h2>
<p>Logistic regression is a popular algorithm used to solve classification problems. In this question, you need to explain what logistic regression is, how it works, and give an example of a data science problem you solved by using logistic regression.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/logistic-regression-the-good-parts-55efa68e11df/">Logistic Regression: The good parts</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/the-least-squares-regression-method-explained/">The Least Squares Regression Method – How to Find the Line of Best Fit</a></li>
</ul>
<h2 id="heading-why-do-we-need-evaluation-metrics-what-is-a-confusion-matrix">Why do we Need Evaluation Metrics? What is a Confusion Matrix?</h2>
<p>Machine learning models must be evaluated to check their performance. In this question, you need to explain how you can use the confusion matrix to evaluate the model's performance. You can further mention other metrics to evaluate regression and classification models.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/a-no-code-intro-to-the-9-most-important-machine-learning-algorithms-today/">9 Key Machine Learning Algorithms Explained in Plain English</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-i-used-deep-learning-to-classify-medical-images-with-fast-ai-cc4cfd64173c/">How I used Deep Learning to classify medical images with Fast.ai</a></li>
</ul>
<h2 id="heading-how-is-data-science-different-from-traditional-application-programming">How is Data Science Different from Traditional Application Programming?</h2>
<p>A good way to answer this question is by using examples of how the program is created in both cases.</p>
<p>Traditional programming approach:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/image-1.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Data science approach:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/image-2.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Here is a good resource to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/data-science-course-for-beginners/">Free 6-Hour Data Science Course for Beginners</a></li>
</ul>
<h2 id="heading-explain-the-difference-between-supervised-and-unsupervised-learning">Explain the Difference Between Supervised and Unsupervised Learning.</h2>
<p>Supervised and unsupervised learning are two types of machine learning techniques. The best way to answer this question is by explaining their differences in terms of the kind of datasets you can use in each technique and examples of algorithms.</p>
<p><strong>Here is a good resource to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/when-to-use-different-machine-learning-algorithms-a-simple-guide-ba615b19fb3b/">When to use different machine learning algorithms: a simple guide</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/want-to-know-how-deep-learning-works-heres-a-quick-guide-for-everyone-1aedeca88076/">Want to know how deep learning works? Here's a quick guide</a></li>
</ul>
<h2 id="heading-what-is-a-decision-tree">What is a Decision Tree?</h2>
<p>A decision tree is another supervised learning algorithm that you can use to solve regression or classification problems. </p>
<p>You should be able to explain how the decision tree algorithm learns from the data and the advantages and disadvantages of using a decision tree algorithm.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-the-tree-based-algorithm-for-machine-learning/">How to Use Tree-Based Algorithms in Machine Learning</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/a-no-code-intro-to-the-9-most-important-machine-learning-algorithms-today/">9 Key Machine Learning Algorithms Explained in Plain English</a></li>
</ul>
<h2 id="heading-what-is-cross-validation">What is Cross-Validation?</h2>
<p>The purpose of this question is to determine if you know any techniques used to assess the effectiveness of the machine learning model – for example, when you want to avoid overfitting. </p>
<p>When answering this question, you should explain any methods of cross-validation you have applied in any data science projects.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-get-a-grip-on-cross-validations-bb0ba779e21c/">Get a Grip on Cross-Validation in Machine Learning</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/key-machine-learning-concepts-explained-dataset-splitting-and-random-forest/">Key Machine Learning Concepts Explained</a></li>
</ul>
<h2 id="heading-what-is-a-normal-distribution">What is a Normal Distribution?</h2>
<p>This term is commonly used when you're solving a data science problem. In this question, you can explain the meaning of normal distribution, its properties, and why it is important to check if your data is normally distributed.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/normal-distribution-explained/">Normal Distribution Explained in Plain English</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=rzFX5NWojp0">Normal Distribution Clearly Explained</a></li>
</ul>
<h2 id="heading-what-is-a-random-forest-algorithm">What is a Random Forest Algorithm?</h2>
<p>Random forest is one of the most popular machine learning algorithms. When answering this question, you should explain how the algorithm learns from the data and when you should use the random forest algorithm over other machine learning algorithms.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-the-tree-based-algorithm-for-machine-learning/">Random Forest Classifier Tutorial</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/key-machine-learning-concepts-explained-dataset-splitting-and-random-forest/">Dataset Splitting and Random Forest Algorithms</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=eM4uJ6XGnSM">Random Forest Algorithm Explained</a></li>
</ul>
<h2 id="heading-explain-univariate-bivariate-and-multivariate-analyses">Explain Univariate, Bivariate, and Multivariate Analyses</h2>
<p>These three types of analyses are used to summarize variables in the dataset and help you get some insights. You can also talk about how they're different and when you can apply them – just make sure to show some examples.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.youtube.com/watch?v=JG8GRlMjp3c">Univariate, Bivariate and Multivariate Analysis</a> </li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-how-to-select-the-best-performing-linear-regression-for-univariate-models-e9d429c40581/">How to Select the Best Performing Linear Regression for Univariate Models</a></li>
</ul>
<h2 id="heading-how-can-we-handle-missing-data">How can we Handle Missing Data?</h2>
<p>Some datasets may have missing data or values and can cause a problem when training machine learning models. </p>
<p>It is important to mention some techniques that can be used to handle missing data. You can also share your experience of how you handled missing data in your last data science project.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/the-penalty-of-missing-values-in-data-science-91b756f95a32/">The Penalty of Missing Values in Data Science</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/feature-engineering-and-feature-selection-for-beginners/">Feature Engineering and Feature Selection for Beginners</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=P_iMSYQnqac">Handling Missing Data Easily Explained</a></li>
</ul>
<h2 id="heading-what-is-the-benefit-of-dimensionality-reduction">What is the Benefit of Dimensionality Reduction?</h2>
<p>Dimensionality reduction is a technique to reduce the number of features or variables in the dataset. </p>
<p>There are different advantages of dimensionality reduction you can explain when answering this question. You should explain why and when you need to apply this technique.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/an-illustrative-introduction-to-fishers-linear-discriminant-9484efee15ac/">How to use dimensionality reduction</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/the-curse-of-dimensionality-how-we-can-save-big-data-from-itself-d9fa0f872335/">Escaping the curse of dimensionality</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=1eYJKD0TQ8U">Pros and Cons of Dimensionality Reduction</a> </li>
</ul>
<h2 id="heading-how-can-we-deal-with-outliers">How can we deal with Outliers?</h2>
<p>An outlier is a data point that deviates significantly from the rest. In this question, you can explain how one can identify outliers and different techniques used to deal with outliers.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/what-is-an-outlier-definition-and-how-to-find-outliers-in-statistics/">What is an Outlier in Statistics?</a> </li>
<li><a target="_blank" href="https://www.kdnuggets.com/2017/01/3-methods-deal-outliers.html">Three Ways to Deal with Outliers</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=DDpym2j_ILY">How to Remove Outliers from a Dataset</a></li>
</ul>
<h2 id="heading-what-is-ensemble-learning">What is Ensemble Learning?</h2>
<p>In machine learning, ensemble learning is a process of using multiple algorithms to obtain better predictive performance than could be obtained from any one algorithm alone. </p>
<p>When answering this question, you can also share your experience the last time you implemented ensemble methods in a data science project.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.analyticsvidhya.com/blog/2015/08/introduction-ensemble-learning/">Introduction to Ensemble Learning</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=WtWxOhhZWX0">Ensemble Learning in Machine Learning</a></li>
</ul>
<h2 id="heading-explain-how-machine-learning-is-different-from-deep-learning">Explain how Machine Learning is Different from Deep Learning</h2>
<p>The best way to explain the difference between machine learning and deep learning is the way they solve problems. </p>
<p>You can go further by explaining some of the problems that can be solved by either machine learning or deep learning techniques.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/convolutional-neural-network-tutorial-for-beginners/">A beginner's guide to Machine Learning and Deep Learning</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/ai-vs-ml-whats-the-difference/">AI vs ML – What's the Difference between Artificial Intelligence and Machine Learning?</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-scikit-learn/">Machine Learning Crash Course</a> and <a target="_blank" href="https://www.freecodecamp.org/news/deep-learning-crash-course-learn-the-key-concepts-and-terms/">Deep Learning Crash Course</a></li>
</ul>
<h2 id="heading-what-are-the-differences-between-overfitting-and-underfitting">What are the Differences Between Overfitting and Underfitting?</h2>
<p>The best way to explain the difference between overfitting and underfitting is not just with a definition but through examples. </p>
<p>You can also share your personal experience when faced with overfitting or underfitting problems in a data science project.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/handling-overfitting-in-deep-learning-models/">How to Handle Overfitting in Deep Learning Models</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-build-better-machine-learning-models/">How to Build Better Machine Learning Models</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/free-deep-learning-with-pytorch-live-course/">Deep Learning with PyTorch Course</a></li>
</ul>
<h2 id="heading-what-is-regularisation-why-is-it-useful">What is Regularisation? Why is it Useful?</h2>
<p>When answering this question, you can also go further by explaining the two common regularization techniques L1 norm and L2 norm.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-build-your-first-neural-network-to-predict-house-prices-with-keras-f8db83049159/">How to Build your First Neural Network</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/deep-learning-crash-course-learn-the-key-concepts-and-terms/">Deep Learning Crash Course</a></li>
</ul>
<h2 id="heading-what-is-selection-bias">What is Selection Bias?</h2>
<p>It is not enough just to define Selection Bias. If possible you should explain different types of bias, their effects, and how to avoid them.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://imotions.com/blog/selection-bias/">What is Selection Bias?</a></li>
<li><a target="_blank" href="https://academy4sc.org/video/selection-bias-dont-forget-about-me/">Selection Bias – Don't forget about me!</a></li>
</ul>
<h2 id="heading-can-you-explain-the-difference-between-a-validation-set-and-a-test-set">Can you Explain the Difference Between a Validation Set and a Test Set?</h2>
<p>In this question, after explaining their differences, you can explain the advantage of having a validation set and a test set in a data science project.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/key-machine-learning-concepts-explained-dataset-splitting-and-random-forest/">Key Machine Learning Concepts Explained</a></li>
<li><a target="_blank" href="https://machinelearningmastery.com/difference-test-validation-datasets/">Difference between Test Sets and Validation Sets</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/what-to-do-when-your-training-and-testing-data-come-from-different-distributions-d89674c6ecd8/">What to do when your training and testing data come from different distributions</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=pGlQLMPI46g">Machine Learning – Validation vs Testing</a></li>
</ul>
<h2 id="heading-what-is-the-difference-between-regression-and-classification-ml-techniques">What is the Difference Between Regression and Classification ML Techniques?</h2>
<p>We all know that regression and classification are supervised learning and the only difference is their output. When you answer this question, you can mention a few algorithms that can be used to solve regression problems or classification problems. Also, try to share how their models are evaluated.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-build-and-train-linear-and-logistic-regression-ml-models-in-python/">How to Build and Train Linear and Logistic Regression ML Models</a></li>
<li><a target="_blank" href="https://www.javatpoint.com/regression-vs-classification-in-machine-learning">Regression vs Classification in Machine Learning</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/machine-learning-basics-for-developers/">Machine Learning Basics for Developers</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=TJveOYsK6MY">Classification and Regression in Machine Learning</a></li>
</ul>
<h2 id="heading-what-are-artificial-neural-networks">What are Artificial Neural Networks?</h2>
<p>In this question don't just define Artificial Neural Networks but also explain their advantages and where you can use them.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://hackernoon.com/overview-of-artificial-neural-networks-and-its-applications-2525c1addff7">Overview of Artificial Neural Networks and their Applications</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/deep-learning-neural-networks-explained-in-plain-english/">Deep Learning Neural Networks Explained in Plain English</a></li>
</ul>
<h2 id="heading-what-tools-and-devices-do-you-plan-to-use-in-your-role-as-a-data-scientist">What Tools and Devices do you Plan to use in Your Role as a Data Scientist?</h2>
<p>This question is straightforward but you should mention tools you have used before or you are planning to use in the future project. </p>
<p>You can also share your experience of how various tools help you implement data science projects successfully.</p>
<p>Keep in mind that you will use different tools for different projects. For example, some tools can be used for an NLP project and others for a Time-series project.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://sdacademy.dev/13-tools-every-data-scientist-needs-to-know/">13 Tools Every Data Scientist Needs to Know</a></li>
</ul>
<h2 id="heading-what-is-natural-language-processing-state-some-real-life-examples-of-nlp">What is Natural Language Processing? State some Real-Life Examples of NLP.</h2>
<p>You have to define Natural language processing in a simple way and how it can be used to solve business problems. Then share some real-life examples. If possible you can also share some of the NLP projects you have done or collaborate with others.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/what-is-natural-language-processing-an-nlp-definition-and-tutorial-for-beginners/">What is Natural Language Processing? A tutorial for beginners</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-natural-language-processing-no-experience-required/">Learn Natural Language Processing with Python and TensorFlow</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/natural-language-processing-basics-for-developers/">What Every Developer Needs to Know about NLP</a></li>
<li><a target="_blank" href="https://intellipaat.com/blog/applications-of-nlp/">Applications of NLP</a></li>
</ul>
<h2 id="heading-what-is-normalisation-difference-between-normalisation-and-standardization">What is Normalisation? Difference between Normalisation and Standardization?</h2>
<p>Normalization and standardization are techniques used to pre-process the data before applying machine learning algorithms. </p>
<p>The purpose of the question is to explain the differences between these two techniques and at what condition of the dataset you should apply one over another.</p>
<p><strong>Here are resources to help you get started crafting your response:</strong></p>
<ul>
<li><a target="_blank" href="https://www.analyticsvidhya.com/blog/2020/04/feature-scaling-machine-learning-normalization-standardization/">The Difference Between Normalization and Standardization</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/all-you-need-to-know-about-text-preprocessing-for-nlp-and-machine-learning-bc1c5765ff67/">Text Preprocessing for NLP and Machine Learning</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/feature-engineering-and-feature-selection-for-beginners/">Feature Engineering and Feature Selection for Beginners</a></li>
<li><a target="_blank" href="https://www.youtube.com/watch?v=mnKm3YP56PY">Standardization vs Normalization – Feature Scaling</a> </li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/https-medium-com-hadrienj-preprocessing-for-deep-learning-9e2b9c75165c/">Preprocessing for Deep Learning</a></li>
</ul>
<h2 id="heading-final-thoughts-on-data-science-interview-questions">Final Thoughts on Data Science Interview Questions</h2>
<p>Reviewing these common data science interview questions will actually boost your confidence during the interview. </p>
<p>Don't expect the interviewer to ask you all questions mentioned in this article. But most of the interview questions will come from the same topics.</p>
<p>For example, instead of asking "<strong>Explain the difference between supervised and unsupervised learning</strong>", the interviewer can ask you to “<strong>Explain some supervised learning algorithms and how they learn from the data</strong>”.</p>
<p>If you are interested in learning and reading more data science interview questions, take your time and read through <a target="_blank" href="https://www.springboard.com/blog/data-science/data-science-interview-questions/">these</a> <a target="_blank" href="https://huyenchip.com/ml-interviews-book/">additional</a> <a target="_blank" href="https://hackernoon.com/160-data-science-interview-questions-415s3y2a">resources</a> for inspiration.</p>
<p>And don't forget to practice your coding skills because some questions during the interview require you to code the solution.</p>
<p>I hope these data science interview questions will help you prepare for your interview and I wish you the best of luck in your data science career.</p>
<p>If you learned something new or enjoyed reading this article, please share it so that others can see it. Until then, see you in the next post!</p>
<p>You can also find me on Twitter <a target="_blank" href="https://twitter.com/Davis_McDavid">@Davis_McDavid</a>.</p>
<p>And you can read more articles like this <a target="_blank" href="https://hackernoon.com/u/davisdavid">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
