<?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[ Farhan Hasin Chowdhury - 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[ Farhan Hasin Chowdhury - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 19 May 2026 10:28:21 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/farhanhasin/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ What Are Context Managers in Python? ]]>
                </title>
                <description>
                    <![CDATA[ One of the most common tasks that you'll have to perform in your programs is working with external resources. These resources can be files on your computer's storage or an open connection to third-party service on the internet. For the sake of simpli... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/context-managers-in-python/</link>
                <guid isPermaLink="false">66b0ab2fd28cb2f6cba9413a</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Mon, 02 Oct 2023 13:49:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/python-context-managers-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>One of the most common tasks that you'll have to perform in your programs is working with external resources. These resources can be files on your computer's storage or an open connection to third-party service on the internet.</p>
<p>For the sake of simplicity, imagine a program that opens a file, writes something to it, and then closes the file.</p>
<p>One way to implement this program in Python would be like this:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    my_file = open(<span class="hljs-string">'books.txt'</span>, <span class="hljs-string">'w'</span>)
    my_file.write(<span class="hljs-string">'If Tomorrow Comes by Sidney Sheldon'</span>)
    my_file.close()


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()
</code></pre>
<p>Given that you run this program with the right permissions on your computer, it'll create a file called <code>books.txt</code> and write <code>If Tomorrow Comes by Sidney Sheldon</code> in it.</p>
<p>The <code>open()</code> function is one of the built-in functions in Python. It can open a file from a given path and return a corresponding file object.</p>
<p>A file object or file-like object, as it's often called, is a useful way to encapsulate methods like <code>read()</code>, <code>write()</code>, or <code>close()</code>. </p>
<p>The <code>write()</code> method can be used write/send bytes-like object to an open stream, like a file.</p>
<p>Whenever you open an external resource, you must close it when its no longer needed, and the <code>close()</code> method does just that.</p>
<p>This program is functional, but it has a big flaw. If the program fails to close the file, it will remain open until the program itself closes.</p>
<p>You see, every program that you run on your computer gets a finite amount of memory allocated to it. All the variables you create or external resource you open from a program stay within the memory allocated to it by your computer.</p>
<p>If a program like this one, keeps opening new files without closing the previous ones, the allocated memory will keep shrinking.</p>
<p>At one point the program will inevitably run out of memory and crash ungracefully. This problem is referred to as a memory leak.</p>
<p>One way to prevent this from happening in Python is using a <code>try...except...finally</code> statement.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    my_file = open(<span class="hljs-string">'books.txt'</span>, <span class="hljs-string">'w'</span>)

    <span class="hljs-keyword">try</span>:
        my_file.write(<span class="hljs-string">'If Tomorrow Comes by Sidney Sheldon'</span>)
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">f'writing to file failed: <span class="hljs-subst">{e}</span>'</span>)
    <span class="hljs-keyword">finally</span>:
        my_file.close()


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()
</code></pre>
<p>The code inside the <code>finally</code> block will run no matter what. So even if the program fails on the right action, it'll still be executed.</p>
<p>So, this solves the problem but imagine writing these lines of code every time you want to write something to a file.</p>
<p>It's not very reusable. You will have to repeat yourself a lot and chances of skipping a portion of the <code>if...except...finally</code> ladder is also a possibility.</p>
<p>That's where context managers come in.</p>
<h2 id="heading-what-is-a-context-manager-in-python">What is a Context Manager in Python?</h2>
<p>According to the Python glossary, a context manager is —</p>
<blockquote>
<p>An object which controls the environment seen in a <code>with</code> statement by defining <code>__enter__()</code> and <code>__exit__()</code> methods.</p>
</blockquote>
<p>That may not be noticeably clear to you. Let me explain the concept with an example.</p>
<p>The <code>with</code> statement in Python lets you run a block of code within a runtime context defined by a context manager object.</p>
<p>Once the block of code has finished executing, the context manager object will take care of tearing down any external resources that are no longer needed.</p>
<p>You can rewrite the program by using the <code>with</code> statement as follows:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    <span class="hljs-keyword">with</span> open(<span class="hljs-string">'books.txt'</span>, <span class="hljs-string">'w'</span>) <span class="hljs-keyword">as</span> my_file:
        my_file.write(<span class="hljs-string">'If Tomorrow Comes by Sidney Sheldon'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()
</code></pre>
<p>Since the <code>open()</code> function is paired with a <code>with</code> statement in this example, the function will create a context manager.</p>
<p>The file object will be accessible within the context of the indented code block, which means the file object doesn't exist outside of that scope.</p>
<p>The <code>as</code> keyword is useful when you want to assign a target variable to a returned object. Here, the <code>my_file</code> variable is the target and will hold the file object.</p>
<p>You can do whatever you want within the indented block of code and don't have to worry about closing the file.</p>
<p>Because once the block of code has finished executing the context manager will close the file automatically.</p>
<p>So, you have rewritten the entire <code>try...except...finally</code> ladder within two lines of code using the <code>with</code> statement and a context manager.</p>
<p>But how does that happen? How does a context manager object handle the task of setting up and closing resources?</p>
<p>And where are those <code>__enter__()</code> and <code>__exit__()</code> methods you read about on the Python documentation glossary?</p>
<p>Well, I'm so glad you asked :-)</p>
<h2 id="heading-how-to-create-a-custom-context-manager-in-python">How To Create a Custom Context Manager in Python</h2>
<p>The American theoretical physicist, Richard Feynman famously said —</p>
<blockquote>
<p>What I cannot create, I do not understand.</p>
</blockquote>
<p>So, to understand the functionalities of a context manager you must create one by yourself and there are two distinct ways of doing that.</p>
<p>The first one is a generator-based approach and the second one is a class-based approach. In this section, I'll teach you both.</p>
<p>But before that, let me you a complex example that does more than merely opening and closing files in Python.</p>
<p>Imagine another Python application that must communicate with an SQLite database for reading and writing data.</p>
<p>You can write that program as follows:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

create_table_sql_statement = <span class="hljs-string">'CREATE TABLE IF NOT EXISTS books(title TEXT, author TEXT)'</span>
insert_into_table_sql_statement = <span class="hljs-string">"INSERT INTO books VALUES ('If Tomorrow Comes', 'Sidney Sheldon'), ('The Lincoln Lawyer', 'Michael Connelly')"</span>
select_from_table_sql_statement = <span class="hljs-string">'SELECT * FROM books'</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    database_path = <span class="hljs-string">':memory:'</span>

    connection = sqlite3.connect(database_path)
    cursor = connection.cursor()

    <span class="hljs-keyword">try</span>:
        cursor.execute(create_table_sql_statement)
        connection.commit()

        cursor.execute(insert_into_table_sql_statement)
        connection.commit()

        cursor.execute(select_from_table_sql_statement)

        print(cursor.fetchall())
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">f'read or write action to the database failed: <span class="hljs-subst">{e}</span>'</span>)
    <span class="hljs-keyword">finally</span>:
        connection.close()


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># [('If Tomorrow Comes', 'Sidney Sheldon'), ('The Lincoln Lawyer', 'Michael Connelly')]</span>
</code></pre>
<p>This Python program establishes a connection with an SQLite database. Then it creates a new table called books with two <code>TEXT</code> columns named <code>title</code> and <code>author</code>.</p>
<p>The program then stores information about three books on the table, retrieves them from the database, and prints out the retrieved data on the console.</p>
<p>As evident from the output of the <code>print()</code> statement, the program has successfully saved and retrieved the given data from the database.</p>
<p>There are three SQL queries in this program responsible for the database actions I just described.</p>
<pre><code class="lang-python">create_table_sql_statement = <span class="hljs-string">'CREATE TABLE IF NOT EXISTS books(title TEXT, author TEXT)'</span>
insert_into_table_sql_statement = <span class="hljs-string">"INSERT INTO books VALUES ('If Tomorrow Comes', 'Sidney Sheldon'), ('The Lincoln Lawyer', 'Michael Connelly')"</span>
select_from_table_sql_statement = <span class="hljs-string">'SELECT * FROM books'</span>
</code></pre>
<p>I've kept these three lines of code at the top of the file to keep the <code>main()</code> function to cleaner. The rest of the program sets up the database and executes the queries.</p>
<p>Python comes with excellent support for SQLite databases, thanks to the <code>sqlite3</code> module encapsulating useful methods such as the <code>sqlite3.connect()</code> method.</p>
<p>This method takes the path to a database as a string, attempts to establish a connection and in case of success, returns a <code>Connection</code> object.</p>
<p>If you pass <code>:memory:</code> instead of a file path, the program will create a temporary database on your computer's memory.</p>
<p>Once you have a connection, you'll need a <code>Cursor</code> object. A cursor object is a layer of abstraction required for executing SQL queries.</p>
<p>The <code>cursor()</code> method encapsulated within the <code>Connection</code> object returns a new cursor to the connected database.</p>
<p>Inside a <code>try</code> block, you can attempt to execute whatever query you want using the <code>execute()</code> or <code>executemany()</code> methods.</p>
<pre><code class="lang-python">    <span class="hljs-keyword">try</span>:
        cursor.execute(create_table_sql_statement)
        connection.commit()

        cursor.execute(insert_into_table_sql_statement)
        connection.commit()

        cursor.execute(select_from_table_sql_statement)

        print(cursor.fetchall())
</code></pre>
<p>You need to call the <code>connection.commit()</code> method every time you write something to the database. Otherwise, the changes will be lost.</p>
<p>Data returned from a database remains within the <code>cursor</code> object and you can access them using the <code>cursor.fetchone()</code> or <code>cursor.fetchall()</code> methods.</p>
<p>In case of a failure, the <code>except</code> block will be triggered. The <code>finally</code> block will run unconditionally and close the database connection in the end.</p>
<p>This is fine and functional but like I've already said, it's not very reusable and is error prone.</p>
<p>Unfortunately, or in our case fortunately Python doesn't come with a built-in context manager for handling connections with SQLite databases.</p>
<p>So, let's try and see if we can produce one ourselves.</p>
<h3 id="heading-how-to-create-a-class-based-context-manager-in-python">How to Create a Class Based Context Manager in Python</h3>
<p>To write a class-based context manager in Python, you need to create an empty class with three specific methods:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Database</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>
        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__enter__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__exit__</span>(<span class="hljs-params">self, exc_type, exc_val, exc_tb</span>):</span>
        <span class="hljs-keyword">pass</span>
</code></pre>
<p>The first one is obviously the class constructor that doesn't accept any parameter yet. It'll be responsible for accepting a database path:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Database</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, path: str</span>):</span>
        self.path = path

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__enter__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">pass</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__exit__</span>(<span class="hljs-params">self, exc_type, exc_val, exc_tb</span>):</span>
        <span class="hljs-keyword">pass</span>
</code></pre>
<p>The <code>__enter__()</code> method handles the task of setting up the resource. This is where you establish the connection and instantiate the cursor:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Database</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, path: str</span>):</span>
        self.path = path

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__enter__</span>(<span class="hljs-params">self</span>):</span>
        self.connection = sqlite3.connect(self.path)
        self.cursor = self.connection.cursor()
        <span class="hljs-keyword">return</span> self

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__exit__</span>(<span class="hljs-params">self, exc_type, exc_val, exc_tb</span>):</span>
        <span class="hljs-keyword">pass</span>
</code></pre>
<p>However you can not return two objects at once so you have to return the instance of the class itself.</p>
<p>Finally, the <code>__exit__()</code> method handles the task of closing the external resource in question.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Database</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, path: str</span>):</span>
        self.path = path

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__enter__</span>(<span class="hljs-params">self</span>):</span>
        self.connection = sqlite3.connect(self.path)
        self.cursor = self.connection.cursor()
        <span class="hljs-keyword">return</span> self

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__exit__</span>(<span class="hljs-params">self, exc_type, exc_val, exc_tb</span>):</span>
        <span class="hljs-keyword">if</span> exc_type <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
            print(<span class="hljs-string">f'an error occurred: <span class="hljs-subst">{exc_val}</span>'</span>)

        self.connection.close()
</code></pre>
<p>You can use this context manager in conjunction with the <code>with</code> statement in your code as follows:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3

create_table_sql_statement = <span class="hljs-string">'CREATE TABLE IF NOT EXISTS books(title TEXT, author TEXT)'</span>
insert_into_table_sql_statement = <span class="hljs-string">"INSERT INTO books VALUES ('If Tomorrow Comes', 'Sidney Sheldon'), ('The Lincoln Lawyer', 'Michael Connelly')"</span>
select_from_table_sql_statement = <span class="hljs-string">'SELECT * FROM books'</span>


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Database</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, path: str</span>):</span>
        self.path = path

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__enter__</span>(<span class="hljs-params">self</span>):</span>
        self.connection = sqlite3.connect(self.path)
        self.cursor = self.connection.cursor()
        <span class="hljs-keyword">return</span> self

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__exit__</span>(<span class="hljs-params">self, exc_type, exc_val, exc_tb</span>):</span>
        <span class="hljs-keyword">if</span> exc_type <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
            print(<span class="hljs-string">f'an error occurred: <span class="hljs-subst">{exc_val}</span>'</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    <span class="hljs-keyword">with</span> Database(<span class="hljs-string">':memory:'</span>) <span class="hljs-keyword">as</span> db:
        db.cursor.execute(create_table_sql_statement)
        db.connection.commit()

        db.cursor.execute(insert_into_table_sql_statement)
        db.connection.commit()

        db.cursor.execute(select_from_table_sql_statement)

        print(db.cursor.fetchall())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># [('If Tomorrow Comes', 'Sidney Sheldon'), ('The Lincoln Lawyer', 'Michael Connelly')]</span>
</code></pre>
<p>Evident from the output of the <code>print()</code> function call, the program has successfully stored and retrieved the given data from the database.</p>
<p>Without the <code>with</code> statement, <code>Database</code> is just a plain old class. However, the moment you put <code>with</code> infront of it, the three methods hop into action.</p>
<p>The <code>__init__()</code> method is the initializer and works identically to any other plain Python class's initializer method. It takes the path to the database.</p>
<p>The <code>__enter__()</code> method sets up the connection to the database and returns the instance of the context manager class to the target variable, <code>db</code> in this case.</p>
<p>This target variable is now encapsulating both the connection and the cursor objects. You can access them as <code>db.connection</code> and <code>db.cursor</code> respectively.</p>
<p>Once the code inside the <code>with</code> block finishes running, the <code>__exit__()</code> method will execute and close the active connection to the database.</p>
<p>You can handle any exception that may occur during the execution inside the <code>__exit__()</code> method. If there is an exception, <code>exc_type</code> holds the type of the exception, <code>exc_val</code> holds the value of the exception, <code>exc_tb</code> holds the traceback.</p>
<p>If there is no exception, the three variables will have a value of <code>None</code>. I'll not get into the details of exception handling in this article since that can take on many forms depending on what you're dealing with.</p>
<p>To make this custom context manager accessible from anywhere in the program, you can put it into its own separate module or even package.</p>
<p>This is far better solution than the <code>try...except...finally</code> ladder you saw earlier. You don't have to repeat yourself and chances of a human error is lower.</p>
<h3 id="heading-how-to-create-a-generator-based-context-manager-in-python">How to Create a Generator Based Context Manager in Python</h3>
<p>Evident from the title of this section, this approach uses a generator instead of a class to implement a context manager.</p>
<p>Syntactically, generators are almost the same as normal functions, except that you need to use <code>yield</code> instead of <code>return</code> in a generator.</p>
<p>Writing a generator-based context manager requires less code but it also loses some of its readability.</p>
<p>You can write the generator-based equivalent of the class-based <code>Database</code> context manager as follows:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3
<span class="hljs-keyword">from</span> contextlib <span class="hljs-keyword">import</span> contextmanager

<span class="hljs-meta">@contextmanager</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">database</span>(<span class="hljs-params">path: str</span>):</span>
    connection = sqlite3.connect(path)
    <span class="hljs-keyword">try</span>:
        cursor = connection.cursor()
        <span class="hljs-keyword">yield</span> {<span class="hljs-string">'connection'</span>: connection, <span class="hljs-string">'cursor'</span>: cursor}
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">f'an error occurred: <span class="hljs-subst">{e}</span>'</span>) 
    <span class="hljs-keyword">finally</span>:
        connection.close()
</code></pre>
<p>Instead of a class, you have a generator function here so there is no initializer. Instead, the function itself can accept the path to the database as a parameter.</p>
<p>Within a <code>try</code> block, you can establish a connection to the database, instantiate the cursor, and return both objects to the user.</p>
<p>You can write <code>yield connection, cursor</code> to return the two objects but in that case the generator will return them as a tuple.</p>
<p>I prefer to use strings over numbers as accessors and that's why I have put the two objects inside a dictionary with descriptive keys.</p>
<p>The <code>except</code> block will run in case of an exception. Feel free to implement any exception handling strategy that you see fit.</p>
<p>The <code>finally</code> block will run unconditionally and close the open connection at the end of the <code>with</code> block.</p>
<p>Since there are no <code>__enter__()</code> or <code>__exit__()</code> methods either, you need to decorate the generator with the <code>@contextmanager</code> decorator.</p>
<p>This decorator defines a factory function for <code>with</code> statement context managers, without needing to create a class or separate <code>__enter__()</code> and <code>__exit__()</code> methods.</p>
<p>Usage of this context manager is identical to its class-based conterpart except the capitalization of its name.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> sqlite3
<span class="hljs-keyword">from</span> contextlib <span class="hljs-keyword">import</span> contextmanager

create_table_sql_statement = <span class="hljs-string">'CREATE TABLE IF NOT EXISTS books(title TEXT, author TEXT)'</span>
insert_into_table_sql_statement = <span class="hljs-string">"INSERT INTO books VALUES ('If Tomorrow Comes', 'Sidney Sheldon'), ('The Lincoln Lawyer', 'Michael Connelly')"</span>
select_from_table_sql_statement = <span class="hljs-string">'SELECT * FROM books'</span>


<span class="hljs-meta">@contextmanager</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">database</span>(<span class="hljs-params">path: str</span>):</span>
    connection = sqlite3.connect(path)
    <span class="hljs-keyword">try</span>:
        cursor = connection.cursor()
        <span class="hljs-keyword">yield</span> {<span class="hljs-string">'connection'</span>: connection, <span class="hljs-string">'cursor'</span>: cursor}
    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">f'an error occurred: <span class="hljs-subst">{e}</span>'</span>) 
    <span class="hljs-keyword">finally</span>:
        connection.close()


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    database_path = <span class="hljs-string">':memory:'</span>

    <span class="hljs-keyword">with</span> database(database_path) <span class="hljs-keyword">as</span> db:
        db.get(<span class="hljs-string">'cursor'</span>).execute(create_table_sql_statement)
        db.get(<span class="hljs-string">'connection'</span>).commit()

        db.get(<span class="hljs-string">'cursor'</span>).execute(insert_into_table_sql_statement)
        db.get(<span class="hljs-string">'connection'</span>).commit()

        db.get(<span class="hljs-string">'cursor'</span>).execute(select_from_table_sql_statement)

        print(db.get(<span class="hljs-string">'cursor'</span>).fetchall())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># [('If Tomorrow Comes', 'Sidney Sheldon'), ('The Lincoln Lawyer', 'Michael Connelly')]</span>
</code></pre>
<p>Since <code>db</code> is a dictionary instead of an object in this case, you will need to use square braces or the <code>get()</code> method to access the connection or cursor object.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Context managers in Python is one of those topics that a lot of programmers have used but do not understand clearly.</p>
<p>I hope this article has cleared up some of your confusions.</p>
<p>If you'd like to connect to me, I am always available on <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>. Feel free to shoot a message and I'd be happy to respond. Also, if you think this was helpful, consider endorsing my relevant skills on the platform.</p>
<p>Until the next one, take care and keep exploring.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Python Code Example Handbook ]]>
                </title>
                <description>
                    <![CDATA[ Very few programming languages are as universally loved as Python. The brainchild of Dutch programmer Guido van Rossum, Python is easy to learn, powerful, and an utter joy to work with. Thanks to its popularity, video and written resources about Pyth... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-python-code-example-handbook/</link>
                <guid isPermaLink="false">66b0ab5bb30dd4d00547bc18</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ example ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Tue, 22 Aug 2023 21:54:38 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/08/Learn-Python-with-Code-Examples-Handbook-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Very few programming languages are as universally loved as Python. The brainchild of Dutch programmer Guido van Rossum, Python is easy to learn, powerful, and an utter joy to work with.</p>
<p>Thanks to its popularity, video and written resources about Python are plentiful. This handbook, however, tries to be a bit different by not being a definitive guide to the language.</p>
<p>Instead you'll learn about all the topics that I consider to be the language fundamentals with a lot of code examples.</p>
<p>I haven't discussed object-oriented programming in this handbook because I believe it to be a very broad subject deserving of its own separate handbook.</p>
<p>Near the end, I've also listed out some learning resources to further your knowledge of Python and programming in general.</p>
<p>Without any further ado, let's jump in!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#heading-how-to-setup-python-on-your-computer">How to Setup Python on Your Computer</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-a-python-ide-on-your-computer">How to Install a Python IDE on Your Computer</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-new-project-on-pycharm">How to Create a New Project on PyCharm</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-the-hello-world-program-in-python">How to Write the Hello World Program in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-initialize-and-publish-a-git-repository-from-pycharm">How to Initialize and Publish a Git Repository From PyCharm</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-variables-and-different-types-of-data-in-python">How to Work With Variables and Different Types of Data in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-simple-numbers-in-python">How to Work With Simple Numbers in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-take-inputs-from-users-in-python">How to Take Inputs From Users in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-strings-in-python">How to Work With Strings in Python</a></li>
<li><a class="post-section-overview" href="#heading-what-are-the-sequence-types-in-python">What Are the Sequence Types in Python?</a><ul>
<li><a class="post-section-overview" href="#heading-lists-in-python">Lists in Python</a></li>
<li><a class="post-section-overview" href="#heading-tuples-in-python">Tuples in Python</a></li>
<li><a class="post-section-overview" href="#heading-ranges-in-python">Ranges in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-indexing-works-in-python">How Indexing Works in Python</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-are-the-iterable-types-and-how-to-use-them-for-loops-in-python">What Are the Iterable Types and How to Use them for Loops in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-while-loops-in-python">How to Use While Loops in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-nested-loops-in-python">How to Write Nested Loops in Python</a></li>
<li><a class="post-section-overview" href="#heading-what-are-some-common-sequence-type-operations-in-python">What Are Some Common Sequence Type Operations in Python?</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-use-the-in-operator-in-python">How to Use the in Operator in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-and-operators-with-sequence-types-in-python">How to Use the + and * Operators with Sequence Types in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-len-min-and-max-functions-in-python">How to Use the len(), min(), and max() Functions in Python</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-are-some-string-type-operations-in-python">What Are Some String Type Operations in Python?</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-capitalize-strings-in-python">How to Capitalize Strings in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-convert-strings-to-lower-case-or-upper-case-in-python">How to Convert Strings to Lower Case or Upper Case in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-count-the-number-of-occurrences-of-a-substring-in-a-string-in-python">How to Count the Number of Occurrences of a Substring in a String in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-split-and-join-strings-in-python">How to Split and Join Strings in Python</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-write-conditional-statements-in-python">How to Write Conditional Statements in Python</a></li>
<li><a class="post-section-overview" href="#heading-what-are-relational-and-logical-operators-in-python">What are Relational and Logical Operators in Python?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-assignment-operators-in-python">What Are Assignment Operators in Python?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-set-type-in-python">What Is the Set Type in Python?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-mapping-type-in-python">What Is the Mapping Type in Python?</a><ul>
<li><a class="post-section-overview" href="#heading-what-are-dictionary-view-objects-in-python">What Are Dictionary View Objects in Python?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-write-functions-in-python">How to Write Functions in Python</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-write-anonymous-or-lambda-functions-in-python">How to Write Anonymous or Lambda Functions in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-local-nonlocal-and-global-variables-in-python">How to Work with local, nonlocal and global Variables in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-pass-a-variable-number-of-arguments-to-a-function-using-args-and-kwargs-in-python">How to Pass a Variable Number of Arguments to a Function Using <em>args and *</em>kwargs in Python</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-are-modules-in-python">What Are Modules in Python?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-python-documentation-efficiently">How to Use the Python Documentation Efficiently</a></li>
<li><a class="post-section-overview" href="#heading-whats-next">What's Next?</a><ul>
<li><a class="post-section-overview" href="#heading-object-oriented-programming">Object Oriented Programming</a></li>
<li><a class="post-section-overview" href="#heading-algorithms-and-data-structures">Algorithms and Data Structures</a></li>
<li><a class="post-section-overview" href="#heading-django">Django</a></li>
<li><a class="post-section-overview" href="#heading-qt">Qt</a></li>
<li><a class="post-section-overview" href="#heading-pygame">PyGame</a></li>
<li><a class="post-section-overview" href="#heading-data-science">Data Science</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-prerequisites"><strong>Prerequisites</strong></h2>
<p>You don't need to know any other programming language for this book, but knowing one may help you understand the basics of Python.</p>
<p>Other than that you'll need to be efficient enough with your choice of operating system to download and install new software, and gain administrative access if needed.</p>
<h2 id="heading-how-to-setup-python-on-your-computer">How to Setup Python on Your Computer</h2>
<p>Installing Python on your computer is a very straightforward process. In fact, if you're on a Linux system, Python should already be installed.</p>
<p>Open up your terminal window and execute the following command:</p>
<pre><code>python --version
</code></pre><p>If Python is installed on your system, you'll get an output like <code>Python 3.10.4</code> or some other minor version.</p>
<p>Although most of the modern Linux distribution use Python 3 as default, some of the older distributions may still use Python 2 by default.</p>
<p>So if the aforementioned command refers to Python 2, try out the following command:</p>
<pre><code>python3 --version
</code></pre><p>I'd also suggest that you check for updates on your Linux distribution and install any new updates for Python.</p>
<p>Although Python comes preinstalled with macOS as well, I'd suggest that you follow this article by <a target="_blank" href="https://www.freecodecamp.org/news/author/dillionmegida/">Dillion Megida</a> and install a more recent version.</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/how-to-install-python-3-on-mac-and-update-the-python-version-macos-homebrew-command-guide/">https://www.freecodecamp.org/news/how-to-install-python-3-on-mac-and-update-the-python-version-macos-homebrew-command-guide/</a></div>
<p>Finally, for Windows, I'd suggest you follow an article by <a target="_blank" href="https://www.freecodecamp.org/news/author/fahimbinamin/">Md. Fahim Bin Amin</a> and properly install the latest version of Python.</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/how-to-install-python-in-windows-operating-system/">https://www.freecodecamp.org/news/how-to-install-python-in-windows-operating-system/</a></div>
<p>As long as you have a Python 3 version installed, you're good to go.</p>
<h2 id="heading-how-to-install-a-python-ide-on-your-computer">How to Install a Python IDE on Your Computer</h2>
<p>Much of your experience as a developer will depend on what program you've chosen to write your code in. A good integrated development environment (IDE) or Code Editor can really boost your productivity.</p>
<p>These days <a target="_blank" href="https://code.visualstudio.com/">Visual Studio Code</a> has become the go to code editor for all languages and platforms. But for the sake of simplicity, we'll use <a target="_blank" href="https://www.jetbrains.com/pycharm/">PyCharm</a> in this book.</p>
<p>If you'd like to use VS Code, have written a full-length article on <a target="_blank" href="https://www.freecodecamp.org/news/how-to-configure-visual-studio-code-for-python-development/">how to configure Visual Studio Code for Python development</a>. Feel free to check that out if you do not mind configuring your editor manually.</p>
<p>The professional edition of the IDE <a target="_blank" href="https://www.jetbrains.com/pycharm/buy/">can cost you $89.00 per year</a> but there is also a free and open-source community edition. Head over to the <a target="_blank" href="https://www.jetbrains.com/pycharm/download/">PyCharm download page</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/download-pycharm-page.png" alt="Image" width="600" height="400" loading="lazy">
<em>Download PyCharm page</em></p>
<p>Use the black "Download" button to download the community edition. The file size should be a little larger than 350 megabytes.</p>
<p>On Windows you'll get an executable installer, on macOS you'll get an Apple disc image, and on Linux you'll get a TAR archive.</p>
<p>I won't demonstrate the installation process in this book since it's similar to installing any other software on your machine.</p>
<p>Once installed, you can start the IDE from your start menu/app launcher. On your first launch, you'll be given the chance to configure a few things. I'd suggest you keep the defaults.</p>
<p>Once the configuration wizard ends, you should see the following welcome window:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-469.png" alt="Image" width="600" height="400" loading="lazy">
<em>Welcome to PyCharm screen - with options to start a new project, open a project, or get one from your VCS</em></p>
<p>Picking one IDE or code editor instead of the other one will not affect your experience with following this handbook, so feel free to use whatever you feel comfortable with.</p>
<h2 id="heading-how-to-create-a-new-project-on-pycharm">How to Create a New Project on PyCharm</h2>
<p>If you have the welcome window open from the previous section, click on the "New Project" button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/start-a-new-project-in-pycharm.png" alt="Image" width="600" height="400" loading="lazy">
<em>Start a new project in PyCharm</em></p>
<p>In the next step, pick a location to store your project:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-472.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the location input box, the <code>HelloWorld</code> part is the name of the project. Then make sure you have "New environment using Virtualenv" selected. Then, make sure that the correct version of Python is selected from the "Base interpreter" dropdown.</p>
<p><a target="_blank" href="https://virtualenv.pypa.io/">Virtualenv</a> is a program that can create isolated Python environments from a given base interpreter. This is very helpful because later on when you'll work on multiple Python projects, their dependencies may conflict with each other.</p>
<p>Creating isolated environments for each project will solve that issue and it'll also keep your global Python installation free from any unnecessary package installation.</p>
<p>Since this may be your first Python project, I'd suggest you leave the "Create a main.py welcome script" option checked. Once you're happy with your choices, click the "Create" button.</p>
<p>The project creation process shouldn't take very long. Once it's done, the IDE should open the project automatically for you.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-473.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can use the play button at the top right corner to run the code. The button is configured to run the "main.py" file by default. </p>
<p>That's why you can see "main" written by its side. You can write your custom configuration as well, but that's a topic for a later section.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/image-474.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can see the output of your program at the bottom of the IDE. PyCharm comes with support for TODO comments, a built in terminal and more. You'll learn about a bunch of these features as you go forward.</p>
<h2 id="heading-how-to-write-the-hello-world-program-in-python">How to Write the Hello World Program in Python</h2>
<p>Continuing on from the last section, open up the "main.py" file and replace all the preexisting code with the following line of code:</p>
<pre><code class="lang-python">print(<span class="hljs-string">'Hello, World!'</span>)

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>The <code>print()</code> function prints out anything that you pass into the set of parenthesis. You don't have to name your Python file "main.py" specifically. It's just a way to let you know that this is the entry point to this program.</p>
<p>That's all you need to write the simplest executable program in Python. But there is even a better way to do it. Update the code as follows:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(<span class="hljs-string">'Hello, World!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>As you keep working on bigger projects, you'll eventually have more than one Python file in your project and this way of writing a script can be useful.</p>
<p>To simulate a bigger project, create another Python file by right clicking on the "HelloWorld" project name and selecting "Python File" under the "New" sub menu.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Name your file something like "library" and press enter while "Python file" is highlighted in the list of file types.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>A new file with the name "library.py" will show up on your project folder. Put the following line of code inside the file:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>():</span>
    print(<span class="hljs-string">'Hello, World!'</span>)
</code></pre>
<p>This is a very simple function that prints out "Hello, World!" on the console. You can <code>import</code> and use this function in your "main.py" file.</p>
<p>To do so, update the code for "main.py" file as follows:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> library <span class="hljs-keyword">import</span> greet


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    greet()


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>You're importing the <code>greet()</code> function from the "library.py" file and executing that inside the <code>main()</code> function.</p>
<p>Right now in your project, you have two types of Python file. You have the "main.py" file which is a script. In other words, you can run this file.</p>
<p>Then you have the "library.py" file which is a library. In other words, it houses a number of useful functions and variables that you can import inside other Python files.</p>
<p>Now imagine you have hundreds of files in your project and they more or less look the same. How would someone else find the entry point to the program?</p>
<p>The easiest way would be to perform a search for the line <code>if __name__ == '__main__'</code> on the entire project. This makes your code a lot more readable.</p>
<p>Now that I have you convinced that this is the way to go, let me explain what is actually going on here.</p>
<p>The <code>__name__</code> is a special Python variable. In case of a script, the value of this variable will be <code>__main__</code> and in case of a library, its value will be the name of that file.</p>
<p>So in the aforementioned program, the value of <code>__name__</code> inside the "main.py" file will be <code>__main__</code> and <code>library</code> inside the "library.py" file.</p>
<p>If you change the name of then "main.py" file to something else, the value will still be <code>__main__</code> because it's a script.</p>
<p>Nothing is stopping the "library.py" file from being a script, though. If you run that file instead, it'll become a script.</p>
<p>In languages like C/C++/Go/Java, you'll have a specified <code>main</code> function. That function will be the entry point to the program.</p>
<p>Since Python doesn't have anything like that, the usage of the <code>if __name__ == '__main__'</code> expression enforces a sense of a specified entry point to your program.</p>
<p>It tells the programmer and the IDE that this script is for execution (not for importing inside other Python files).</p>
<h2 id="heading-how-to-initialize-and-publish-a-git-repository-from-pycharm">How to Initialize and Publish a Git Repository From PyCharm</h2>
<p>You may already be familiar with <a target="_blank" href="https://git-scm.com/">Git</a> and know how to initialize a new repository. If you prefer using some other Git client, that's totally fine.</p>
<p>However I think knowing how to make commits right from your IDE can boost your productivity.</p>
<p>Keep in mind you'll need to have Git installed and configured on your system. If you don't have that, <a target="_blank" href="https://www.freecodecamp.org/news/git-first-time-setup/">this article</a> by <a target="_blank" href="https://www.freecodecamp.org/news/author/bolajiayodeji/">Bolaji Ayodeji</a> may come in handy.</p>
<p>Now, continuing on from the last section, if you look at the bottom of your IDE, you should see a "Version Control" tab.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-2-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click on it and you should switch to the version control tab. Now click on the "Create Git repository..." link.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-3-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>PyCharm will ask you where you want to initialize the new repository. Make sure you're picking the right folder.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As soon as you press the "OK" button, the "Version Control" tab will change to a "Git" tab.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-5-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>At it's current state, there are no commits. Before you make your first commit, I'd suggest you add a ".gitignore" file so that no unwanted file gets to the repository.</p>
<p>To generate a new gitignore file, head over to <a target="_blank" href="https://www.toptal.com/developers/gitignore/">gitignore.io</a> website. You can generate gitignore files for a large number of technologies from this website.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-6.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You write the name of the technologies that you want to generate the file for. I usually go with "Python", "PyCharm" and hit the "Create" button.</p>
<p>The website will display the content of your desired ".gitignore" file. Select and copy everything from there and go back to PyCharm.</p>
<p>To simulate that, create a new file in your project by right clicking on the "HelloWorld" project name and selecting "File" under the "New" sub menu.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Name your file ".gitignore" and press enter. PyCharm will ask whether you want to add this file to Git or not. Click on Add and then paste the copied content.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-10.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>At this moment, your repository doesn't have any commits. To create a new commit, click on the "Commit local changes" link or switch to the "Commit" tab.</p>
<p>Since this is your first commit, check all "Changes" and "Unversioned Files" from the commit tab.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-11.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Since this is your first commit, put a descriptive commit message such as "Initial commit" and press the "Commit" button to finalize.</p>
<p>You've successfully made a commit to your local repository. You can now see all the commits under the master branch in detail.</p>
<p>Now it's time to publish this repository on GitHub. To do so, create a new repository under your GitHub account.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-14.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Then copy the SSH link to this repository. If you do not have SSH configured for your project, you may use the HTTPS link but I'd highly recommend SSH.</p>
<p>Now go back to PyCharm and look at the top right corner. Besides where it says Git, you'll find a few signs.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-15.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The downwards blue arrow will pull code from your remote repository, the tick sign will create a new commit, the upwards green arrow will push code.</p>
<p>The clock icon will show your commit history and finally the looped back arrow will revert your changes. Click on the push arrow and a new window will pop up.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-16.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click on the "Define remote" link and inside the URL input box, paste the link you've copied from GitHub. Press the OK button and wait until the process ends.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-17.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If everything goes fine, PyCharm will give you a "Push" button. It shouldn't take more than a few seconds to push the code to your remote repository.</p>
<p>If you're using HTTPS instead of SSH, you may have to provide your GitHub email and password on every push.</p>
<p>Once done, visit your remote repository and refresh the page to see if the changes have been pushed correctly or not.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-18.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now you can commit and push your code to GitHub right from your IDE every time you make any significant change.</p>
<p>For example, delete the "library.py" file and update the code inside the "main.py" file to print out "Hello, World!" on the console.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(<span class="hljs-string">"Hello, World!"</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>Once you've made the changes, switch to the commit tab and you'll see all the uncommitted changes.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-19.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Make sure you've checked all the changes you want to commit. Write a descriptive commit message.</p>
<p>Then instead of just committing, try the "Commit and Push..." button this time. A new window will show up.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-21.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If everything looks good to you, click on the Push button and wait for the process to finish.</p>
<p>Remember, if you're using HTTPS you may have to reenter your email and password on every push.</p>
<p>You can check your remote repository on GitHub to make sure that the push has been done correctly.</p>
<p>You can do a lot more in terms of version controlling within PyCharm such as handling pull requests, but I'll leave those out for a later time.</p>
<h2 id="heading-how-to-work-with-variables-and-different-types-of-data-in-python">How to Work With Variables and Different Types of Data in Python</h2>
<p>A variable is an entity that can take on different values of different types. It's a named location in your computer's memory.</p>
<p>To create a new variable in Python, you just need to type out the name of the variable, followed by an equal sign and the value.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book = <span class="hljs-string">'Dracula'</span>
    author = <span class="hljs-string">'Bram Stoker'</span>
    release_year = <span class="hljs-number">1897</span>
    goodreads_rating = <span class="hljs-number">4.01</span>

    print(book)
    print(author)
    print(release_year)
    print(goodreads_rating)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula</span>
<span class="hljs-comment"># Bram Stoker</span>
<span class="hljs-comment"># 1897</span>
<span class="hljs-comment"># 4.01</span>
</code></pre>
<p>When it comes to naming your variable, the <a target="_blank" href="https://peps.python.org/pep-0008/#function-and-variable-names">PEP 8 - Style Guide for Python</a> says:</p>
<blockquote>
<p>Function names should be lowercase, with words separated by underscores as necessary to improve readability.</p>
</blockquote>
<p>And</p>
<blockquote>
<p>Variable names follow the same convention as function names.</p>
</blockquote>
<p>The <a target="_blank" href="https://peps.python.org/pep-0008/#names-to-avoid">guide also</a> says:</p>
<blockquote>
<p>Never use the characters ‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as single character variable names. In some fonts, these characters are indistinguishable from the numerals one and zero. When tempted to use ‘l’, use ‘L’ instead.</p>
</blockquote>
<p>As long as you're keeping these guidelines in mind, declaring variables in Python is very straightforward.</p>
<p>Instead of declaring the variables in separate lines, you can declare them in one go as follows:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(book)
    print(author)
    print(release_year)
    print(goodreads_rating)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula</span>
<span class="hljs-comment"># Bram Stoker</span>
<span class="hljs-comment"># 1897</span>
<span class="hljs-comment"># 4.01</span>
</code></pre>
<p>All you have to do is write the individual variable names in a single line using commas as separators. </p>
<p>Then after the equal sign you have to write the corresponding values in the same order as their names again using commas as separators.</p>
<p>In fact, you can also print them all out in one go. The <code>print()</code> method can take multiple parameters separated by commas.</p>
<pre><code>def main():
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(book, author, release_year, goodreads_rating)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

# Dracula Bram Stoker <span class="hljs-number">1897</span> <span class="hljs-number">4.01</span>
</code></pre><p>These parameters are then printed on the terminal in a single line using spaces for separating each of them.</p>
<p>Speaking of the <code>print()</code> method, you can use the <code>+</code> sign to add variables with strings inside a print method:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(book + <span class="hljs-string">' is a novel by '</span> + author + <span class="hljs-string">', published in '</span> + release_year + <span class="hljs-string">'. It has a rating of '</span> + goodreads_rating + <span class="hljs-string">' on goodreads.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()


<span class="hljs-comment"># TypeError: can only concatenate str (not "int") to str</span>
</code></pre>
<p>If you try to run this code you'll get a <code>TypeError</code> that says Python can concatenate or add together strings not integers.</p>
<p>In the code snippet above, <code>book</code>, <code>author</code>, <code>release_year</code>, and <code>goodreads_rating</code> are all variables of different types.</p>
<p>The <code>book</code> and <code>author</code> variables are strings. The <code>release_year</code> is an integer and finally the <code>goodreads_rating</code> variable is a floating point number.</p>
<p>Whenever Python encounters a <code>+</code> sign in front of a numeric type, it assumes that the programmer may be performing an arithmetic operation.</p>
<p>The easiest way to solve this problem is to convert the numeric types to strings. You can do that by calling the <code>str()</code> method on the numeric variables.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(book + <span class="hljs-string">' is a novel by '</span> + author + <span class="hljs-string">', published in '</span> + str(release_year) + <span class="hljs-string">'. It has a rating of '</span> + str(goodreads_rating) + <span class="hljs-string">' on goodreads.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula is a novel by Bram Stoker, published in 1897. It has a rating of 4.01 on goodreads.</span>
</code></pre>
<p>That's better – but you can make that line of code even more readable by using a f string.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(<span class="hljs-string">f'<span class="hljs-subst">{book}</span> is a novel by <span class="hljs-subst">{author}</span>, published in <span class="hljs-subst">{release_year}</span>. It has a rating of <span class="hljs-subst">{goodreads_rating}</span> on goodreads.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula is a novel by Bram Stoker, published in 1897. It has a rating of 4.01 on goodreads.</span>
</code></pre>
<p>You can turn a regular string to a f string by putting a <code>f</code> in front of it and suddenly you can write variable names inside curly braces right within the string itself.</p>
<p>There is one last thing that's bugging me, and that's the length of the line of code itself. Fortunately you can split long strings into multiple shorter ones as follows:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book, author, release_year, goodreads_rating = <span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Bram Stoker'</span>, <span class="hljs-number">1897</span>, <span class="hljs-number">4.01</span>

    print(<span class="hljs-string">f'<span class="hljs-subst">{book}</span> is a novel by <span class="hljs-subst">{author}</span>, published in <span class="hljs-subst">{release_year}</span>.'</span>
          <span class="hljs-string">f' It has a rating of <span class="hljs-subst">{goodreads_rating}</span> on goodreads.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula is a novel by Bram Stoker, published in 1897. It has a rating of 4.01 on goodreads.</span>
</code></pre>
<p>Now that's how a good piece of Python code should look. I'd suggest you try to make your code readable from the very beginning – you'll thank me later for that.</p>
<p>Other than <code>int</code> and <code>float</code>, there is another numeric type called <code>complex</code> in Python. It was specifically designed for dealing with numbers like <code>500+2j</code>.</p>
<p>There are also boolean data that can hold the value <code>True</code> or <code>False</code> and nothing else. You can actually ask Python questions and it'll answer in boolean.</p>
<p>Throughout this book you'll not see complex numbers in action and booleans will come into play much later. So for now, lets focus on simple numbers and strings.</p>
<h2 id="heading-how-to-work-with-simple-numbers-in-python">How to Work With Simple Numbers in Python</h2>
<p>Simple numbers in Python are of two types. Whole numbers are integers and numbers with floating points in them are floats.</p>
<p>In Python, you can represent integers using four different bases. These are decimal, hexadecimal, octal, and binary.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Base</td><td>Representation</td></tr>
</thead>
<tbody>
<tr>
<td>Decimal</td><td>404</td></tr>
<tr>
<td>Hexadecimal</td><td>0x194</td></tr>
<tr>
<td>Octal</td><td>0o624</td></tr>
<tr>
<td>Binary</td><td>0b000110010100</td></tr>
</tbody>
</table>
</div><p>So you can represent the value of 404 in hexadecimal, octal, or binary by prefixing the corresponding value with <code>0x</code>, <code>0o</code>, or <code>0b</code> respectively.</p>
<p>On the other hand you can represent floats with the precision of up to 15 significant digits in Python. Any digit after the 15th place may be inaccurate.</p>
<p>There are six different arithmetic operations that you can perform on any of the simple numeric types. The simplest of the bunch are addition and subtraction.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">15</span>
    num_2 = <span class="hljs-number">12</span>

    print(<span class="hljs-string">f'sum of num_1 and num_2 is: <span class="hljs-subst">{num_1 + num_2}</span>'</span>)
    print(<span class="hljs-string">f'difference of num_1 and num_2 is: <span class="hljs-subst">{num_1 - num_2}</span>'</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># sum of num_1 and num_2 is: 27</span>
<span class="hljs-comment"># difference of num_1 and num_2 is: 3</span>
</code></pre>
<p>In case of a subtraction operation, the result will be negative if the second operand is larger than the first one.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">15</span>
    num_2 = <span class="hljs-number">12</span>

    print(<span class="hljs-string">f'difference of num_2 and num_1 is: <span class="hljs-subst">{num_2 - num_1}</span>'</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># difference of num_2 and num_1 is: -3</span>
</code></pre>
<p>Similarly you can perform multiplication and division operations using their corresponding operators.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">15</span>
    num_2 = <span class="hljs-number">12</span>

    print(<span class="hljs-string">f'product of num_1 and num_2 is: <span class="hljs-subst">{num_1 * num_2}</span>'</span>)
    print(<span class="hljs-string">f'quotient of num_1 and num_2 is: <span class="hljs-subst">{num_1 / num_2}</span>'</span>)
    print(<span class="hljs-string">f'floored quotient of num_1 and num_2 is: <span class="hljs-subst">{num_1 // num_2}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># product of num_1 and num_2 is: 180</span>
<span class="hljs-comment"># quotient of num_1 and num_2 is: 1.25</span>
<span class="hljs-comment"># floored quotient of num_1 and num_2 is: 1</span>
</code></pre>
<p>Keep in mind that you can not divide a number by zero in Python. If you attempt that, you'll get a <code>ZeroDivisionError</code> error (more on that later).</p>
<p>Output from a division operation will always be a float value, unless you perform a floored division by using two division operators.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">15</span>
    num_2 = <span class="hljs-number">12</span>

    print(<span class="hljs-string">f'floored quotient of num_1 and num_2 is: <span class="hljs-subst">{num_1 // num_2}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># floored quotient of num_1 and num_2 is: 1</span>
</code></pre>
<p>In this case the result will be rounded off to the nearest integer low – so, for example, 0.25 will be lost. So only perform this operation when such loss of data is permissible.</p>
<p>The last operation to discuss is finding the remainder of a division operation.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">15</span>
    num_2 = <span class="hljs-number">12</span>

    print(<span class="hljs-string">f'remainder of num_1 / num_2 is: <span class="hljs-subst">{num_1 % num_2}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># remainder of num_1 / num_2 is: 3</span>
</code></pre>
<p>This operation is also called a modulo or modulus operation. So if someone mentions the modulo or modulus operator, they're referring to the percent sign.</p>
<p>You can turn an unsigned number into a negative one just by adding a <code>-</code> sign in front of it. You can also freely convert between integer to float and vice versa.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    float_variable = <span class="hljs-number">1.25</span>
    integer_variable = <span class="hljs-number">55</span>

    print(<span class="hljs-string">f'<span class="hljs-subst">{float_variable}</span> converted to an integer is: <span class="hljs-subst">{int(float_variable)}</span>'</span>)
    print(<span class="hljs-string">f'<span class="hljs-subst">{integer_variable}</span> converted to a float is: <span class="hljs-subst">{float(integer_variable)}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 1.25 converted to an integer is: 1</span>
<span class="hljs-comment"># 55 converted to a float is: 55.0</span>
</code></pre>
<p>Loss of data in case of a float to integer conversion is inevitable, so be careful. You can use the <code>int()</code> and <code>float()</code> methods on strings as well (more on that later).</p>
<p>Any arithmetic operation involving a float operand will always produce a float result, unless converted to integer explicitly.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    float_variable = <span class="hljs-number">5.0</span>
    integer_variable = <span class="hljs-number">55</span>

    print(<span class="hljs-string">f'the sum of <span class="hljs-subst">{float_variable}</span> and <span class="hljs-subst">{integer_variable}</span> is: <span class="hljs-subst">{float_variable + integer_variable}</span>'</span>)
    print(<span class="hljs-string">f'the sum of <span class="hljs-subst">{float_variable}</span> and <span class="hljs-subst">{integer_variable}</span> '</span>
          <span class="hljs-string">f'converted to integer is: <span class="hljs-subst">{int(float_variable + integer_variable)}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># the sum of 5.0 and 55 is: 60.0</span>
<span class="hljs-comment"># the sum of 5.0 and 55 converted to integer is: 60</span>
</code></pre>
<p>If you ever want to get the absolute value of a signed value you can do so using the <code>abs()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">-5.8</span>

    print(<span class="hljs-string">f'the absolute value of <span class="hljs-subst">{num_1}</span> is: <span class="hljs-subst">{abs(num_1)}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># the absolute value of -5.8 is: 5.8</span>
</code></pre>
<p>There is a similar method <code>pow(x, y)</code> that you can use to apply <code>x</code> as the power of <code>y</code> like this.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    x = <span class="hljs-number">2</span>
    y = <span class="hljs-number">3</span>

    print(<span class="hljs-string">f'<span class="hljs-subst">{<span class="hljs-number">2</span>}</span> to the power of <span class="hljs-subst">{<span class="hljs-number">3</span>}</span> is: <span class="hljs-subst">{pow(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)}</span>'</span>)
    print(<span class="hljs-string">f'<span class="hljs-subst">{<span class="hljs-number">2</span>}</span> to the power of <span class="hljs-subst">{<span class="hljs-number">3</span>}</span> is: <span class="hljs-subst">{<span class="hljs-number">2</span> ** <span class="hljs-number">3</span>}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 2 to the power of 3 is: 8</span>
<span class="hljs-comment"># 2 to the power of 3 is: 8</span>
</code></pre>
<p>You can perform the same operation using two multiplication operators but I always prefer the <code>pow()</code> method.</p>
<p>Finally there is the <code>divmod()</code> method that you can use to combine the division and modulo operation.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    num_1 = <span class="hljs-number">8</span>
    num_2 = <span class="hljs-number">2</span>

    print(<span class="hljs-string">f'division and modulus of <span class="hljs-subst">{num_1}</span> and <span class="hljs-subst">{num_2}</span> is: <span class="hljs-subst">{divmod(num_1, num_2)}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># division and modulus of 8 and 2 is: (4, 0)</span>
</code></pre>
<p>The method returns a tuple of numbers (more on that later). The first one is the result of the division and the second one is the result of the modulo operation.</p>
<p>These are the basic operations you can perform on simple numbers right from the get go. But you can do much more once you start to pull in the built-in modules.</p>
<h2 id="heading-how-to-take-inputs-from-users-in-python">How to Take Inputs From Users in Python</h2>
<p>Learning how to take input from a user is an important milestone because it lets you create programs that a human being can interact with.</p>
<p>Unlike many other programming languages, taking user inputs in Python is very straightforward.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    name = input(<span class="hljs-string">'What is your name? '</span>)

    print(<span class="hljs-string">f'Nice to meet you <span class="hljs-subst">{name}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># What is your name? Farhan</span>
<span class="hljs-comment"># Nice to meet you Farhan</span>
</code></pre>
<p>The built-in <code>input()</code> method does exactly what it sounds like. The method accepts a single parameter <code>prompt</code> which is of string type.</p>
<p>Whatever you write as the value of this parameter will be shown in the console – like in this case, "What is your name?" is the prompt.</p>
<p>Once the user writes something on the console and presses enter, the input method will return that as a string.</p>
<p>You can save that string to any variable like I've saved the name inside the <code>name</code> variable. Even if the user inputs a number, <code>input()</code> will return that as a string.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    name = input(<span class="hljs-string">'What is your name? '</span>)
    age = input(<span class="hljs-string">f'How old are you <span class="hljs-subst">{name}</span>? '</span>)
    current_year = input(<span class="hljs-string">f'What year is this again? '</span>)

    print(<span class="hljs-string">f'If my calculations are right, you were born in <span class="hljs-subst">{current_year - age}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># What is your name? Farhan</span>
<span class="hljs-comment"># How old are you Farhan? 27</span>
<span class="hljs-comment"># What year is this again? 2023</span>
<span class="hljs-comment"># TypeError: unsupported operand type(s) for -: 'str' and 'str'</span>
</code></pre>
<p>Even though Python is taking all the user inputs correctly, it fails to calculate the user's birth year because arithmetic operations are not a good fit for strings.</p>
<p>To solve this problem, you just have to convert the user inputs to numeric types using the <code>int()</code> or <code>float()</code> functions as needed.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    name = input(<span class="hljs-string">'What is your name? '</span>)
    age = int(input(<span class="hljs-string">f'How old are you <span class="hljs-subst">{name}</span>? '</span>))
    current_year = int(input(<span class="hljs-string">f'What year is this again? '</span>))

    print(<span class="hljs-string">f'If my calculations are right, you were born in <span class="hljs-subst">{current_year - age}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># What is your name? Farhan</span>
<span class="hljs-comment"># How old are you Farhan? 27</span>
<span class="hljs-comment"># What year is this again? 2023</span>
<span class="hljs-comment"># If my calculations are right, you were born in 1996</span>
</code></pre>
<p>There you go, works like a charm. You can perform this conversion at any point in the code. It's not mandatory to convert them right at the beginning.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    temperature_in_celsius = input(<span class="hljs-string">'What is the temperature in celsius? '</span>)

    temperature_in_fahrenheit = (float(temperature_in_celsius) * <span class="hljs-number">1.8</span>) + <span class="hljs-number">32</span>

    print(<span class="hljs-string">f'<span class="hljs-subst">{temperature_in_celsius}</span> degree celsius is equivalent to <span class="hljs-subst">{temperature_in_fahrenheit}</span> degree fahrenheit.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># What is the temperature in celsius? 32</span>
<span class="hljs-comment"># 32 degree celsius is equivalent to 89.6 degree fahrenheit.</span>
</code></pre>
<p>This program can convert temperature from Celsius to Fahrenheit. In this program, I didn't convert the input from string to a numeric type right away.</p>
<p>I performed the conversion during the calculation leaving the original input variable intact. Also notice the use of <code>float()</code> instead of the <code>int()</code> function.</p>
<h2 id="heading-how-to-work-with-strings-in-python">How to Work With Strings in Python</h2>
<p>You've already seen examples of strings in the previous sections – but there is a lot more that you need to learn about strings.</p>
<p>In Python, anything enclosed within a set of single, double, or triple quotes is a string. These are sequences of bytes representing Unicode characters.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book = <span class="hljs-string">'Dracula'</span>
    author = <span class="hljs-string">"Bram Stoker"</span>

    print(<span class="hljs-string">'Title:'</span>, book)
    print(<span class="hljs-string">'Author:'</span>, author)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Title: Dracula</span>
<span class="hljs-comment"># Author: Bram Stoker</span>
</code></pre>
<p>Declaring a string with single or double quotes makes no difference whatsoever. But based on the scenario, you may have to choose on over the other.</p>
<p>For example, if you have an apostrophe within your sentence, you may want to use double quotes.</p>
<pre><code>def main():
    question = <span class="hljs-string">"What's your name?"</span>

    print(question)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

# What<span class="hljs-string">'s your name?</span>
</code></pre><p>The opposite can also occur. For example, when you have a direct quote within your string:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    sentence = <span class="hljs-string">'Harriet Jacobs writes, "She sat down, quivering in every limb"'</span>

    print(sentence)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Harriet Jacobs writes, "She sat down, quivering in every limb"</span>
</code></pre>
<p>You can also go for <a target="_blank" href="https://www.freecodecamp.org/news/escape-sequences-python/">escape sequences</a> if you want to, but the <a target="_blank" href="https://peps.python.org/pep-0008/#string-quotes">PEP 8 - Style Guide for Python Code</a> recommends avoiding the usage of back slashes within strings.</p>
<p>Triple quotes are a different case altogether. You can put multi-line strings within triple quotes and Python will preserve the white spaces as well.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    synopsis = <span class="hljs-string">"""Dracula comprises journal entries, letters, and telegrams written by the main characters.
It begins with Jonathan Harker, a young English lawyer, as he travels to Transylvania.
Harker plans to meet with Count Dracula, a client of his firm, in order to finalize a property transaction.
When he arrives in Transylvania, the locals react with terror after he discloses his destination: Castle Dracula.
Though this unsettles him slightly, he continues onward.
The ominous howling of wolves rings through the air as he arrives at the castle.
When Harker meets Dracula, he acknowledges that the man is pale, gaunt, and strange.
Harker becomes further concerned when, after Harker cuts himself while shaving, Dracula lunges at his throat.
Soon after, Harker is seduced by three female vampires, from whom he barely escapes.
He then learns Dracula’s secret—that he is a vampire and survives by drinking human blood.
Harker correctly assumes that he is to be the count’s next victim.
He attacks the count, but his efforts are unsuccessful.
Dracula leaves Harker trapped in the castle and then, along with 50 boxes of dirt, departs for England."""</span>

    print(<span class="hljs-string">'Synopsis:'</span>, synopsis)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Synopsis: Dracula comprises journal entries, letters, and telegrams written by the main characters.</span>
<span class="hljs-comment"># It begins with Jonathan Harker, a young English lawyer, as he travels to Transylvania.</span>
<span class="hljs-comment"># Harker plans to meet with Count Dracula, a client of his firm, in order to finalize a property transaction.</span>
<span class="hljs-comment"># When he arrives in Transylvania, the locals react with terror after he discloses his destination: Castle Dracula.</span>
<span class="hljs-comment"># Though this unsettles him slightly, he continues onward.</span>
<span class="hljs-comment"># The ominous howling of wolves rings through the air as he arrives at the castle.</span>
<span class="hljs-comment"># When Harker meets Dracula, he acknowledges that the man is pale, gaunt, and strange.</span>
<span class="hljs-comment"># Harker becomes further concerned when, after Harker cuts himself while shaving, Dracula lunges at his throat.</span>
<span class="hljs-comment"># Soon after, Harker is seduced by three female vampires, from whom he barely escapes.</span>
<span class="hljs-comment"># He then learns Dracula’s secret—that he is a vampire and survives by drinking human blood.</span>
<span class="hljs-comment"># Harker correctly assumes that he is to be the count’s next victim.</span>
<span class="hljs-comment"># He attacks the count, but his efforts are unsuccessful.</span>
<span class="hljs-comment"># Dracula leaves Harker trapped in the castle and then, along with 50 boxes of dirt, departs for England.</span>
</code></pre>
<p>So if you ever want to print out a multi line string while preserving the white spaces, go for triple quotes.</p>
<p>You can declare a triple quoted string using three single quotes but the <a target="_blank" href="https://peps.python.org/pep-0008/#string-quotes">PEP 8 - Style Guide for Python Code</a> recommends the usage of three double quotes.</p>
<p>There is a lot more to learn about strings, but I'd like to introduce you to some other sequence types in Python.</p>
<h2 id="heading-what-are-the-sequence-types-in-python">What Are the Sequence Types in Python?</h2>
<p>In Python, there are three sequence types. They are lists, tuples, and ranges. I'll start with the lists because it's probably the most utilized sequence type in Python.</p>
<h3 id="heading-lists-in-python">Lists in Python</h3>
<p>A list in Python is exactly what it sounds like: a collection of data stored sequentially on the computer's memory.</p>
<p>You can create a new list in Python by writing out its name followed by an equal sign, followed by the values to store enclosed in square brackets:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    horror_books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Carmilla'</span>, <span class="hljs-string">'The Imago Sequence'</span>]

    print(horror_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Dracula', 'Carmilla', 'The Imago Sequence']</span>
</code></pre>
<p>In this example, <code>horror_books</code> is a list of strings. But you can create lists of integers, floats, or even of mixed types.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_random_list = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">5.7</span>, <span class="hljs-string">'Carmilla'</span>]

    print(a_random_list)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Dracula', 1, 5.7, 'Carmilla']</span>
</code></pre>
<p>Though this is perfectly valid, you may find yourself creating lists of the same types more often.</p>
<p>Lists in Python are mutable. This means you can modify a list after its creation. For example, you can use the <code>pop()</code> method to get rid of the last value in a list.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    horror_books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Carmilla'</span>, <span class="hljs-string">'The Imago Sequence'</span>]

    print(horror_books.pop())
    print(horror_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># The Imago Sequence</span>
<span class="hljs-comment"># ['Dracula', 'Carmilla']</span>
</code></pre>
<p>As you can see, the <code>pop()</code> method returns the last value from the list and gets rid of it. Like <code>pop()</code> there is the <code>append()</code> method for inserting new item to the list.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    horror_books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Carmilla'</span>, <span class="hljs-string">'The Imago Sequence'</span>]

    print(horror_books)

    horror_books.append(<span class="hljs-string">'The Exorcist'</span>)

    print(horror_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Dracula', 'Carmilla', 'The Imago Sequence']</span>
<span class="hljs-comment"># ['Dracula', 'Carmilla', 'The Imago Sequence', 'The Exorcist']</span>
</code></pre>
<p>As you can see from the method name, it adds the new item at the end of the list. Given their mutable nature, lists can also be sorted.</p>
<p>Feel free to check out the following article written by my colleague <a target="_blank" href="https://www.freecodecamp.org/news/author/dionysia/">Dionysia Lemonaki</a> here on freeCodeCamp about how to sort lists in Python:</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/python-sort-how-to-sort-a-list-in-python/">https://www.freecodecamp.org/news/python-sort-how-to-sort-a-list-in-python/</a></div>
<h3 id="heading-tuples-in-python">Tuples in Python</h3>
<p>Lists are not the only sequence type in Python. The closest sibling of lists in Python are tuples.</p>
<p>You can create a new tuple in Python by writing out its name followed by an equal sign, then enclosing inside a pair of parenthesis the values you want to store.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    horror_books = (<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Carmilla'</span>, <span class="hljs-string">'The Imago Sequence'</span>)

    print(horror_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ('Dracula', 'Carmilla', 'The Imago Sequence')</span>
</code></pre>
<p>Just like lists, you can also mix and match different types of data within a single tuple as you see fit.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_random_list = (<span class="hljs-string">'Dracula'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">5.7</span>, <span class="hljs-string">'Carmilla'</span>)

    print(a_random_list)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ('Dracula', 1, 5.7, 'Carmilla')</span>
</code></pre>
<p>The most glaring dissimilarity between a list and a tuple is the fact that a tuple is immutable. So there's no popping and appending for us this time.</p>
<h3 id="heading-ranges-in-python">Ranges in Python</h3>
<p>The final sequence type that you're going to learn about in this section is a range. A range in Python is just a range of numbers.</p>
<p>You can create a range by calling the <code>range()</code> method and it'll return a range of numbers. You can call the method in a few different ways.</p>
<p>The most common is by passing a single number as a parameter. In this case, the method will treat that number as the end of the range and 0 as the start.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_range = range(<span class="hljs-number">10</span>)

    print(a_range)

    list_a_range = list(a_range)

    print(list_a_range)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># range(0, 10)</span>
<span class="hljs-comment"># [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</span>
<span class="hljs-comment"># (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)</span>
</code></pre>
<p>Printing out a range as is won't give you much information. You'll have to convert the range to a list or a tuple by either calling the <code>list()</code> or <code>tuple()</code> method.</p>
<p>Once converted, you can then print out the entire range to the console. Notice how 10 or the number passed to the <code>range()</code> method is not included in the range.</p>
<p>The second way of calling the method is by supplying both the starting and ending numbers for the range.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_range = range(<span class="hljs-number">5</span>, <span class="hljs-number">15</span>)

    print(a_range)

    list_a_range = list(a_range)

    print(list_a_range)

    tuple_a_range = tuple(a_range)

    print(tuple_a_range)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># range(5, 15)</span>
<span class="hljs-comment"># [5, 6, 7, 8, 9, 10, 11, 12, 13, 14]</span>
<span class="hljs-comment"># (5, 6, 7, 8, 9, 10, 11, 12, 13, 14)</span>
</code></pre>
<p>Once again, the number you pass as the ending for the range will not be included in the resultant range.</p>
<p>The third and final way to call the method is by also defining a step. For example, imagine you want a range comprising of all the odd numbers within 1 to 10.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_range = range(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>, <span class="hljs-number">2</span>)

    print(a_range)

    list_a_range = list(a_range)

    print(list_a_range)

    tuple_a_range = tuple(a_range)

    print(tuple_a_range)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># range(1, 10, 2)</span>
<span class="hljs-comment"># [1, 3, 5, 7, 9]</span>
<span class="hljs-comment"># (1, 3, 5, 7, 9)</span>
</code></pre>
<p>Since the value of step is 2 in this case, the range will begin with 1 but then skip every second number.</p>
<p>It may take some time to wrap your head around this concept but practicing with different step values will help.</p>
<p>Or you can read the following article written by <a target="_blank" href="https://www.freecodecamp.org/news/author/bala-priya/">Bala Priya C</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/python-range-function-explained-with-code-examples/">https://www.freecodecamp.org/news/python-range-function-explained-with-code-examples/</a></div>
<h3 id="heading-how-indexing-works-in-python">How Indexing Works in Python</h3>
<p>One of the most important concepts regarding sequence types that you need to understand is indexing.</p>
<p>You see, each element in a sequence has a number attached to it that expresses its position in the list called an index. These indices are 0 based.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/horror-books-list.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This diagram represents our list of horror books. The index of the first book is 0 – this means that the first element is at the 0th place.</p>
<p>The second one is at the 1st place and the third one is at the 2nd place. This zero-based indexing is may seem confusing at first but you'll get the hang of it.</p>
<p>The most basic usage of a index is to access its corresponding value from the sequence.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    horror_books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Carmilla'</span>, <span class="hljs-string">'The Imago Sequence'</span>]

    print(horror_books[<span class="hljs-number">0</span>])
    print(horror_books[<span class="hljs-number">1</span>])
    print(horror_books[<span class="hljs-number">2</span>])


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula</span>
<span class="hljs-comment"># Carmilla</span>
<span class="hljs-comment"># The Imago Sequence</span>
</code></pre>
<p>You can also use negative numbers as indices but in that case the counting will start from the end.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Frankenstein'</span>, <span class="hljs-string">'The Omen'</span>, <span class="hljs-string">'The Exorcist'</span>, <span class="hljs-string">'The Legend of Sleepy Hollow'</span>,
             <span class="hljs-string">'And Then There Were None'</span>, <span class="hljs-string">'The ABC Murders'</span>, <span class="hljs-string">'The Valley of Fear'</span>]

    print(books[<span class="hljs-number">0</span>])

    print(books[<span class="hljs-number">1</span>])
    print(books[<span class="hljs-number">-1</span>])

    print(books[<span class="hljs-number">2</span>])
    print(books[<span class="hljs-number">-2</span>])


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Dracula</span>

<span class="hljs-comment"># Frankenstein</span>
<span class="hljs-comment"># The Valley of Fear</span>

<span class="hljs-comment"># The Omen</span>
<span class="hljs-comment"># The ABC Murders</span>
</code></pre>
<p>The 0th element in a list will always be the first one. Now if you access the element on the 1st position you get "Frankenstein".</p>
<p>But if you try to access the element on the -1st position, you get "The Valley of Fear" because that's the second item in reverse.</p>
<p>The element on the 2nd position is "The Omen" but the element at the -2nd position is "The ABC Murders" because that's the third item in reverse.</p>
<p>If you're finding it hard to wrap your head around, imagine the list like a clock.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/list-clock.svg" alt="Image" width="600" height="400" loading="lazy">
<em>Zero-based indexing represented as a circular diagram like a clock</em></p>
<p>Here the outer number is the negative index and the inner number is the positive index. If you try to match the outputs against this imaginary clock, it should be easier to understand.</p>
<h2 id="heading-what-are-the-iterable-types-and-how-to-use-them-for-loops-in-python">What Are the Iterable Types and How to Use them for Loops in Python</h2>
<p>So far you've learned about creating collections of data and accessing them one by one. That's cool but there is something cooler.</p>
<p>Imagine you have a list or some other type of that contains a bunch of numbers.</p>
<p>Now you want to multiply each number in that list by two, insert the multiplied numbers in a new list, and print out the list on the terminal.</p>
<p>This is an excellent use case for the <code>for</code> statement in Python. Let's begin by first iterating through each number in a given list.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    random_numbers = [<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, <span class="hljs-number">12</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">54</span>, <span class="hljs-number">8</span>, <span class="hljs-number">100</span>, <span class="hljs-number">55</span>, <span class="hljs-number">60</span>, <span class="hljs-number">70</span>, <span class="hljs-number">85</span>]

    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> random_numbers:
        print(number)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 6</span>
<span class="hljs-comment"># 1</span>
<span class="hljs-comment"># 3</span>
<span class="hljs-comment"># 8</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 9</span>
<span class="hljs-comment"># 12</span>
<span class="hljs-comment"># 3</span>
<span class="hljs-comment"># 4</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 54</span>
<span class="hljs-comment"># 8</span>
<span class="hljs-comment"># 100</span>
<span class="hljs-comment"># 55</span>
<span class="hljs-comment"># 60</span>
<span class="hljs-comment"># 70</span>
<span class="hljs-comment"># 85</span>
</code></pre>
<p>You start by writing out the word <code>for</code> followed by a variable name. I've used <code>number</code> but you can use anything that makes sense to you.</p>
<p>Although you write it as <code>for number</code>, Python reads it as <code>for each number</code> and wonders where are these numbers staying?</p>
<p>That's when you say <code>in</code> followed by the name of the sequence, <code>random_numbers</code> in this case.</p>
<p>Now Python understands that you want to do something with each number in the <code>random_numbers</code> sequence, but what?</p>
<p>That's what you have to write out after the colon and be very careful about the indentation. Anything indented one level after the for loop declaration is considered the loop body.</p>
<p>Inside the for loop you can write whatever you want to do with the current value of the <code>number</code> variable.</p>
<p>Since there are 17 numbers in the sequence, the loop will run 17 times and each time it'll have a new value.</p>
<p>It'll start at index 0 which has the value of 6 and go through index 1, 2, 3, 4, 5, and so on. </p>
<p>On each iteration, it'll save the value of the index it's currently working on inside the <code>number</code> variable and print it out. Hence you get the long list of numbers.</p>
<p>Instead of printing out the original value, you can multiply it by 2 and print out the resultant value instead.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    random_numbers = [<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, <span class="hljs-number">12</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">54</span>, <span class="hljs-number">8</span>, <span class="hljs-number">100</span>, <span class="hljs-number">55</span>, <span class="hljs-number">60</span>, <span class="hljs-number">70</span>, <span class="hljs-number">85</span>]

    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> random_numbers:
        print(number * <span class="hljs-number">2</span>)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 12</span>
<span class="hljs-comment"># 2</span>
<span class="hljs-comment"># 6</span>
<span class="hljs-comment"># 16</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 18</span>
<span class="hljs-comment"># 24</span>
<span class="hljs-comment"># 6</span>
<span class="hljs-comment"># 8</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 108</span>
<span class="hljs-comment"># 16</span>
<span class="hljs-comment"># 200</span>
<span class="hljs-comment"># 110</span>
<span class="hljs-comment"># 120</span>
<span class="hljs-comment"># 140</span>
<span class="hljs-comment"># 170</span>
</code></pre>
<p>Now you're getting the multiplied values. The final task is to insert these multiplied values in a new list and print out the new list itself.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    random_numbers = [<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, <span class="hljs-number">12</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">54</span>, <span class="hljs-number">8</span>, <span class="hljs-number">100</span>, <span class="hljs-number">55</span>, <span class="hljs-number">60</span>, <span class="hljs-number">70</span>, <span class="hljs-number">85</span>]
    multiplied_random_numbers = []

    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> random_numbers:
        multiplied_random_numbers.append(number * <span class="hljs-number">2</span>)

    print(multiplied_random_numbers)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># [12, 2, 6, 16, 0, 18, 24, 6, 8, 0, 108, 16, 200, 110, 120, 140, 170]</span>
</code></pre>
<p>For that you'll need an empty list. Then, after multiplying the number, you can simply call the <code>append()</code> method on the new list and pass the multiplied value.</p>
<p>Finally, make sure that you're putting the print statement outside of the loop body otherwise you'll end up printing out the list 17 times.</p>
<p>The <code>for</code> loop works with all the sequence types and any iterable type in the Python language. What is an iterable type, I hear you ask.</p>
<p>Well, any object that has the <code>__iter__()</code> method is considered an iterable in Python.</p>
<p>You can call the <code>dir()</code> function on any object to list out all its methods and properties. Take the <code>random_numbers</code> list as an example.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    random_numbers = [<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, <span class="hljs-number">12</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">0</span>, <span class="hljs-number">54</span>, <span class="hljs-number">8</span>, <span class="hljs-number">100</span>, <span class="hljs-number">55</span>, <span class="hljs-number">60</span>, <span class="hljs-number">70</span>, <span class="hljs-number">85</span>]

    print(dir(random_numbers))

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']</span>
</code></pre>
<p>You can see some familiar methods such as <code>append</code>, <code>count</code>, and <code>index</code> but most importantly it has the <code>__iter__</code> method.</p>
<p>As you keep working in Python you'll eventually remember the types supported by the <code>for</code> loop but you can always use the <code>dir()</code> method on a object to find out.</p>
<h2 id="heading-how-to-use-while-loops-in-python">How to Use While Loops in Python</h2>
<p>There is another type of loop in Python known as the <code>while</code> loop. Unlike <code>for</code>, a <code>while</code> loop can execute a statement as long as a given condition evaluates to <code>true</code>.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    number = <span class="hljs-number">1</span>
    <span class="hljs-keyword">while</span> number &lt; <span class="hljs-number">11</span>:
        print(number)
        number += <span class="hljs-number">1</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 1</span>
<span class="hljs-comment"># 2</span>
<span class="hljs-comment"># 3</span>
<span class="hljs-comment"># 4</span>
<span class="hljs-comment"># 5</span>
<span class="hljs-comment"># 6</span>
<span class="hljs-comment"># 7</span>
<span class="hljs-comment"># 8</span>
<span class="hljs-comment"># 9</span>
<span class="hljs-comment"># 10</span>
</code></pre>
<p>Here you have a variable <code>number</code> with the value <code>11</code> and a <code>while</code> loop that prints out the value of number, then increases it by 1.</p>
<p>A <code>while</code> loop starts by writing out <code>while</code> followed by the condition. Then you write the loop body starting from the next line after the colon.</p>
<p><code>for</code> loops are useful when you're trying to access every element inside an iterable. <code>while</code> loops are useful when you want to repeat the same set of instructions an arbitrary number of times.</p>
<p>The line <code>number += 1</code> is another way to write <code>number = number + 1</code> and it's very commonly used by programmers across different programming languages.</p>
<h2 id="heading-how-to-write-nested-loops-in-python">How to Write Nested Loops in Python</h2>
<p>You can also nest one loop inside another. For example, look at the following code that prints out multiplication tables:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>):
        print()
        <span class="hljs-keyword">for</span> y <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">11</span>):
            print(<span class="hljs-string">f"<span class="hljs-subst">{x}</span> x <span class="hljs-subst">{y}</span> = <span class="hljs-subst">{x * y}</span>"</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment">#</span>
<span class="hljs-comment"># 1 x 1 = 1</span>
<span class="hljs-comment"># 1 x 2 = 2</span>
<span class="hljs-comment"># 1 x 3 = 3</span>
<span class="hljs-comment"># 1 x 4 = 4</span>
<span class="hljs-comment"># 1 x 5 = 5</span>
<span class="hljs-comment"># 1 x 6 = 6</span>
<span class="hljs-comment"># 1 x 7 = 7</span>
<span class="hljs-comment"># 1 x 8 = 8</span>
<span class="hljs-comment"># 1 x 9 = 9</span>
<span class="hljs-comment"># 1 x 10 = 10</span>
<span class="hljs-comment">#</span>
<span class="hljs-comment"># 2 x 1 = 2</span>
<span class="hljs-comment"># 2 x 2 = 4</span>
<span class="hljs-comment"># 2 x 3 = 6</span>
<span class="hljs-comment"># 2 x 4 = 8</span>
<span class="hljs-comment"># 2 x 5 = 10</span>
<span class="hljs-comment"># 2 x 6 = 12</span>
<span class="hljs-comment"># 2 x 7 = 14</span>
<span class="hljs-comment"># 2 x 8 = 16</span>
<span class="hljs-comment"># 2 x 9 = 18</span>
<span class="hljs-comment"># 2 x 10 = 20</span>
<span class="hljs-comment">#</span>
<span class="hljs-comment"># 3 x 1 = 3</span>
<span class="hljs-comment"># 3 x 2 = 6</span>
<span class="hljs-comment"># 3 x 3 = 9</span>
<span class="hljs-comment"># 3 x 4 = 12</span>
<span class="hljs-comment"># 3 x 5 = 15</span>
<span class="hljs-comment"># 3 x 6 = 18</span>
<span class="hljs-comment"># 3 x 7 = 21</span>
<span class="hljs-comment"># 3 x 8 = 24</span>
<span class="hljs-comment"># 3 x 9 = 27</span>
<span class="hljs-comment"># 3 x 10 = 30</span>
<span class="hljs-comment">#</span>
<span class="hljs-comment"># 4 x 1 = 4</span>
<span class="hljs-comment"># 4 x 2 = 8</span>
<span class="hljs-comment"># 4 x 3 = 12</span>
<span class="hljs-comment"># 4 x 4 = 16</span>
<span class="hljs-comment"># 4 x 5 = 20</span>
<span class="hljs-comment"># 4 x 6 = 24</span>
<span class="hljs-comment"># 4 x 7 = 28</span>
<span class="hljs-comment"># 4 x 8 = 32</span>
<span class="hljs-comment"># 4 x 9 = 36</span>
<span class="hljs-comment"># 4 x 10 = 40</span>
<span class="hljs-comment">#</span>
<span class="hljs-comment"># 5 x 1 = 5</span>
<span class="hljs-comment"># 5 x 2 = 10</span>
<span class="hljs-comment"># 5 x 3 = 15</span>
<span class="hljs-comment"># 5 x 4 = 20</span>
<span class="hljs-comment"># 5 x 5 = 25</span>
<span class="hljs-comment"># 5 x 6 = 30</span>
<span class="hljs-comment"># 5 x 7 = 35</span>
<span class="hljs-comment"># 5 x 8 = 40</span>
<span class="hljs-comment"># 5 x 9 = 45</span>
<span class="hljs-comment"># 5 x 10 = 50</span>
</code></pre>
<p>To be honest, this is a very simple bit of code that makes use of a lot of the things you've already learned in this handbook.</p>
<p>To create a multiplication table we need two operands: one remains constant for the entire table and the other increases by 1 until it reaches 10. </p>
<p>Here, <code>x</code> represents the left operand or the constant one and <code>y</code> represents the right operand or the variable one.</p>
<p>The first loop iterates through a range of 1 to 5 and the second loop iterates through a range of 1 to 10.</p>
<p>Since the ending number of a range is exclusive, you need to put a number that is 1 higher than the desired ending number.</p>
<p>First the Python interpreter encounters the outer loop and starts executing it. While inside that loop, the value of <code>x</code> is 1.</p>
<p>The interpreter then encounters the inner loop and starts executing that. While inside the inner loop, the value of <code>x</code> remains 1 but the value of <code>y</code> increases in each iteration.</p>
<p>The inner loop is the body of the outer loop in this case, so the first iteration of the outer loop lasts until the inner loop finishes.</p>
<p>After finishing 10 iterations of the inner loop, the interpreter comes back to the outer loop and starts executing it once again.</p>
<p>This time the value of <code>x</code> becomes 2 since that's what comes next in the range.</p>
<p>Just like that, the outer loop executes 5 times and the inner loop executes 10 times for each of those iterations.</p>
<p>Like a lot of other concepts, wrapping your head around nested loops can be difficult, but practice will make things easier.</p>
<p>I'd suggest you go ahead and implement this program using <code>while</code> loops to test your understanding.</p>
<p>You can also take the two numbers from the user and print the multiplication table within that range.</p>
<p>For example, if the user puts 5 and 10 as inputs, then you'll print out the multiplication tables of all the numbers from 5 to 10.</p>
<p>You can nest loops to even deeper levels, but going deeper than two loops may cause performance issues so be careful with that.</p>
<h2 id="heading-what-are-some-common-sequence-type-operations-in-python">What Are Some Common Sequence Type Operations in Python?</h2>
<p>Assuming you remember the text sequence type (strings), you're now familiar with the four most popular Python sequence types.</p>
<p>So I think it's time for you to learn some common operations that you can perform on them. Let's begin, shall we?</p>
<h3 id="heading-how-to-use-the-in-operator-in-python">How to Use the <code>in</code> Operator in Python</h3>
<p>The <code>in</code> operator is the most common way of checking for any object's existence. For example, assume that you have a string and you want to check if it contains the word "red" or not.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    a_string = <span class="hljs-string">'Little Red Riding-Hood comes to me one Christmas Eve to give me information of the cruelty and '</span> \
               <span class="hljs-string">'treachery of that dissembling Wolf who ate her grandmother. '</span>

    print(<span class="hljs-string">'Red'</span> <span class="hljs-keyword">in</span> a_string)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># True</span>
</code></pre>
<p>It's literally like asking Python, if the word <code>Red</code> is <code>in</code> the <code>a_string</code> variable. And Python will give you either <code>True</code> or <code>False</code> as an answer.</p>
<p>The <code>in</code> operator is not exclusive to strings. You can actually use it on any other collection type such as lists, tuples, and ranges.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Frankenstein'</span>, <span class="hljs-string">'The Omen'</span>, <span class="hljs-string">'The Exorcist'</span>, <span class="hljs-string">'The Legend of Sleepy Hollow'</span>]
    movies = (<span class="hljs-string">'A Christmas Carol'</span>, <span class="hljs-string">'The Sea Beast'</span>, <span class="hljs-string">'Enchanted'</span>, <span class="hljs-string">'Pinocchio'</span>, <span class="hljs-string">'The Addams Family'</span>)
    numbers = range(<span class="hljs-number">10</span>)

    print(<span class="hljs-string">'A Christmas Carol'</span> <span class="hljs-keyword">in</span> books)
    print(<span class="hljs-string">'Enchanted'</span> <span class="hljs-keyword">in</span> movies)
    print(<span class="hljs-number">5</span> <span class="hljs-keyword">in</span> numbers)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># False</span>
<span class="hljs-comment"># True</span>
<span class="hljs-comment"># True</span>
</code></pre>
<p>A Christmas Carol doesn't exist in the <code>books</code> list so it's a <code>False</code> statement. The other two statements are right, so they're <code>True</code>.</p>
<p>You may also want to find out about the absence of an object. For that, you can use the <code>not</code> operator in conjunction with the <code>in</code> operator.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Frankenstein'</span>, <span class="hljs-string">'The Omen'</span>, <span class="hljs-string">'The Exorcist'</span>, <span class="hljs-string">'The Legend of Sleepy Hollow'</span>]
    movies = (<span class="hljs-string">'A Christmas Carol'</span>, <span class="hljs-string">'The Sea Beast'</span>, <span class="hljs-string">'Enchanted'</span>, <span class="hljs-string">'Pinocchio'</span>, <span class="hljs-string">'The Addams Family'</span>)
    numbers = range(<span class="hljs-number">10</span>)

    print(<span class="hljs-string">'A Christmas Carol'</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> books)
    print(<span class="hljs-string">'Enchanted'</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> movies)
    print(<span class="hljs-number">15</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> numbers)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># True</span>
<span class="hljs-comment"># False</span>
<span class="hljs-comment"># True</span>
</code></pre>
<p>A Christmas Carol doesn't exist in the <code>books</code> list, so the first statement evaluates to <code>true</code>. The second one evaluates to false because Enchanted is present in the <code>movies</code> list.</p>
<p>The last one is self explanatory at this point. The <code>in</code> and <code>not in</code> operators come in very handy when working with conditional statements.</p>
<h3 id="heading-how-to-use-the-and-operators-with-sequence-types-in-python">How to Use the <code>+</code> and <code>*</code> Operators with Sequence Types in Python</h3>
<p>You've already learned about <code>+</code> and <code>*</code> as arithmetic operators – but in the case of sequence types, they play a very different role.</p>
<p>The <code>+</code> operator lets you merge two sequences together.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Frankenstein'</span>, <span class="hljs-string">'The Omen'</span>, <span class="hljs-string">'The Exorcist'</span>, <span class="hljs-string">'The Legend of Sleepy Hollow'</span>]
    more_books = [<span class="hljs-string">'And Then There Were None'</span>, <span class="hljs-string">'The ABC Murders'</span>, <span class="hljs-string">'The Valley of Fear'</span>, <span class="hljs-string">'The Hound of the Baskervilles'</span>, <span class="hljs-string">'The Chestnut Man'</span>]


    print(books + more_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Dracula', 'Frankenstein', 'The Omen', 'The Exorcist', 'The Legend of Sleepy Hollow', 'And Then There Were None', 'The ABC Murders', 'The Valley of Fear', 'The Hound of the Baskervilles', 'The Chestnut Man']</span>
</code></pre>
<p>As you can see, the operator has appended the content of the <code>books</code> list to the content of the <code>more_books</code> list.</p>
<p>The <code>*</code> operator, on the other hand, makes multiple copies of a given sequence.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    books = [<span class="hljs-string">'Dracula'</span>, <span class="hljs-string">'Frankenstein'</span>, <span class="hljs-string">'The Omen'</span>, <span class="hljs-string">'The Exorcist'</span>, <span class="hljs-string">'The Legend of Sleepy Hollow'</span>]


    print(books * <span class="hljs-number">2</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Dracula', 'Frankenstein', 'The Omen', 'The Exorcist', 'The Legend of Sleepy Hollow', 'Dracula', 'Frankenstein', 'The Omen', 'The Exorcist', 'The Legend of Sleepy Hollow']</span>
</code></pre>
<p>So multiplying the <code>books</code> list by 2 gives us all the 5 books in the list twice. These operators work the same for tuples, strings, ranges or any other sequence types.</p>
<h3 id="heading-how-to-use-the-len-min-and-max-functions-in-python">How to Use the <code>len()</code>, <code>min()</code>, and <code>max()</code> Functions in Python</h3>
<p>The <code>len()</code> function can return the length of a given sequence. And the <code>min()</code> and <code>max()</code> functions can return the minimum and maximum value in a given sequence, respectively.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    random_numbers = [<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">0</span>]


    print(len(random_numbers))
    print(min(random_numbers))
    print(max(random_numbers))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 5</span>
<span class="hljs-comment"># 0</span>
<span class="hljs-comment"># 8</span>
</code></pre>
<p>Since there are 5 elements in the list, 5 is the output from the <code>len()</code> function call. </p>
<p>The smallest value in the list is 0 and the largest value is 8 which are the outputs from the <code>min()</code> and <code>max()</code> function calls, respectively.</p>
<p>Depending on the type of programs you end up writing in the future, these three functions can prove to be some of the most useful ones.</p>
<h2 id="heading-what-are-some-string-type-operations-in-python">What Are Some String Type Operations in Python?</h2>
<p>In the previous section, you've learned about some common operations that you can perform on any sequence type including strings.</p>
<p>However, the text sequence type aka strings have some special operations available to them.</p>
<p>In this chapter I'll introduce you to some of the most common string methods. Keep in mind that this is not a definitive list.</p>
<p>Although each of the methods I'm going to teach you performs a different task, they have one thing in common. None of them modifies a given string variable in place, but rather returns a new, modified copy.</p>
<p>If you want to learn about all the available string methods, feel free to consult the official Python documentation.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://docs.python.org/3/library/stdtypes.html#string-methods">https://docs.python.org/3/library/stdtypes.html#string-methods</a></div>
<p>Also remember it's not a matter of just going through each method and memorizing their usage.</p>
<p>It's about knowing what works best in a given scenario and coming up with clever solutions. And that requires practice.</p>
<h3 id="heading-how-to-capitalize-strings-in-python">How to Capitalize Strings in Python</h3>
<p>The first method you're going to learn is called <code>capitalize()</code> and it does what it sounds like.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    country_name = <span class="hljs-string">'bangladesh'</span>

    print(country_name.capitalize())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Bangladesh</span>
</code></pre>
<p>As you can see from the code snippet above, the <code>capitalize()</code> method turns the first letter of the word to a capital letter.</p>
<p>This is simple, but let's try this on a string with multiple words in it – a sentence perhaps.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'the house of silk'</span>

    print(book_name.capitalize())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># The house of silk</span>
</code></pre>
<p>Although the method did its job, there is slight problem. Depending on what you're trying to achieve, you may expect the first letter of each word to be capitalized.</p>
<p>That's where the <code>title()</code> method comes in. This method returns a title cased version of a given string.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'the house of silk'</span>

    print(book_name.title())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># The House Of Silk</span>
</code></pre>
<p>But there is still an issue. Take the following string with apostrophes for example.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">"alice's adventures in wonderland"</span>

    print(book_name.title())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Alice'S Adventures In Wonderland</span>
</code></pre>
<p>As you can see, the <code>title()</code> method treats the <code>s</code> following the apostrophe as a separate word and capitalizes it.</p>
<p>Regarding this issue, the <a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#str.title">official documentation</a> states:</p>
<blockquote>
<p>The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries.</p>
</blockquote>
<p>The <code>capwords()</code> helper function can solve this issue. This function breaks the string into multiple words based on the spaces between them, capitalizes the words, joins them back into a string and returns that to the user.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> string <span class="hljs-keyword">import</span> capwords


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">"alice's adventures in wonderland"</span>

    print(capwords(book_name))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Alice's Adventures In Wonderland</span>
</code></pre>
<p>Pay attention to the <code>import</code> statement at the top. The <code>capwords()</code> function is not a method within the string type but a function that resides inside the <code>string</code> module.</p>
<p>You'll learn about modules and imports in more details later on. For now, just roll with it. Although the function uses spaces to split words, you can overwrite it.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> string <span class="hljs-keyword">import</span> capwords


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    address = <span class="hljs-string">'house 42, road 02, wonderland'</span>

    print(capwords(address, <span class="hljs-string">', '</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># House 42, Road 02, Wonderland</span>
</code></pre>
<p>As you can see, in this case the string has multiple parts divided by a comma followed by a space.</p>
<p>The <code>capwords()</code> function can take a custom delimiter as its second parameter. You can pass any string as the delimiter.</p>
<p>Finally, there is the <code>istitle()</code> method that can check whether a given string is in title case or not.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'hearts in atlantis'</span>

    print(<span class="hljs-string">f'Is "<span class="hljs-subst">{book_name}</span>" in title case? <span class="hljs-subst">{book_name.istitle()}</span>'</span>)
    print(<span class="hljs-string">f'Is "<span class="hljs-subst">{book_name.title()}</span>" in title case? <span class="hljs-subst">{book_name.title().istitle()}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Is "hearts in atlantis" in title case? False</span>
<span class="hljs-comment"># Is "Hearts In Atlantis" in title case? True</span>
</code></pre>
<p>However, keep in mind that the <code>istitle()</code> method doesn't work with the <code>capwords()</code> helper function.</p>
<h3 id="heading-how-to-convert-strings-to-lower-case-or-upper-case-in-python">How to Convert Strings to Lower Case or Upper Case in Python</h3>
<p>Apart from capitalization, you may want to convert an entire string to upper case or lower case. You can do that by using the <code>upper()</code> and <code>lower()</code> methods in Python.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'moriarty'</span>

    print(book_name.upper())

    another_book_name = <span class="hljs-string">'DRACULA'</span>

    print(another_book_name.lower())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># MORIARTY</span>
<span class="hljs-comment"># dracula</span>
</code></pre>
<p>There are also the <code>isupper()</code> and <code>islower()</code> methods to check whether a given string is already in either of the letter cases or not.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'moriarty'</span>

    print(book_name)
    print(<span class="hljs-string">f'Is <span class="hljs-subst">{book_name}</span> in upper case? <span class="hljs-subst">{book_name.isupper()}</span>'</span>)
    print(<span class="hljs-string">f'Is <span class="hljs-subst">{book_name}</span> in lower case? <span class="hljs-subst">{book_name.islower()}</span>'</span>)

    another_book_name = <span class="hljs-string">'DRACULA'</span>

    print(another_book_name)
    print(<span class="hljs-string">f'Is <span class="hljs-subst">{another_book_name}</span> in upper case? <span class="hljs-subst">{another_book_name.islower()}</span>'</span>)
    print(<span class="hljs-string">f'Is <span class="hljs-subst">{another_book_name}</span> in lower case? <span class="hljs-subst">{another_book_name.isupper()}</span>'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># moriarty</span>
<span class="hljs-comment"># Is moriarty in upper case? False</span>
<span class="hljs-comment"># Is moriarty in lower case? True</span>
<span class="hljs-comment"># DRACULA</span>
<span class="hljs-comment"># Is DRACULA in upper case? True</span>
<span class="hljs-comment"># Is DRACULA in lower case? False</span>
</code></pre>
<p>There is one last method called <code>casefold()</code> which is kind of a more aggressive version of the <code>lower()</code> method.</p>
<p>According to the <a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#str.casefold">official documentation</a>:</p>
<blockquote>
<p>Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".</p>
</blockquote>
<p>The usage of this method is identical to the <code>lower()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'DRACULA'</span>

    print(book_name.casefold())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># dracula</span>
</code></pre>
<p>These three methods are fine and dandy, but what if you don't want to use any of these particular methods and just want to switch the case of a given string?</p>
<p>The <code>swapcase()</code> method can do just that.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    book_name = <span class="hljs-string">'HEARTS IN ATLANTIS'</span>

    print(book_name.swapcase())


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># hearts in atlantis</span>
</code></pre>
<p>As you can see, the method has converted the book name into lower case from upper case.</p>
<h3 id="heading-how-to-count-the-number-of-occurrences-of-a-substring-in-a-string-in-python">How to Count the Number of Occurrences of a Substring in a String in Python</h3>
<p>If you want to find out the number of occurrences of a substring within a string, you can use the <code>count()</code> method in Python.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    paragraph = <span class="hljs-string">'''At three in the morning the chief Sussex detective, obeying the urgent call from Sergeant Wilson of 
    Birlstone, arrived from headquarters in a light dog-cart behind a breathless trotter. By the five-forty train in 
    the morning he had sent his message to Scotland Yard, and he was at the Birlstone station at twelve o'clock to 
    welcome us. White Mason was a quiet, comfortable-looking person in a loose tweed suit, with a clean-shaved, 
    ruddy face, a stoutish body, and powerful bandy legs adorned with gaiters, looking like a small farmer, 
    a retired gamekeeper, or anything upon earth except a very favourable specimen of the provincial criminal 
    officer.'''</span>

    substring = <span class="hljs-string">'morning'</span>

    print(<span class="hljs-string">f'The substring "<span class="hljs-subst">{substring}</span>" shows up <span class="hljs-subst">{paragraph.count(substring)}</span> times in the paragraph.'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># The substring "morning" shows up 2 times in the paragraph.</span>
</code></pre>
<p>If you call the <code>count()</code> method without passing anything to it, the method will return the number of empty spaces in the given string.</p>
<h3 id="heading-how-to-split-and-join-strings-in-python">How to Split and Join Strings in Python</h3>
<p>You can actually break a string into a list of words or join a list of words in a string in Python.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    string = <span class="hljs-string">'Holmes was certainly not a difficult man to live with'</span>

    word_list = string.split()

    print(word_list)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Holmes', 'was', 'certainly', 'not', 'a', 'difficult', 'man', 'to', 'live', 'with']</span>
</code></pre>
<p>If you call the <code>split()</code> method without any parameters, it'll split the given string into words using the spaces as separators.</p>
<p>You can override that by passing a custom separator and also fix the number of splits you want.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    string = <span class="hljs-string">'Holmes,was,certainly,not,a,difficult,man,to,live,with'</span>

    word_list = string.split(<span class="hljs-string">','</span>, <span class="hljs-number">5</span>)

    print(word_list)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ['Holmes', 'was', 'certainly', 'not', 'a', 'difficult,man,to,live,with']</span>
</code></pre>
<p>This time I've replaced the spaces in the source string with commas. I've also overridden the default separator with a comma and fixed the number of splits to five.</p>
<p>As you can see in the output, there are five splits and the rest of the string is kept unchanged as the sixth element in the list.</p>
<p>The <code>split()</code> method is good for using with data that has been intentionally delimited. Using it with natural text with punctuation may produce unexpected results.</p>
<p>The opposite of the <code>split()</code> method is <code>join()</code> and it works on any iterator type in Python.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    word_list = [<span class="hljs-string">'Holmes'</span>, <span class="hljs-string">'was'</span>, <span class="hljs-string">'certainly'</span>, <span class="hljs-string">'not'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'difficult'</span>, <span class="hljs-string">'man'</span>, <span class="hljs-string">'to'</span>, <span class="hljs-string">'live'</span>, <span class="hljs-string">'with'</span>]
    string = <span class="hljs-string">''</span>

    string = string.join(word_list)

    print(string)

    word_list = [<span class="hljs-string">'Holmes '</span>, <span class="hljs-string">'was '</span>, <span class="hljs-string">'certainly '</span>, <span class="hljs-string">'not '</span>, <span class="hljs-string">'a '</span>, <span class="hljs-string">'difficult '</span>, <span class="hljs-string">'man '</span>, <span class="hljs-string">'to '</span>, <span class="hljs-string">'live '</span>, <span class="hljs-string">'with'</span>]
    string = <span class="hljs-string">''</span>

    string = string.join(word_list)

    print(string)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Holmeswascertainlynotadifficultmantolivewith</span>
<span class="hljs-comment"># Holmes was certainly not a difficult man to live with</span>
</code></pre>
<p>There you have it. Notice how the <code>join()</code> method didn't care about adding spaces as separator after each word in the first call.</p>
<p>So I appended a space with each word in the list and in the second call the line has become much more readable.</p>
<h2 id="heading-how-to-write-conditional-statements-in-python">How to Write Conditional Statements in Python</h2>
<p>This is where it gets interesting. In Python or in any other programming language you can make decisions based on conditions.</p>
<p>I hope you remember the <code>boolean</code> data type from a previous section – the one that can only hold <code>True</code> or <code>False</code> values.</p>
<p>Well, you can use a boolean with an <code>if</code> statement (a conditional statement) in Python to perform an action conditionally.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    number = int(input(<span class="hljs-string">'what number would you like to check?\n- '</span>))

    <span class="hljs-keyword">if</span> number % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is even."</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is odd."</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># what number would you like to check?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 10 is even.</span>
</code></pre>
<p>You start by writing out <code>if</code> followed by a condition and a colon. By condition, what I mean is a statement that evaluates to a boolean value (true or false).</p>
<p>You've been using the <code>==</code> operator since the beginning and already know that it checks whether the value on the left side of it is equal to the one in the right or not.</p>
<p>So, if you divide a given number by 2 and the remainder is 0, that's an even number – otherwise, it'll be odd.</p>
<p>You can use the <code>if...else</code> statement to choose between two different options. But, if you have multiple options to choose from, you can use the <code>if...elif...else</code> statement.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    year = int(input(<span class="hljs-string">'which year would you like to check?\n- '</span>))

    <span class="hljs-keyword">if</span> year % <span class="hljs-number">400</span> == <span class="hljs-number">0</span> <span class="hljs-keyword">and</span> year % <span class="hljs-number">100</span> == <span class="hljs-number">0</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{year}</span> is leap year."</span>)
    <span class="hljs-keyword">elif</span> year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span> <span class="hljs-keyword">and</span> year % <span class="hljs-number">100</span> != <span class="hljs-number">0</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{year}</span> is leap year."</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{year}</span> is not leap year."</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># which year would you like to check?</span>
<span class="hljs-comment"># - 2004</span>
<span class="hljs-comment"># 2004 is leap year.</span>
</code></pre>
<p>The <code>elif</code> statement usually goes after an <code>if</code> statement and before an <code>else</code> statement.</p>
<p>Think of it like "else if", so if the <code>if</code> statement fails, then the <code>elif</code> will take over. You write it exactly like a regular <code>if</code> statement.</p>
<p>Another new thing in this example is the <code>and</code> operator. It's one of the logical operators in Python. It does what it does in real life.</p>
<p>If the expressions on both sides of the <code>and</code> statement evaluates to <code>true</code>, then the whole expression evaluates to <code>true</code>. Simple.</p>
<p>Don't worry if you do not understand the <code>and</code> operator in detail at the moment. You'll learn about it and its siblings in the very next section.</p>
<p>Another thing you need to understand is that these <code>if</code> statements are just regular statements so you can do pretty much anything inside them.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    number = int(input(<span class="hljs-string">'what number would you like to check?\n- '</span>))

    is_not_prime = <span class="hljs-literal">False</span>

    <span class="hljs-keyword">if</span> number == <span class="hljs-number">1</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is not a prime number."</span>)
    <span class="hljs-keyword">elif</span> number &gt; <span class="hljs-number">1</span>:
        <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> range(<span class="hljs-number">2</span>, number):
            <span class="hljs-keyword">if</span> (number % n) == <span class="hljs-number">0</span>:
                is_not_prime = <span class="hljs-literal">True</span>
                <span class="hljs-keyword">break</span>

        <span class="hljs-keyword">if</span> is_not_prime:
            print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is not a prime number."</span>)
        <span class="hljs-keyword">else</span>:
            print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is a prime number."</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># what number would you like to check?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 10 is not a prime number.</span>
</code></pre>
<p>This example is a bit more complex than what you've seen so far. So let me break it down for you. The program checks whether a given number is a prime number or not.</p>
<p>First, you take a number from the user. For a number to be prime, it has to be divisible only by 1 and itself. Since 1 is only divisible by 1, it's not a prime number.</p>
<p>Now, if the given number is larger than 1, then you'd have to divide the number with all the numbers from 2 to that particular number.</p>
<p>If the number is divisible by any of these numbers, then you'll turn the <code>is_not_prime</code> variable to <code>True</code>, and <code>break</code> the loop.</p>
<p>The <code>break</code> statement simply breaks out of a loop immediately. There is also the <code>continue</code> statement that can skip the current iteration instead of breaking out.</p>
<p>Finally, if the <code>is_not_prime</code> variable is <code>True</code> then the number is not prime, otherwise it's a prime number.</p>
<p>So as you can see, not only you can put loops inside a conditional statement but also put conditional statements inside a loop.</p>
<p>The final example that I'd like to show you is the <code>for...else</code> statement. As you can see in the example above, you have a <code>for</code> statement followed by a <code>if...else</code> statement.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    number = int(input(<span class="hljs-string">'what number would you like to check?\n- '</span>))

    <span class="hljs-keyword">if</span> number == <span class="hljs-number">1</span>:
        print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is not a prime number."</span>)
    <span class="hljs-keyword">elif</span> number &gt; <span class="hljs-number">1</span>:
        <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> range(<span class="hljs-number">2</span>, number):
            <span class="hljs-keyword">if</span> (number % n) == <span class="hljs-number">0</span>:
                print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is not a prime number."</span>)
                <span class="hljs-keyword">break</span>
        <span class="hljs-keyword">else</span>:
            print(<span class="hljs-string">f"<span class="hljs-subst">{number}</span> is a prime number."</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># what number would you like to check?</span>
<span class="hljs-comment"># - 5</span>
<span class="hljs-comment"># 5 is a prime number.</span>
</code></pre>
<p>If you put an <code>else</code> statement on the same level as a <code>for</code> statement, then Python will execute whatever you put inside that <code>else</code> block as soon as the loop has finished.</p>
<h2 id="heading-what-are-relational-and-logical-operators-in-python">What are Relational and Logical Operators in Python?</h2>
<p>In the examples above, you've seen the usage of <code>==</code> as well as the <code>and</code> operators. In this section, you'll learn about them in detail.</p>
<p>The relational operators come in handy when you want to check the relationship between two operands. There are six of these operators:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>OPERATOR</td><td>EXPLANATION</td><td>USAGE</td></tr>
</thead>
<tbody>
<tr>
<td><code>==</code></td><td>Equal To</td><td><code>5 == 5</code> gives you <code>True</code>, but <code>5 == 10</code> gives you <code>False</code></td></tr>
<tr>
<td><code>!=</code></td><td>Not Equal To</td><td><code>5 != 10</code> gives you <code>True</code>, but <code>5 != 5</code> gives you <code>False</code></td></tr>
<tr>
<td><code>&gt;</code></td><td>Greater Than</td><td><code>10 &gt; 5</code> gives you <code>True</code>, but <code>5 &gt; 10</code>gives you <code>False</code></td></tr>
<tr>
<td><code>&lt;</code></td><td>Less Than</td><td><code>5 &lt; 10</code> gives you <code>True</code>, but <code>10 &lt; 5</code> gives you <code>False</code></td></tr>
<tr>
<td><code>&gt;=</code></td><td>Greater Than or Equal</td><td><code>10 &gt;= 5</code> and <code>10 &gt;= 10</code> gives you <code>True</code>, but <code>5 &gt;= 10</code> gives you <code>False</code></td></tr>
<tr>
<td><code>&lt;=</code></td><td>Less Than or Equal</td><td><code>5 &lt;= 10</code> and <code>5 &lt;= 5</code> gives you <code>True</code>, but <code>10 &lt;= 5</code> gives you <code>False</code></td></tr>
</tbody>
</table>
</div><p>You've been using the <code>equal to</code> operator since the very beginning. The other ones you'll learn about as you keep going.</p>
<p>Apart from these, there are three logical operators in Python. They are the <code>and</code>, <code>or</code>, and <code>not</code> operators.</p>
<p>Take an RPG game, for example, where the hero has to have a level 45 or up shield and a level 48 or up sword in order to go to the next level.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    shield = int(input(<span class="hljs-string">'what is your shield level? '</span>))
    sword = int(input(<span class="hljs-string">'what is your sword level? '</span>))

    <span class="hljs-keyword">if</span> shield &gt;= <span class="hljs-number">45</span> <span class="hljs-keyword">and</span> sword &gt;= <span class="hljs-number">48</span>:
        print(<span class="hljs-string">'you shall pass!'</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">'you shall not pass!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># what is your shield level? 42</span>
<span class="hljs-comment"># what is your sword level? 52</span>
<span class="hljs-comment"># you shall not pass!</span>
</code></pre>
<p>Unless you meet both conditions, the statement will evaluate to <code>False</code>. You can have more conditions in a statement like this:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    shield = int(input(<span class="hljs-string">'what is your shield level? '</span>))
    sword = int(input(<span class="hljs-string">'what is your sword level? '</span>))
    armor = int(input(<span class="hljs-string">'what is your armor level? '</span>))

    <span class="hljs-keyword">if</span> shield &gt;= <span class="hljs-number">45</span> <span class="hljs-keyword">and</span> sword &gt;= <span class="hljs-number">48</span> <span class="hljs-keyword">and</span> armor &gt;= <span class="hljs-number">25</span>:
        print(<span class="hljs-string">'you shall pass!'</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">'you shall not pass!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># what is your shield level? 45</span>
<span class="hljs-comment"># what is your sword level? 50</span>
<span class="hljs-comment"># what is your armor level? 10</span>
<span class="hljs-comment"># you shall not pass!</span>
</code></pre>
<p>The <code>or</code> operator, on the other hand, is a bit more forgiving. If any of the given conditions evaluates true, than the entire statement will evaluate to true.</p>
<p>For example in another horror game, you can only get into The Castle Dracula if you are more than 500,000 years old or legally dead.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    age = <span class="hljs-number">10</span>_000
    is_legally_dead = <span class="hljs-literal">True</span>

    <span class="hljs-keyword">if</span> is_legally_dead <span class="hljs-keyword">or</span> age &gt; <span class="hljs-number">500</span>_000:
        print(<span class="hljs-string">'you shall pass!'</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">'you shall not pass!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># you shall pass!</span>
</code></pre>
<p>You can mix the <code>and</code> and <code>or</code> operators together. I won't list out all the possible combinations of these operators, but as you keep working with Python, you'll get to use a lot of them.</p>
<p>The last logical operator that I'd like to discuss is the <code>not</code> operator. This operator takes only one operand and returns the opposite value.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(<span class="hljs-string">'not True ='</span>, <span class="hljs-keyword">not</span> <span class="hljs-literal">True</span>)
    print(<span class="hljs-string">'not False ='</span>, <span class="hljs-keyword">not</span> <span class="hljs-literal">False</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># not True = False</span>
<span class="hljs-comment"># not False = True</span>
</code></pre>
<p>For example, if you change the rules of the horror game we talked about in the previous example and make is so that only people who are over 500,000 years old and not Van Helsing can enter the castle.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    age = <span class="hljs-number">800</span>_000
    is_van_helsing = <span class="hljs-literal">True</span>

    <span class="hljs-keyword">if</span> age &gt; <span class="hljs-number">500</span>_000 <span class="hljs-keyword">and</span> <span class="hljs-keyword">not</span> is_van_helsing:
        print(<span class="hljs-string">'you shall pass!'</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">'you shall not pass!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># you shall not pass!</span>
</code></pre>
<p>Since we've been talking about conditional statements and some of the operators associated with them, I'd like to introduce you to another statement first introduced in Python 3.10, the <code>match...case</code> statement.</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/python-switch-statement-switch-case-example/">https://www.freecodecamp.org/news/python-switch-statement-switch-case-example/</a></div>
<p>Since my colleague <a target="_blank" href="https://www.freecodecamp.org/news/author/kolade/">Kolade Chris</a> has written such a nice article on the topic, I'll not repeat that here. Feel free to check it out at your leisure.</p>
<h2 id="heading-what-are-assignment-operators-in-python">What Are Assignment Operators in Python?</h2>
<p>You've already encountered the simple assignment operator which is the <code>=</code> sign you used to assign a value to a variable.</p>
<p>Now there are a few variations to this operator that you can use to perform arithmetic and bitwise operations while also assigning a value.</p>
<p>Bitwise operations are a little out of the scope of this book, so I'll stick to the arithmetic operations.</p>
<p>There are seven different assignment operators in Python. Since you've already learned about the simple one, I'll discuss the other six in the following table.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>OPERATOR</td><td>USAGE</td><td>EQUIVALENT TO</td></tr>
</thead>
<tbody>
<tr>
<td><code>+=</code></td><td><code>a += b</code></td><td><code>a = a + b</code></td></tr>
<tr>
<td><code>-=</code></td><td><code>a -= b</code></td><td><code>a = a - b</code></td></tr>
<tr>
<td><code>*=</code></td><td><code>a *= b</code></td><td><code>a = a * b</code></td></tr>
<tr>
<td><code>/=</code></td><td><code>a /= b</code></td><td><code>a = a / b</code></td></tr>
<tr>
<td><code>%=</code></td><td><code>a %= b</code></td><td><code>a = a % b</code></td></tr>
<tr>
<td><code>**=</code></td><td><code>a **= b</code></td><td><code>a = a ** b</code></td></tr>
</tbody>
</table>
</div><p>These operators are not exclusive to Python, and in most programming resources, you'll find these in a much earlier chapter.</p>
<p>But I wanted to wait until you've learned about taking input from the user, working with ranges, and looping through them before introducting them here.</p>
<p>Assume that you want to write a program that calculates the sum of all the numbers within a given range.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    start = int(input(<span class="hljs-string">'which number do you want to start from?\n- '</span>))
    end = int(input(<span class="hljs-string">'which number do you want to stop at?\n- '</span>))

    total = <span class="hljs-number">0</span>

    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> range(start, end + <span class="hljs-number">1</span>):
        total += number

    print(<span class="hljs-string">f"the sum of the numbers between <span class="hljs-subst">{start}</span> and <span class="hljs-subst">{end}</span> is: <span class="hljs-subst">{total}</span>"</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># which number do you want to start from?</span>
<span class="hljs-comment"># - 1</span>
<span class="hljs-comment"># which number do you want to stop at?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># the sum of the numbers between 1 and 10 is: 55</span>
</code></pre>
<p>I hope you remember that the ending number of a <code>range()</code> function call is exclusive. So I had to add a <code>+1</code> with the ending number.</p>
<p>Otherwise it's a very simple range based for loop that adds each number to the <code>total</code> variable and prints it out once the loop has finished.</p>
<h2 id="heading-what-is-the-set-type-in-python">What Is the Set Type in Python?</h2>
<p>So far you've learned about a number of iterable types such as lists, tuples, and also strings. There is another one known as a set. Let's look at an example:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers = {<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-keyword">for</span> number <span class="hljs-keyword">in</span> numbers:
        print(number)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 1</span>
<span class="hljs-comment"># 2</span>
<span class="hljs-comment"># 3</span>
<span class="hljs-comment"># 4</span>
<span class="hljs-comment"># 5</span>
</code></pre>
<p>You can create a new set by putting the values between a set of curly braces. Keep in mind however, you can not create an empty set using the curly braces.</p>
<p>You'll have to use the <code>set()</code> function for that.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers = {}

    print(type(numbers))

    numbers = set()

    print(type(numbers))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># &lt;class 'dict'&gt;</span>
<span class="hljs-comment"># &lt;class 'set'&gt;</span>
</code></pre>
<p>As you can see, usage of empty curly braces creates a dictionary whereas the <code>set()</code> function creates an empty set.</p>
<p>Sets may seem similar to lists, but they are actually quite different. For starters, you can not put duplicate values in a set.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers_list = [<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-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>]

    print(numbers_list)

    numbers_set = set(numbers_list)

    print(numbers_set)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># [1, 2, 3, 4, 5, 3, 2, 4]</span>
<span class="hljs-comment"># {1, 2, 3, 4, 5}</span>
</code></pre>
<p>The list of numbers can hold duplicate values without any problem. But as soon as you create a set from that list, all the duplicate values will be gone.</p>
<p>Sets are mutable, so you can add new values to a set using the <code>add()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers = {<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>}

    numbers.add(<span class="hljs-number">500</span>)

    print(numbers)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {1, 2, 3, 4, 5, 500}</span>
</code></pre>
<p>Likewise you can use the <code>discard()</code> method to remove an item from a set or use the <code>clear()</code> method to remove all values altogether.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers = {<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>}

    numbers.discard(<span class="hljs-number">3</span>)

    print(numbers)

    numbers.clear()

    print(numbers)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {1, 2, 4, 5}</span>
<span class="hljs-comment"># set()</span>
</code></pre>
<p>Notice how an empty set shows up as <code>set()</code> instead of <code>{}</code> because the latter indicates an empty dictionary.</p>
<p>Apart from the fact that a set never contains duplicate values, there is another speciality of this type.</p>
<p>You can perform set operations such as union, intersection, complement, and  difference using sets in Python.</p>
<p>My colleague <a target="_blank" href="https://www.freecodecamp.org/news/author/estefaniacn/">Estefania Cassingena Navone</a> has written an excellent guide on sets, frozen set and all the operations that you can perform on them.</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/python-sets-detailed-visual-introduction/">https://www.freecodecamp.org/news/python-sets-detailed-visual-introduction/</a></div>
<p>Finally, if you'd like to get a definitive look at the set type, the <a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset">official documentation</a> will more than suffice.</p>
<h2 id="heading-what-is-the-mapping-type-in-python">What Is the Mapping Type in Python?</h2>
<p>You've already learned about the sequence types and set types in Python. Those are really useful for containing a bunch of data.</p>
<p>But situations where you want to store data in key value pairs are not uncommon. Take, for example, an online bookshop where you have to store the prices of the books.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    print(programming_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {'C Programming Language': 35, 'Introduction to Algorithms': 100, 'Clean Code: A Handbook of Agile Software Craftsmanship': 50}</span>
</code></pre>
<p>The variable <code>programming_books</code> here is a mapping type usually known as a dictionary. Declaring a dictionary is similar to declaring a list or tuple but you use a set of curly braces instead of square braces or parenthesis.</p>
<p>Enclosed within the braces are a bunch of key value pairs. The strings on the left side are the keys and the numbers are the values. You can access any of the keys using the <code>get()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    cpl = <span class="hljs-string">'C Programming Language'</span>
    algo = <span class="hljs-string">'Introduction to Algorithms'</span>

    print(<span class="hljs-string">f"The price of <span class="hljs-subst">{cpl}</span> is $<span class="hljs-subst">{programming_books.get(cpl)}</span>"</span>)
    print(<span class="hljs-string">f"The price of <span class="hljs-subst">{algo}</span> is $<span class="hljs-subst">{programming_books[algo]}</span>"</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># The price of C Programming Language is $35</span>
<span class="hljs-comment"># The price of Introduction to Algorithms is $100</span>
</code></pre>
<p>Alternatively, you can also use square braces like you did with lists to access a dictionary item.</p>
<p>Dictionaries are mutable which means you can add new items to them, remove or change existing items.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    key = <span class="hljs-string">'C Programming Language'</span>

    programming_books[key] = <span class="hljs-number">45</span>

    programming_books[<span class="hljs-string">'The Pragmatic Programmer'</span>] = <span class="hljs-number">32</span>

    print(programming_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {'C Programming Language': 45, 'Introduction to Algorithms': 100, 'Clean Code: A Handbook of Agile Software Craftsmanship': 50, 'The Pragmatic Programmer': 32}</span>
</code></pre>
<p>You can change an existing item by accessing the item using the square braces and assign a new value to it. The price of C Programming Language has gone up by $10.</p>
<p>If you put a nonexistent key in between the square braces, then that'll show up as a new item. The price of The Pragmatic Programmer was not in the dictionary before but now it has been added.</p>
<p>For removing an item from a dictionary, you can use the <code>popitem()</code> or the <code>pop()</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    print(programming_books.popitem())

    key = <span class="hljs-string">'C Programming Language'</span>

    print(programming_books.pop(key))

    print(programming_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ('Clean Code: A Handbook of Agile Software Craftsmanship', 50)</span>
<span class="hljs-comment"># 35</span>
<span class="hljs-comment"># {'Introduction to Algorithms': 100}</span>
</code></pre>
<p>The <code>popitem()</code> method removes the last item in the dictionary and returns that as a tuple.</p>
<p>The <code>pop()</code> method, on the other hand, returns the value for a given key and removes the pair.</p>
<p>The final <code>print()</code> function call shows that indeed two items were removed from the dictionary due to the pop calls.</p>
<p>Finally, there is the <code>clear()</code> method that wipes out all the pairs in a given dictionary in one go.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    programming_books.clear()

    print(programming_books)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {}</span>
</code></pre>
<h3 id="heading-what-are-dictionary-view-objects-in-python">What Are Dictionary View Objects in Python?</h3>
<p>So far in this section, you've seen dictionaries printed out as long comma separated lines between pairs of curly braces – but that's not very readable.</p>
<p>This is where the view objects come in handy. You can call some specific methods on dictionaries and get view objects in return.</p>
<p>The first method that I'm going to discuss is the <code>keys()</code> methods. It returns the keys of a given dictionary and you can loop over them.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    <span class="hljs-keyword">for</span> key <span class="hljs-keyword">in</span> programming_books.keys():
        print(key)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># C Programming Language</span>
<span class="hljs-comment"># Introduction to Algorithms</span>
<span class="hljs-comment"># Clean Code: A Handbook of Agile Software Craftsmanship</span>
</code></pre>
<p>Just like the <code>keys()</code> method, there is the <code>values()</code> method that returns the values in a dictionary instead.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    <span class="hljs-keyword">for</span> value <span class="hljs-keyword">in</span> programming_books.values():
        print(value)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 35</span>
<span class="hljs-comment"># 100</span>
<span class="hljs-comment"># 50</span>
</code></pre>
<p>Finally, if you want both the keys and the values as tuples, you can use the <code>items</code> method.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    programming_books = {
        <span class="hljs-string">'C Programming Language'</span>: <span class="hljs-number">35</span>,
        <span class="hljs-string">'Introduction to Algorithms'</span>: <span class="hljs-number">100</span>,
        <span class="hljs-string">'Clean Code: A Handbook of Agile Software Craftsmanship'</span>: <span class="hljs-number">50</span>
    }

    <span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> programming_books.items():
        print(item)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># ('C Programming Language', 35)</span>
<span class="hljs-comment"># ('Introduction to Algorithms', 100)</span>
<span class="hljs-comment"># ('Clean Code: A Handbook of Agile Software Craftsmanship', 50)</span>
</code></pre>
<h2 id="heading-how-to-write-functions-in-python">How to Write Functions in Python</h2>
<p>A function in Python (and programming in general) is a self-contained collection of instructions that perform a single task.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_hello</span>():</span>
    print(<span class="hljs-string">'Hello, World!'</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print_hello()


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>You define a function by writing out <code>def</code> followed by the name of the funtion and a colon. You can then write the function body from the next indented line.</p>
<p>In this example, the <code>print_hello()</code> prints out <code>Hello, World!</code> on the terminal. It doesn't accept any argument.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_hello</span>(<span class="hljs-params">message</span>):</span>
    print(message)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print_hello(<span class="hljs-string">'Hello, Universe!'</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, Universe!</span>
</code></pre>
<p>Now instead of printing out <code>Hello, World!</code> all the time, you can pass a custom message for the function to print out.</p>
<p>You can make a function accept multiple arguments and even set a default value for it.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_hello</span>(<span class="hljs-params">message, is_lower=False</span>):</span>
    <span class="hljs-keyword">if</span> is_lower:
        print(message.lower())
    <span class="hljs-keyword">else</span>:
        print(message.upper())


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print_hello(<span class="hljs-string">'Hello, Universe!'</span>)
    print_hello(<span class="hljs-string">'Hello, Universe!'</span>, <span class="hljs-literal">True</span>)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># HELLO, UNIVERSE!</span>
<span class="hljs-comment"># hello, universe!</span>
</code></pre>
<p>Setting a default value to a function parameter makes it optional. So if you do not pass a value during the function call, your program will use the default value.</p>
<p>Instead of printing out the message outright, you can make the function return the message.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">message, is_lower=False</span>):</span>
    <span class="hljs-keyword">if</span> is_lower:
        <span class="hljs-keyword">return</span> message.lower()
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> message.upper()


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(hello(<span class="hljs-string">'Hello, Universe!'</span>))
    print(hello(<span class="hljs-string">'Hello, Universe!'</span>, <span class="hljs-literal">True</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># HELLO, UNIVERSE!</span>
<span class="hljs-comment"># hello, universe!</span>
</code></pre>
<p>Since the function doesn't print out the message anymore, changing its name from <code>print_hello()</code> to just <code>hello()</code> makes more sense.</p>
<p>When you call the function with or without a custom message, the function returns a string that you can then print out within the <code>main()</code> function.</p>
<p>You can also save the message in variables instead of passing them to the <code>print()</code> function directly.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">hello</span>(<span class="hljs-params">message, is_lower=False</span>):</span>
    <span class="hljs-keyword">if</span> is_lower:
        <span class="hljs-keyword">return</span> message.lower()
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> message.upper()


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    uppercase_message = hello(<span class="hljs-string">'Hello, Universe!'</span>)
    print(uppercase_message)

    lowercase_message = hello(<span class="hljs-string">'Hello, Universe!'</span>, <span class="hljs-literal">True</span>)
    print(lowercase_message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># HELLO, UNIVERSE!</span>
<span class="hljs-comment"># hello, universe!</span>
</code></pre>
<p>It's not that you can only pass singular values to a function. You can pass lists, tuples, dictionaries or any other object to a function.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">total</span>(<span class="hljs-params">numbers</span>):</span>
    s = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> numbers:
        s += number
    <span class="hljs-keyword">return</span> s


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(total([<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-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>]))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># 55</span>
</code></pre>
<p>In this function, you can pass a list of numbers to and get their sum. I had to name the function <code>total()</code> instead of <code>sum()</code> because there is a built-in function with that name.</p>
<p>There is one last concept regarding functions that I'd like to discuss in this section, and that is recursion.</p>
<p>Recursion in Python or programming in general is the technique of making a function call itself to perform a task iteratively.</p>
<p>For example, imagine a function that accepts an integer and calculates the sum of all natural numbers up to that given integer. You can write this program using loops.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">natural_sum</span>(<span class="hljs-params">last_number</span>):</span>
    <span class="hljs-keyword">if</span> last_number &lt; <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> last_number

    total = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, last_number + <span class="hljs-number">1</span>):
        total += number

    <span class="hljs-keyword">return</span> total


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(natural_sum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>There is nothing new there, just regular usage of a range-based for loop. Now, you can also write the same program without any loop.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">recursive_natural_sum</span>(<span class="hljs-params">last_number</span>):</span>
    <span class="hljs-keyword">if</span> last_number &lt; <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> last_number

    <span class="hljs-keyword">return</span> last_number + recursive_natural_sum(last_number - <span class="hljs-number">1</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(recursive_natural_sum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>At a glance, this piece of code may look very complicated to you. But in reality it's very simple. Let's break it down step by step.</p>
<p>When you call the <code>recursive_natural_sum()</code> function with the value of 10 for the first time, you start a chain reaction of sorts.</p>
<p>Since the value is not less than 1, the <code>if</code> statement evaluates to <code>False</code> and the second <code>return</code> statement gets called.</p>
<p>Inside that <code>return</code> statement, you're calling the <code>recursive_natural_sum()</code> function by passing the value of <code>last_number - 1</code> which is 9 at this point.</p>
<p>You're also adding the returned value from this call to the current value of the <code>last_number</code> variable.</p>
<p>But you'll not get a return value because your inner function call will call itself again with <code>last_number - 1</code> which will be 8 at that point.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/recursion-1.drawio.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This calling goes on and on until the value of <code>last_digit</code> becomes zero. Once it becomes zero, the <code>if</code> statement evaluates to <code>True</code> and the function calls start to return a value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/recursion-2.drawio-1.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The value returned from each function call is <code>last_digit + (last_digit - 1)</code> by the end of the recursion chain it adds up to 55.</p>
<p>My colleague <a target="_blank" href="https://www.freecodecamp.org/news/author/beau/">Beau Carnes</a> has written a more in-depth article discussing how recursion works. You may take a look at it if you want to learn more.</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/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/">https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/</a></div>
<p>I'm not sating that recursive functions are easier than loops – but at times, using a recursive function instead of nested loops can be more efficient.</p>
<h3 id="heading-how-to-write-anonymous-or-lambda-functions-in-python">How to Write Anonymous or Lambda Functions in Python</h3>
<p>Anonymous or lambda functions are functions without any name. This is not something exclusive to Python and most of the modern programming languages have some sort of lambda implementation.</p>
<p>Instead of beginning the function declaration with <code>def</code>, you instead start with writing out <code>lambda</code> followed by a colon and the function body.</p>
<pre><code class="lang-python">print_hello = <span class="hljs-keyword">lambda</span>: print(<span class="hljs-string">'Hello, World!'</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print_hello()


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>Since lambdas do not have a name, you have to put it in a variable in order to access it but that's not recommended. If you need a named function, use <code>def</code> instead.</p>
<p>Lambda functions are useful when you want to pass a function as an argument to another function call. Take the <code>filter()</code> function for example.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_even</span>(<span class="hljs-params">number</span>):</span>
    <span class="hljs-keyword">if</span> number % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">4</span>, <span class="hljs-number">7</span>, <span class="hljs-number">88</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">55</span>, <span class="hljs-number">77</span>, <span class="hljs-number">95</span>]

    even_numbers = filter(check_even, numbers)

    print(list(even_numbers))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># [2, 4, 88, 12]</span>
</code></pre>
<p>The <code>filter()</code> function takes a function and an iterable type as its two arguments. The function should describe the logic for filtering and the iterable type will contain the values you want to filter from.</p>
<p>In this code, you have a list of numbers and you want to filter out the odd numbers from that list.</p>
<p>The <code>check_even()</code> function takes a number as argument. It then returns <code>True</code> if the number is divisible by two and <code>False</code> if not.</p>
<p>The <code>filter()</code> function iterates through the list of numbers and passes each number to the <code>check_even()</code> function.</p>
<p>It keeps the number if the <code>check_even()</code> function returns <code>True</code> or discards the number if the <code>check_even()</code> function returns <code>False</code>.</p>
<p>Now this <code>check_even()</code> function doesn't have any purpose other than checking if a given number is divisible by two or not. So you can write it as a lambda.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">4</span>, <span class="hljs-number">7</span>, <span class="hljs-number">88</span>, <span class="hljs-number">12</span>, <span class="hljs-number">15</span>, <span class="hljs-number">55</span>, <span class="hljs-number">77</span>, <span class="hljs-number">95</span>]

    even_numbers = filter(<span class="hljs-keyword">lambda</span> number: <span class="hljs-literal">True</span> <span class="hljs-keyword">if</span> number % <span class="hljs-number">2</span> == <span class="hljs-number">0</span> <span class="hljs-keyword">else</span> <span class="hljs-literal">False</span>, numbers)

    print(list(even_numbers))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># [2, 4, 88, 12]</span>
</code></pre>
<p>This lambda takes an argument named <code>number</code> then returns <code>True</code> if that's divisible by two and <code>False</code> otherwise.</p>
<p>You can add multiple arguments separating each by a comma. Finally a lambda doesn'e need a return statement but you can assume a return.</p>
<p>So <code>True if number % 2 == 0 else False</code> is equivalent to <code>return True if number % 2 == 0 else False</code>. The <code>if...else</code> statement inside the lambda is in short hand form.</p>
<h3 id="heading-how-to-work-with-local-nonlocal-and-global-variables-in-python">How to Work with local, nonlocal and global Variables in Python</h3>
<p>Scope of a variable in Python or programming in general refers to region where that variable is accessible.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">outside</span>():</span>
    message = <span class="hljs-string">'Hello, World!'</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># NameError: name 'msg' is not defined</span>
</code></pre>
<p>In this example, the <code>message</code> variable is defined inside the <code>outside()</code> function and there is no existence of it anywhere else.</p>
<p>As a result, when you try to access that variable from the <code>main()</code> function, you get a <code>NameError</code> since the variable is scoped to the <code>outside()</code> function.</p>
<p>Variables like this are called local variables and they only exist within the block they've been declared.</p>
<p>Global variables, on the other hand, are usually declared outside of any particular block of code.</p>
<pre><code class="lang-python">message = <span class="hljs-string">'Hello, World!'</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>As you can see, now the <code>message</code> variable has no indentation and is declared at the top of the function. You could've declared the variable after the <code>main()</code> function.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(message)


message = <span class="hljs-string">'Hello, World!'</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, World!</span>
</code></pre>
<p>This works because you don't try to access the variable until you call the <code>main()</code> function inside the <code>if</code> statement.</p>
<p>Although global variables are accessible pretty much everywhere, it can be a bit tricky to work with if you have a local variable with a similar name.</p>
<pre><code class="lang-python">message = <span class="hljs-string">'Hello, {name}!'</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    message = message.format(name=<span class="hljs-string">'Farhan'</span>)
    print(message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># UnboundLocalError: local variable 'message' referenced before assignment</span>
</code></pre>
<p>In this code, you have a placeholder for a name inside the <code>message</code> variable. You can use the <code>format()</code> method to put a name there.</p>
<p>But if you try to run this code, you'll get a <code>local variable 'message' referenced before assignment</code> message. In simpler words, you're trying to access a local variable named <code>message</code> before even assigning anything to it.</p>
<p>So clearly, Python is looking for a local variable with the given name instead of accessing the global one. Since it's asking, try giving it a local variable.</p>
<pre><code class="lang-python">message = <span class="hljs-string">'Hello, {name}!'</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    message = str()

    message = message.format(name=<span class="hljs-string">'Farhan'</span>)
    print(message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()
</code></pre>
<p>This time the error will be gone but you will not get any output in your console. This is because the local <code>message</code> variable is empty and there is no placeholder to put a name in.</p>
<p>This is where the <code>global</code> keyword comes in. Instead of creating a local variable, you can let Python know that you're trying to access the global <code>message</code> variable.</p>
<pre><code class="lang-python">message = <span class="hljs-string">'Hello, {name}!'</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    <span class="hljs-keyword">global</span> message

    message = message.format(name=<span class="hljs-string">'Farhan'</span>)
    print(message)


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, Farhan!</span>
</code></pre>
<p>Now, instead of trying to look for a variable named <code>message</code> within the local scope, Python will directly reach out to the global scope.</p>
<p>Finally, there is the <code>nonlocal</code> keyword usually used in nested functions. It solves a similar problem as the <code>global</code> keyword but in a local scope.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>):</span>
    message = <span class="hljs-string">'Hello, {name}!'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">include_name</span>():</span>
        message = message.format(name=name)

    include_name()
    <span class="hljs-keyword">return</span> message


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(greet(<span class="hljs-string">'Farhan'</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># UnboundLocalError: local variable 'message' referenced before assignment</span>
</code></pre>
<p>In this example, you're dealing with three functions. There is the <code>main()</code> function, there is the <code>greet()</code> function, and inside that is the <code>include_name()</code> function.</p>
<p>The <code>greet()</code> function takes a name as an argument but doesn't include that in the message right away.</p>
<p>Instead it calls the <code>include_name()</code> function defined within its local scope. That's where the problem begins.</p>
<p>You see, the <code>message</code> variable is outside the scope of the <code>include_message()</code> function and that's why you're getting the <code>referenced before assignment</code> error message.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>):</span>
    message = <span class="hljs-string">'Hello, {name}!'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">include_name</span>():</span>
        <span class="hljs-keyword">global</span> message

        message = message.format(name=name)

    include_name()
    <span class="hljs-keyword">return</span> message


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(greet(<span class="hljs-string">'Farhan'</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># NameError: name 'message' is not defined</span>
</code></pre>
<p>You can't use the <code>global</code> keyword either since the <code>message</code> variable is not defined in the global scope and that's what the error message dictates.</p>
<p>You can use the <code>nonlocal</code> keyword to use variables that are not in the global scope but in the scope of the outer function.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>):</span>
    message = <span class="hljs-string">'Hello, {name}!'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">include_name</span>():</span>
        <span class="hljs-keyword">nonlocal</span> message
        message = message.format(name=name)

    include_name()
    <span class="hljs-keyword">return</span> message


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(greet(<span class="hljs-string">'Farhan'</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># Hello, Farhan!</span>
</code></pre>
<p>Now the <code>include_name()</code> function will look for the <code>message</code> variable within the scope of the <code>greet()</code> function instead of its local scope.</p>
<h3 id="heading-how-to-pass-a-variable-number-of-arguments-to-a-function-using-args-and-kwargs-in-python">How to Pass a Variable Number of Arguments to a Function Using <em>args and *</em>kwargs in Python</h3>
<p>Imagine a function that takes a bunch of numbers as arguments and returns their sum. In a function like this, it'd be nice to have the provision of passing a variable number of arguments.</p>
<p>Surely you can pass the numbers as a tuple or as a list but you may want to pass them as regular arguments separated by commas. You can do that by using <code>*args</code> or non key arguments in Python.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">total</span>(<span class="hljs-params">*args</span>):</span>
    print(type(args))

    t = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> arg <span class="hljs-keyword">in</span> args:
        t += arg

    <span class="hljs-keyword">return</span> t


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(total(<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-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># &lt;class 'tuple'&gt;</span>
<span class="hljs-comment"># 15</span>
</code></pre>
<p>Here, you can pass an arbitrary number of variables to the <code>total()</code> function as argument and you'll have access to them as a tuple inside that function.</p>
<p>It's not mandatory to name the argument as <code>*args</code><em>,</em> you can call it something more descriptive like <code>_*_numbers</code> or anything else. As long as you put the asterisk in front, you're good to go.</p>
<p>Like <code>*args</code> there is also <code>**kwargs</code> or keyword arguments that will allow you to access the function arguments as a dictionary.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">items</span>(<span class="hljs-params">**kwargs</span>):</span>
    print(type(kwargs))

    <span class="hljs-keyword">for</span> key, value <span class="hljs-keyword">in</span> kwargs.items():
        print(<span class="hljs-string">f"<span class="hljs-subst">{key}</span> : <span class="hljs-subst">{value}</span>"</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    items(
        Apple=<span class="hljs-number">10</span>,
        Orange=<span class="hljs-number">8</span>,
        Grape=<span class="hljs-number">35</span>
    )


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># &lt;class 'dict'&gt;</span>
<span class="hljs-comment"># Apple : 10</span>
<span class="hljs-comment"># Orange : 8</span>
<span class="hljs-comment"># Grape : 35</span>
</code></pre>
<p>In this case, you can pass arbitrary number of key-value pairs and access them as a dictionary inside the <code>items()</code> function.</p>
<p>Just like the the <code>*args</code> keyword, you don't have to absolutely name it <code>**kwargs</code>. Instead you can name it anything you want.</p>
<p>As long as you put the double asterisks at the front, you'll be fine. The <code>items()</code> method within dictionaries lets you iterate through them.</p>
<p>You can also change the names of the <code>key</code> and <code>value</code> variables. A more readable version of the function can be as follows:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">items</span>(<span class="hljs-params">**fruits</span>):</span>
    print(type(fruits))

    <span class="hljs-keyword">for</span> fruit, price <span class="hljs-keyword">in</span> fruits.items():
        print(<span class="hljs-string">f"<span class="hljs-subst">{fruit}</span> : <span class="hljs-subst">{price}</span>"</span>)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    items(
        Apple=<span class="hljs-number">10</span>,
        Orange=<span class="hljs-number">8</span>,
        Grape=<span class="hljs-number">35</span>
    )


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># &lt;class 'dict'&gt;</span>
<span class="hljs-comment"># Apple : 10</span>
<span class="hljs-comment"># Orange : 8</span>
<span class="hljs-comment"># Grape : 35</span>
</code></pre>
<p>Keep in mind that the type of the keys in this case has to be a string and the values can be anything you want.</p>
<h2 id="heading-what-are-modules-in-python">What Are Modules in Python?</h2>
<p>As you project grows, breaking off your code into multiple files becomes a necessity. A module in Python is just a file containing Python code that you can import inside other Python files.</p>
<p>For example, assume that you have a Python project with two files. The first one may be "mathstuff.py" and the other one may be "main.py".</p>
<p>The "mathstuff.py" file can contain stuff related to mathematics, for example a function that sums up all the natural numbers in a range.</p>
<pre><code class="lang-python"><span class="hljs-comment"># mathstuff.py</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">natural_sum</span>(<span class="hljs-params">last_number</span>):</span>
    <span class="hljs-keyword">if</span> last_number &lt; <span class="hljs-number">1</span>:
        <span class="hljs-keyword">return</span> last_number

    total = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> number <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, last_number + <span class="hljs-number">1</span>):
        total += number

    <span class="hljs-keyword">return</span> total
</code></pre>
<p>Now you can import this function any other file such as the "main.py" file.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> mathstuff


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(mathstuff.natural_sum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>The <code>import</code> statement, as the name suggests, imports bits of code from another file or module.</p>
<p>It's not uncommon to house more than one function, variable, or other object in a Python module and often times you may want to use only few of them.</p>
<p>You can use the <code>from...import</code> statement in these situations.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> mathstuff <span class="hljs-keyword">import</span> natural_sum


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(natural_sum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>It also saves you from having to write the module name everytime you want to access a function or object living inside that module.</p>
<p>Finally, you can use the <code>as</code> keyword to change the name of an imported module to make that more easily accessible.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> mathstuff <span class="hljs-keyword">as</span> math


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(math.natural_sum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>Also works with the <code>from...import</code> statement.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> mathstuff <span class="hljs-keyword">import</span> natural_sum <span class="hljs-keyword">as</span> nsum


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    last_number = int(input(<span class="hljs-string">'up to which number would you like to calculate the sum?\n- '</span>))

    print(nsum(last_number))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># up to which number would you like to calculate the sum?</span>
<span class="hljs-comment"># - 10</span>
<span class="hljs-comment"># 55</span>
</code></pre>
<p>Importing modules is something that you'll have to do all the time. Apart from modules, there is also the idea of packages.</p>
<p>In these examples, both files are in the same folder. Packages are a nifty little way of keeping related Python modules together in different folders.</p>
<p>For example, in a web framework, you may have a package called <code>framework</code> that houses all the code that comes with this web framework.</p>
<p>Now this <code>framework</code> package can in turn have multiple subpackages – for example there may be a package named <code>http</code> for handling HTTP requests and responses.</p>
<pre><code>├───framework
│   └───http
</code></pre><p>At the moment, these are just regular folders. To turn them into Python, all you need is to create "<strong>init</strong>.py" files inside them.</p>
<pre><code>├───framework
│   │   __init__.py
│   │
│   └───http
│           __init__.py
</code></pre><p>Now these files have turned into packages. These "<strong>init</strong>.py" files will tell the Python import system that these folders are indeed packages.</p>
<p>Finally, to put some code inside the <code>http</code> package, create a file named <code>response.py</code> with the following content:</p>
<pre><code class="lang-python"><span class="hljs-comment"># framework/http/response.py</span>

<span class="hljs-keyword">from</span> json <span class="hljs-keyword">import</span> dumps


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">as_json</span>(<span class="hljs-params">message</span>):</span>
    <span class="hljs-keyword">return</span> dumps({
        <span class="hljs-string">'message'</span>: message
    })
</code></pre>
<p>First, you're importing the <code>dumps</code> function from the <code>json</code> package. These are part of the Python standard library.</p>
<p>The <code>dumps</code> function can turn a Python object like a dictionary into a JSON string, which means the <code>as_json()</code> function returns a given value in JSON format.</p>
<pre><code class="lang-json">{<span class="hljs-attr">"message"</span>: <span class="hljs-string">"Hello, World"</span>}
</code></pre>
<p>Now you can import this function in the "main.py" file.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> framework.http.response <span class="hljs-keyword">import</span> as_json


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(as_json(<span class="hljs-string">'Hello, World!'</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {"message": "Hello, World"}</span>
</code></pre>
<p>Instead of putting the <code>as_json()</code> function inside another Python file, you can simply put it inside the "framework/http/<strong>init</strong>.py" file.</p>
<p>Then you can update the "main.py" file to use the updated package path.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> framework.http <span class="hljs-keyword">import</span> as_json


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    print(as_json(<span class="hljs-string">'Hello, World!'</span>))


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    main()

<span class="hljs-comment"># {"message": "Hello, World"}</span>
</code></pre>
<p>If you ever try out a framework like Django, you'll see that the framework contains a huge amount of packages, so understanding how the import system works will help you out immensely.</p>
<h2 id="heading-how-to-use-the-python-documentation-efficiently">How to Use the Python Documentation Efficiently</h2>
<p>Since you're now out of infancy as a Python programmer, I'd like to show you how you can browse through the official Python documentation.</p>
<p>You may think, well browsing documentation is not hard and you'd be absolutely right. But it can be daunting at first.</p>
<p>So what I'm going to do is give you a little primer on how I have used the documentation throughout my career.</p>
<p>The first step is to visit <a target="_blank" href="https://docs.python.org/">https://docs.python.org/</a> and you'll automatically land on the documentation for the latest version of Python.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-154.png" alt="Image" width="600" height="400" loading="lazy">
<em>Python Documentation (<a target="_blank" href="https://docs.python.org/">https://docs.python.org/</a>)</em></p>
<p>At the time of writing, the latest version of Python is 3.11.4 however I still have version 3.10.11 installed on my computers.</p>
<p>Right from the get go, you can see lots of different links other pages and to be honest, you're not going to need all of them right away.</p>
<p>The best way to find out which link to what page is to to have a look at whichever looks interesting to you.</p>
<p>I'll talk about three links from this page that have helped me immensely. The first one is the "Tutorial" page.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-155.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Python Tutorial (https://docs.python.org/3/tutorial/index.html)</em></p>
<p>Back when I was making my shift from C to Python, this is the tutorial I went through. The tutorial starts with an introduction to the Python interpreter.</p>
<p>Then it teaches you topics including but not limited to data types, control flow statements, data structures, modules, error handling, the standard library, and even object oriented programming.</p>
<p>The other page that's extremely useful is the "Glossary" page. It contains a list of all the important terminology that you may come across while working with Python.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-156.png" alt="Image" width="600" height="400" loading="lazy">
<em>Glossary (https://docs.python.org/3/glossary.html)</em></p>
<p>So at any point if you feel like that you do not know the meaning of a word, take a look at the glossary.</p>
<p>Finally the "Library Reference" page is a detailed description of everything included in the standard Python library.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-158.png" alt="Image" width="600" height="400" loading="lazy">
<em>Library Reference (https://docs.python.org/3/library/index.html)</em></p>
<p>Say, for example, I'd like to learn about the context manager type (which is beyond the scope of this book). I can just look under the "Built-in Types" section.</p>
<p>Or if you want to know about something else such as the JSON package, you can search the library reference for JSON – and sure enough you'll find something on it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-159.png" alt="Image" width="600" height="400" loading="lazy">
<em>JSON is under the Internet Data Handling section ()</em></p>
<p>Following the link will land you on the page describing how the JSON package works.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/image-160.png" alt="Image" width="600" height="400" loading="lazy">
<em>JSON encoder and decoder (https://docs.python.org/3/library/json.html)</em></p>
<p>The page not only contains text but also contains practical and very useful code examples.</p>
<p>The official documentation is going to be your most reliable and in-depth source of learning, so the sooner you get used to it the better.</p>
<h2 id="heading-whats-next">What's Next?</h2>
<p>As I've said, this text is not a definitive guide to Python – which means there is still a lot to learn. In this section I'll list out a number of different resources.</p>
<h3 id="heading-object-oriented-programming">Object Oriented Programming</h3>
<p>The first thing that you may want to learn right after finishing this handbook is object oriented programming with Python.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Ej_02ICOIgs" 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>
<p>This comprehensive video course is hosted on the freeCodeCamp YouTube channel. It's a little over 2 hours long and covers the essential concepts nicely.</p>
<p>Object Oriented Programming is not just about learning about concepts like classes, objects, and inheritance.</p>
<p>Writing good object oriented code takes a lot of practice and it all begins with the basics. Take your time with this one and make sure to understand everything.</p>
<h3 id="heading-algorithms-and-data-structures">Algorithms and Data Structures</h3>
<p>The second item on the list that you should absolutely learn if you're serious about being an efficient programmer is data structures and algorithms.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/8hly31xKli0" 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>
<p>Fortunately, the freeCodeCamp YouTube channel hosts a very comprehensive video produced by some of the finest teachers out there on the topic.</p>
<p>The video is a little over 5 hours long and will teach everything you need to know about data structures and algorithms as beginner.</p>
<p>This course is not going to turn you into a better programmer instantly, but it'll teach you a better and more efficient way of thinking about problems.</p>
<h3 id="heading-django">Django</h3>
<p>If you'd like to get into web development using Python, Django is among the most popular choices out there.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/o0XbHvKxw7Y" 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>
<p>The freeCodeCamp YouTube channel hosts this massive 18 hour long course taught by Dr. Chuck, one of the best teachers in the world.</p>
<p>The course not only teaches Django from the ground up but also a long list of concepts around the web itself.</p>
<p>Having a good understanding of object oriented programming is important before you jump into the world of Django, so make sure you have that.</p>
<h3 id="heading-qt">Qt</h3>
<p>Python may not be the most popular languages for building graphical user interfaces, but it's surprisingly capable on that end, too.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Z1N9JzNax2k" 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>
<p>Qt is a very popular cross-platform UI framework and PySide6 is the official Python bindings for Qt 6.</p>
<p>In this 5 hour long course, you'l learn all the fundamentals of creating user interfaces using Qt and create cross-platform, robust software in no time.</p>
<h3 id="heading-pygame">PyGame</h3>
<p>Just like cross-platform graphical user interfaces, Python is not the most popular choice when it comes to game programing.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/R9apl6B_ZgI" 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>
<p>However, the PyGame library is a very powerful and easy to use library for writing 2D games in Python.</p>
<p>In this almost 7 hour long course on game programming with Python, you'll learn about writing a game that mimicks the very popular Stardew Valley.</p>
<p>Undoubtedly, this is a very challenging video to go through but so is making games. So if you're into gamedev and Python, this may be the course you need.</p>
<h3 id="heading-data-science">Data Science</h3>
<p>Data science is arguably the most popular field where Python plays a huge role. Becoming a data scientist can take years but you gotta start somewhere.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/LHBE6Q9XlzI" 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>
<p>This 12 hour long course on the freeCodeCamp YouTube channel teaches you a lot about how to use your Python knowledge in data science.</p>
<p>Although the course doesn't go very deep into the realm of data science, it teaches you about a number of very important libraries used regularly in data science.</p>
<p>Near the end of the course, you'll also create a project by applying everything you learn throughout the course.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I would like to thank you from the bottom of my heart for the time you've spent reading this article.</p>
<p>Although I've listed only a small number of courses here, the <a target="_blank" href="https://www.youtube.com/c/Freecodecamp/search?query=python">freeCodeCamp YouTube channel</a> is just filled with excellent Python learning resources.</p>
<p>Keep in mind that this handbook is a living document and I'll update it with from time to time. So bookmarking it maybe a great idea.</p>
<p>I also have a personal blog where I write about random tech stuff, so if you're interested in something like that, checkout <a target="_blank" href="https://farhan.dev">https://farhan.dev</a>.</p>
<p>If you have any questions or are confused about anything – or just want to get in touch – I'm available on <a target="_blank" href="https://twitter.com/frhnhsin">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Configure Visual Studio Code for Python Development ]]>
                </title>
                <description>
                    <![CDATA[ Visual Studio Code is one of the most versatile code editors out there. Even though it's a code editor, the sheer extensibility of the program makes it almost as capable as some of the JetBrains products out there. In this article, I'll walk you thro... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-configure-visual-studio-code-for-python-development/</link>
                <guid isPermaLink="false">66b0ab347cd8dca6718a22b6</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Visual Studio Code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Visual Studio Code ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Mon, 17 Jul 2023 17:13:01 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/10/visual-studio-code-for-python.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Visual Studio Code is one of the most versatile code editors out there. Even though it's a code editor, the sheer extensibility of the program makes it almost as capable as some of the JetBrains products out there.</p>
<p>In this article, I'll walk you through the entire process of configuring Visual Studio Code for Python development. It's not a universal setup, but this is something that I use personally and have found it to be really comfortable.</p>
<p>The first step is to install Visual Studio Code on your computer. I'm on Debian 12 at the moment and I have the editor ready to go. Platform specific <a target="_blank" href="https://code.visualstudio.com/docs/setup/setup-overview">installation instructions</a> are available in the documentation.</p>
<p>Assuming you are past the installation step, now I'll introduce you to a set of essential extensions that will elevate your Python development experience to the next level.</p>
<h2 id="heading-python-extension">Python Extension</h2>
<p>The first extension that you need to install is the <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=ms-python.python">Python Extension</a> from Microsoft.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-86.png" alt="Image" width="600" height="400" loading="lazy">
<em>https://marketplace.visualstudio.com/items?itemName=ms-python.python</em></p>
<p>This is actually an extension pack that contains two extensions. The first extension is the Python extension. It lays the foundation for Python development in Visual Studio Code.</p>
<p>The other one is <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance">Pylance</a>, which is a very performant language server for Python.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-88.png" alt="Image" width="600" height="400" loading="lazy">
<em>https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance</em></p>
<p>This extension provides rich intellisense support and is powered by <a target="_blank" href="https://github.com/microsoft/pyright">Pyright</a>, the static type checker from Microsoft. The next thing you need to think about is linting.</p>
<h2 id="heading-ruff-linter">Ruff Linter</h2>
<p>A linter is a program that analyses your code statically and provides valuable insights on possible errors.</p>
<p>The Pylance extension does an excellent job of finding out fatal errors within your code, but there is more to code than just that.</p>
<p>When working on a big project, it's pretty common to leave unwanted mess within your codebase. Things like unused imports and variables, bad code practices, and so on.</p>
<p>A good linter can point out code smells like this and make your code cleaner. Now, the go-to choice when it comes to Python linters is Pylint.</p>
<p>Pylint has been around for ages and works quite well, but I think there is a better alternative.</p>
<p>Ruff is an extremely fast Python linter written in Rust that imposes stricter linting rules than Pylint. The tool also has an <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=charliermarsh.ruff">official extension</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-89.png" alt="Image" width="600" height="400" loading="lazy">
<em>https://marketplace.visualstudio.com/items?itemName=charliermarsh.ruff</em></p>
<p>It's a plug n' play extension and doesn't require any additional configuration whatsoever. So once you have it installed, you're good to go.</p>
<h2 id="heading-isort">Isort</h2>
<p>Like a linter, <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=ms-python.isort">isort</a> is another utility that's sole purpose is sorting import statements.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-95.png" alt="Image" width="600" height="400" loading="lazy">
<em>https://marketplace.visualstudio.com/items?itemName=ms-python.isort</em></p>
<p>The utility sorts all the imports alphabetically, while also dividing them into sections.</p>
<p>The extension is very straightforward. Once you have the extension, it'll render squiggly lines under any import statement that seems out of place.</p>
<p>You can then use the quick action menu to sort them. Or, you can also use the command palette to quickly access the isort command.</p>
<h2 id="heading-mypy-type-checker">Mypy Type Checker</h2>
<p>Before I start talking about this extension, let me explain what <a target="_blank" href="https://mypy-lang.org/">mypy</a> actually is.</p>
<p>According to the info on their homepage:</p>
<blockquote>
<p>Mypy is an optional static type checker for Python that aims to combine the benefits of dynamic (or "duck") typing and static typing. Mypy combines the expressive power and convenience of Python with a powerful type system and compile-time type checking.</p>
</blockquote>
<p>In simpler words, mypy forces you to add essential type annotations to your Python programs, making them easier to comprehend.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-90.png" alt="Image" width="600" height="400" loading="lazy">
<em>https://mypy-lang.org/</em></p>
<p>Recently, Microsoft has published <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=ms-python.mypy-type-checker">an extension</a> that adds type checking functionality using mypy to their beloved editor.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-91.png" alt="Image" width="600" height="400" loading="lazy">
<em>https://marketplace.visualstudio.com/items?itemName=ms-python.mypy-type-checker</em></p>
<p>Once you have installed the extension, it'll perform necessary checks on your code and report any missing type annotations as compile-time errors.</p>
<p>While having type annotations is not mandatory, it's highly recommended.</p>
<h2 id="heading-intellicode">IntelliCode</h2>
<p><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=VisualStudioExptTeam.vscodeintellicode">IntelliCode</a> provides AI assisted code completion in Visual Studio Code. It may sound similar to GitHub Copilot, but in reality it's a lot smaller than that.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-93.png" alt="Image" width="600" height="400" loading="lazy">
<em>https://marketplace.visualstudio.com/items?itemName=VisualStudioExptTeam.vscodeintellicode</em></p>
<p>Where GitHub Copilot or Tabnine provides full-blown code blocks, IntelliCode autocompletes lines of code pretty flawlessly.</p>
<p>In most cases, this extension can help you type less of the same code by suggesting the right thing while also keeping out of your way.</p>
<h2 id="heading-error-lens">Error Lens</h2>
<p>While not related to Python specifically, <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=usernamehw.errorlens">Error Lens</a> is a great extension that embeds errors right by the side of the line of code.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-94.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I often work on my 14 inch Thinkpad and like to turn off the terminal pane. Error Lens eradicates the need to look at the terminal now and then to see my errors and warnings.</p>
<p>As useful as it may be, sometimes your editor can look cluttered due to all the warning and error outputs, so decide accordingly.</p>
<h2 id="heading-indent-rainbow">Indent Rainbow</h2>
<p>Unlike other programming languages, an incorrect level of indentation can literally break your program in Python.</p>
<p>Visual Studio Code already does a good job of visualizing indentation levels within your code, but if you want to add some color to it, the <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=oderwat.indent-rainbow">indent-rainbow</a> package is what you need.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/07/image-92.png" alt="Image" width="600" height="400" loading="lazy">
<em>https://marketplace.visualstudio.com/items?itemName=oderwat.indent-rainbow</em></p>
<p>It adds different colors to the different levels of indentation. Personally, I don't use this one on a regular basis, but you may find it useful.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Like I said, these extensions and my personal configuration are not a silver bullet. But this setup is something that I've been using for quite a while and I hope it's useful to you as well.</p>
<p>I often install specialized extensions depending on the projects I work on. For example, I use the <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=batisteo.vscode-django">Django</a> or <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=wholroyd.jinja">Jinja</a> project when I work on a Django or Flask project.</p>
<p>Or I install the <a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter">Jupyter</a> extension while working on a Jupyter Notebook. So feel free to install whatever you need, just don't overdo it.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Java Handbook – Learn Java Programming for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Java has been around since the 90s. And despite its massive success in many areas, this cross-platform, object-oriented programming language is often maligned. Regardless of how people feel about Java, I can tell you from experience is that it is an ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-java-handbook/</link>
                <guid isPermaLink="false">66b0ab518d675d0da5f1ab83</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Wed, 07 Sep 2022 18:05:02 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/Farhan-Java-Handbook-Mockup.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Java has been around since the 90s. And despite its massive success in many areas, this cross-platform, object-oriented programming language is often maligned.</p>
<p>Regardless of how people feel about Java, I can tell you from experience is that it is an excellent programming language. After its first appearance back in 1995, it's still widely-used – and chances are it's not going anywhere anytime soon.</p>
<p>You can use Java to build servers, create desktop applications, games, mobile applications and more. There are also other JVM (we'll discuss what that means very soon) languages such as <a target="_blank" href="https://kotlinlang.org/">Kotlin</a>, <a target="_blank" href="https://groovy-lang.org/">Groovy</a>, <a target="_blank" href="https://www.scala-lang.org/">Scala</a>, and <a target="_blank" href="https://clojure.org/">Clojure</a> that you can use for different purposes.</p>
<p>Java is also cross-platform which means code you write and compile on one platform can run on any other platform that has Java installed on it. We'll discuss this topic in much more detail later on.</p>
<p>For now, I can tell you that although Java has its fair share of flaws, it also a has a lot to offer. </p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-hello-world-in-java">How to Write Hello World in Java</a><ul>
<li><a class="post-section-overview" href="#heading-whats-going-on-in-the-code">What’s Going On in the Code?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-jvm">What is JVM?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-jre-and-jdk">What is JRE and JDK?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-setup-java-on-your-computer">How To Setup Java on Your Computer?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-a-java-ide-on-your-computer">How To Install a Java IDE on Your Computer?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-new-project-on-intellij-idea">How To Create a New Project on IntelliJ IDEA</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-variables-in-java">How to Work with Variables in Java</a><ul>
<li><a class="post-section-overview" href="#heading-what-are-the-rules-for-declaring-variables">What Are the Rules for Declaring Variables?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-final-variables">What Are final Variables?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-are-the-primitive-data-types-in-java">What are the Primitive Data Types in Java?</a><ul>
<li><a class="post-section-overview" href="#heading-what-is-type-conversion-or-casting">What is Type Conversion or Casting?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-wrapper-classes-in-java">What are Wrapper Classes in Java</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-use-operators-in-java">How to Use Operators in Java</a><ul>
<li><a class="post-section-overview" href="#heading-what-are-the-arithmetic-operators">What Are the Arithmetic Operators?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-the-assignment-operators">What Are the Assignment Operators?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-the-relational-operators">What Are the Relational Operators?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-the-logical-operators">What Are the Logical Operators?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-the-unary-operators">What Are the Unary Operators?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-strings-in-java">How to Work with Strings in Java</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-format-a-string">How to Format a String</a></li>
<li><a class="post-section-overview" href="#heading-how-to-get-the-length-of-a-string-or-check-if-its-empty-or-not">How to Get the Length of a String or Check if It's Empty or Not</a></li>
<li><a class="post-section-overview" href="#heading-how-to-split-and-join-strings">How to Split and Join Strings</a></li>
<li><a class="post-section-overview" href="#heading-how-to-convert-a-string-to-upper-or-lowercase">How to Convert a String to Upper or Lowercase</a></li>
<li><a class="post-section-overview" href="#heading-how-to-compare-two-strings">How to Compare Two Strings</a></li>
<li><a class="post-section-overview" href="#how-to-replace-characters-or-substring-in-a-string">How to Replace Characters or Substring in a String</a></li>
<li><a class="post-section-overview" href="#heading-how-to-check-if-a-string-contains-a-substring-or-not">How to Check If a String Contains a Substring or Not</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-are-the-different-ways-of-inputting-and-outputting-data">What Are the Different Ways of Inputting and Outputting Data?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-conditional-statements-in-java">How to Use Conditional Statements in Java</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-switch-case-statement">What is a switch-case statement?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-variable-scope-in-java">What is Variable Scope in Java?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-default-values-of-variables-in-java">What Are Default Values of Variables in Java?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-arrays-in-java">How to Work with Arrays in Java</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-sort-an-array">How to Sort an Array</a></li>
<li><a class="post-section-overview" href="#heading-how-to-perform-binary-search-on-an-array">How to Perform Binary Search on an Array</a></li>
<li><a class="post-section-overview" href="#heading-how-to-fill-an-array">How to Fill an Array</a></li>
<li><a class="post-section-overview" href="#heading-how-to-make-copies-of-an-array">How to Make Copies of an Array</a></li>
<li><a class="post-section-overview" href="#heading-how-to-compare-two-arrays">How to Compare Two Arrays</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-use-loops-in-java">How to Use Loops in Java</a><ul>
<li><a class="post-section-overview" href="#heading-for-loop">For Loop</a></li>
<li><a class="post-section-overview" href="#heading-for-each-loop">For-Each Loop</a></li>
<li><a class="post-section-overview" href="#heading-while-loop">While Loop</a></li>
<li><a class="post-section-overview" href="#heading-do-while-loop">Do-While Loop</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-array-lists-in-java">How to Work with Array Lists in Java</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-add-or-remove-multiple-elements">How to Add or Remove Multiple Elements</a></li>
<li><a class="post-section-overview" href="#heading-how-to-remove-elements-based-on-a-condition">How to Remove Elements Based on a Condition</a></li>
<li><a class="post-section-overview" href="#heading-how-to-clone-and-compare-array-lists">How to Clone and Compare Array Lists</a></li>
<li><a class="post-section-overview" href="#heading-how-to-check-if-an-element-is-present-or-the-array-list-is-empty">How To Check if an Element Is Present or the Array List Is Empty</a></li>
<li><a class="post-section-overview" href="#heading-how-to-sort-an-array-list">How to Sort an Array List</a></li>
<li><a class="post-section-overview" href="#heading-how-to-keep-common-elements-from-two-array-lists">How To Keep Common Elements From Two Array Lists</a></li>
<li><a class="post-section-overview" href="#heading-how-to-perform-an-action-on-all-elements-of-an-array-list">How To Perform an Action on All Elements of an Array List</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-hash-maps-in-java">How To Work With Hash Maps in Java</a><ul>
<li><a class="post-section-overview" href="#how-to-put-or-replace-multiple-elements-in-a-hash-map">How To Put or Replace Multiple Elements in a Hash Map</a></li>
<li><a class="post-section-overview" href="#heading-how-to-check-if-a-hash-map-contains-an-item-or-if-its-empty">How To Check if a Hash Map Contains an Item or if It’s Empty</a></li>
<li><a class="post-section-overview" href="#heading-how-to-perform-an-action-on-all-elements-of-a-hash-map">How To Perform an Action on All Elements of a Hash Map</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-classes-and-objects-in-java">Classes and Objects in Java</a><ul>
<li><a class="post-section-overview" href="#heading-what-is-a-method">What is a Method?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-method-overloading">What is Method Overloading?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-are-constructors-in-java">What are Constructors in Java?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-access-modifiers-in-java">What Are Access Modifiers in Java?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-the-getter-and-setter-methods-in-java">What Are the Getter and Setter Methods in Java?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-inheritance-in-java">What is Inheritance in Java?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-override-a-method-in-java">How to Override a Method in Java</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-prerequisites"><strong>Prerequisites</strong></h2>
<p>The only re-requisite for this course is familiarity with any other programming language such as Python, JavaScript, and so on.</p>
<p>Although I'll explain crucial programming concepts in the context of Java, I'll not explain things like what a variable is in the context of programming in general.</p>
<h2 id="heading-how-to-write-hello-world-in-java">How to Write Hello World in Java</h2>
<p>Ideally the first step should've been setting up Java on your computer, but I don't want to bore you with downloading and installing a bunch of software right at the beginning. For this example, you'll use <a target="_blank" href="https://replit.com/">https://replit.com/</a> as your platform.</p>
<p>First, head over to <a target="_blank" href="https://replit.com/">https://replit.com/</a> and create a new account if you don't already have one. You can use your existing Google/GitHub/Facebook account to login. Once logged in, you'll land on your home. From there, use the <strong>Create</strong> button under <strong>My Repls</strong> to create a new repl.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-201.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the <strong>Create a Repl</strong> modal, choose <strong>Java</strong> as <strong>Template,</strong> set a descriptive <strong>Title</strong> such as <strong>HelloWorld</strong> and hit the <strong>Create Repl</strong> button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-202.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>A code editor will show up with an integrated terminal as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-203.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>On the left side is the list of files in this project, in the middle is the code editor, and on the right side is the terminal.</p>
<p>The template comes with some code by default. You can run the code by hitting the <strong>Run</strong> button. Go ahead and do that, run the program.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-205.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If everything goes fine, you'll see the words "Hello world!" printed on the right side. Congratulations, you've successfully run your first Java program.</p>
<h3 id="heading-whats-going-on-in-the-code">What’s Going On in the Code?</h3>
<p>The hello world program is probably the most basic executable Java program that you can possibly write – and understanding this program is crucial.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
    System.out.println(<span class="hljs-string">"Hello world!"</span>);
  }
}
</code></pre>
<p>Let's start with the first line:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
  <span class="hljs-comment">//...</span>
}
</code></pre>
<p>This line creates a <code>Main</code> class. A class groups together a bunch of related code within a single unit.</p>
<p>This is a <code>public</code> class, which means this class is accessible anywhere in the codebase. One Java source file (files with the <code>.java</code> extension) can contain only one top level <code>public</code> class in it.</p>
<p>This top level public class has to be named exactly the same as the source code filename. That's why the file named <code>Main.java</code> contains the <code>main</code> class in this project.</p>
<p>To understand why, click on the three dots in the list of files and click on the <strong>Show hidden files</strong> option.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-204.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This will unveil some new files within the project. Among them is the <code>Main.class</code> file. This is called a bytecode. When you hit the Run button, the Java compiler compiled your code from the <code>Main.java</code> file into this bytecode.</p>
<p>Now, modify the existing Hello World code as follows:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
    System.out.println(<span class="hljs-string">"Hello world!"</span>);
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NotMain</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>{
    System.out.println(<span class="hljs-string">"Not hello world!"</span>);
  }
}
</code></pre>
<p>As you can see, a new class called <code>NotMain</code> has been added. Go ahead and hit the <strong>Run</strong> button once more while keeping your eyes on the <strong>Files</strong> menu.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-206.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>A new bytecode named <code>NotMain.class</code> has showed up. This means that for every class you have within your entire codebase, the compiler will create a separate bytecode.</p>
<p>This creates confusion about which class is the entry-point to this program. To solve this issue, Java uses the class that matches the source code file name as the entry-point to this program.</p>
<p>Enough about the class, now let's look at the function inside it:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
    System.out.println(<span class="hljs-string">"Hello world!"</span>);
  }
}
</code></pre>
<p>The <code>public static void main (String[] args)</code> function is special in Java. If you have experience with languages like C, C++ or Go, you should already know that every program in those languages has a main function. The execution of the program begins from this main function.</p>
<p>In Java, you have to write this function as exactly <code>public static void main (String[] args)</code> otherwise it won't work. In fact, if you change it even a little bit Java will start to scream.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-207.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The return type has changed from <code>void</code> to <code>int</code> and the function now returns <code>0</code> at the end. As you can see in the console, it says:</p>
<pre><code><span class="hljs-built_in">Error</span>: Main method must <span class="hljs-keyword">return</span> a value <span class="hljs-keyword">of</span> type <span class="hljs-keyword">void</span> <span class="hljs-keyword">in</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span>, <span class="hljs-title">please</span> 
<span class="hljs-title">define</span> <span class="hljs-title">the</span> <span class="hljs-title">main</span> <span class="hljs-title">method</span> <span class="hljs-title">as</span>:
   <span class="hljs-title">public</span> <span class="hljs-title">static</span> <span class="hljs-title">void</span> <span class="hljs-title">main</span>(<span class="hljs-title">String</span>[] <span class="hljs-title">args</span>)</span>
</code></pre><p>Listen to that suggestion and revert your program back to how it was before.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
    System.out.println(<span class="hljs-string">"Hello world!"</span>);
  }
}
</code></pre>
<p>The <code>main</code> method is a <code>public</code> method and the <code>static</code> means, you can call it without instantiating its class.</p>
<p>The <code>void</code> means that the function doesn't return any value and the <code>String[] args</code> means that the function takes an array of strings as an argument. This array holds command line arguments passed to the program during execution.</p>
<p>The <code>System.out.println</code> prints out strings on the terminal. In the example above, <code>"Hello world!"</code> has been passed to the function, so you get <code>Hello world!</code> printed on the terminal.</p>
<p>In Java, every statement ends with a semicolon. <strong>Unlike JavaScript or Python, semicolons in Java are mandatory</strong>. Leaving one out will cause the compilation to fail.</p>
<p>That's pretty much it for this program. If you didn't understand every aspect of this section word by word, don't worry. Things will become much clearer as you go forward.</p>
<p>For now, remember that the top level <code>public class</code> in a Java source file has to match the file name, and the main function of any Java program has to be defined as <code>public static void main(String[] args)</code>.</p>
<h3 id="heading-what-is-jvm">What is JVM?</h3>
<p>I've uttered the word "bytecode" a few times already in the previous section. I've also said that Java is "cross-platform" which means code written and compiled in one platform can run on any platform that has Java installed on it.</p>
<p>You see, your processor doesn't understand English. In fact the only thing it understands are zeros and ones, aka binary.</p>
<p>When you write and compile a C++ program it results in a binary file. Your processor understands it and based on the program's targeted platform, this file can be different.</p>
<p>Take an AMD64 and an ARMv8-A processor for example. These processors have different instruction sets. So in order to run your program on these two different platforms, you'll have to compile them separately.</p>
<p>But a Java program can be written once and run anywhere. I hope you remember the bytecodes we talked about in the previous section. When you compile Java code it doesn't result in binary but rather in bytecode.</p>
<p>This bytecode is not entirely binary but it's also not human readable. In fact, your processor can't read it either.</p>
<p>So instead of throwing this bytecode at the CPU, we instead run it through the Java Virtual Machine or JVM for short. JVM then reads and interprets the bytecode to the CPU.</p>
<p>If you would like to understand the architecture of JVM at a deeper level, I would suggest <a target="_blank" href="https://www.freecodecamp.org/news/author/theawesomenayak/">Siben Nayak</a>'s <a target="_blank" href="https://www.freecodecamp.org/news/jvm-tutorial-java-virtual-machine-architecture-explained-for-beginners/">in-depth article</a> on the topic.</p>
<h3 id="heading-what-is-jre-and-jdk">What is JRE and JDK?</h3>
<p>JRE stands for Java Runtime Environment and JDK stands for Java Development Kit.</p>
<p>The JRE or Java Runtime Environment packages together an implementation of the JVM along with a set of libraries required for running Java programs.</p>
<p>The JDK, on the other hand, packages the JRE along with all the necessary libraries for developing Java programs.</p>
<p>So if you want to run Java programs on your computer you install the JRE. If you want to develop Java programs yourself, you install the JDK. There are multiple implementation of the JDK.</p>
<p>There is the <a target="_blank" href="https://www.oracle.com/java/technologies/downloads/">Java SE (Standard Edition) Development Kit</a> from Oracle, then there is the <a target="_blank" href="https://openjdk.org/">OpenJDK</a>, an official reference implementation of Java SE (Standard Edition) Development Kit.</p>
<p>As you can tell from the name of OpenJDK, it's open-source. So there are multiple builds of it. If you're on a Linux machine and use your distro's package manager to install JDK, it's highly likely that you'll install an OpenJDK build such as <a target="_blank" href="https://adoptium.net/">Adoptium</a>, <a target="_blank" href="https://docs.microsoft.com/en-us/java/openjdk/">Microsoft Build of OpenJDK</a> and so on.</p>
<p>I hope that you understand that JRE is a superset of JVM and JDK is a superset of JRE. Don't worry about different implementations or builds at the moment, you'll get your hands on them when the time comes.</p>
<h2 id="heading-how-to-setup-java-on-your-computer">How to Setup Java on Your Computer</h2>
<p>First, head over to <a target="_blank" href="https://www.oracle.com/java/technologies/downloads/">https://www.oracle.com/java/technologies/downloads/</a> and download the latest version of the <strong>Java SE Development Kit</strong> according to the platform you're on:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-208.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once the download has finished, start the installer and go through the installation process by hitting the Next buttons. Finish it by hitting the Close button on the last page.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/image-235.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The installation process may vary on macOS and Linux but you should be able to figure it out by yourself.</p>
<p>Once the installation has finished, execute the following command on your terminal:</p>
<pre><code>java --version

# java <span class="hljs-number">18.0</span><span class="hljs-number">.2</span> <span class="hljs-number">2022</span><span class="hljs-number">-07</span><span class="hljs-number">-19</span>
# Java(TM) SE Runtime Environment (build <span class="hljs-number">18.0</span><span class="hljs-number">.2</span>+<span class="hljs-number">9</span><span class="hljs-number">-61</span>)
# Java HotSpot(TM) <span class="hljs-number">64</span>-Bit Server VM (build <span class="hljs-number">18.0</span><span class="hljs-number">.2</span>+<span class="hljs-number">9</span><span class="hljs-number">-61</span>, mixed mode, sharing)
</code></pre><p>If it works, you've successfully install Java SE Development Kit on your computer. If you want to use OpenJDK instead, feel free to download <a target="_blank" href="https://docs.microsoft.com/en-us/java/openjdk/">Microsoft Build of OpenJDK</a> or <a target="_blank" href="https://adoptium.net/">Adoptium</a> and go through the installation process. </p>
<p>For the simple example programs that we're going to write in this article, it won't matter which JDK you're using. But in real life, make sure that your JDK version plays nicely with the type of project you're working on.</p>
<h2 id="heading-how-to-install-a-java-ide-on-your-computer">How to Install a Java IDE on Your Computer</h2>
<p>When it comes to Java, <a target="_blank" href="https://www.jetbrains.com/idea/">IntelliJ IDEA</a> is undeniably the best IDE out there. Even Google uses it as a base for their <a target="_blank" href="https://developer.android.com/studio">Android Studio</a>.</p>
<p>The ultimate version of the IDE can <a target="_blank" href="https://www.jetbrains.com/idea/buy/">cost an individual up-to $149.00 per year</a>. But if you're student, you can get <a target="_blank" href="https://www.jetbrains.com/community/education/#students">educational licenses</a> for all JetBrains products for free.</p>
<p>There is also the completely free and open-source community edition. This is the one we'll be using throughout the entire book.</p>
<p>Head over to the <a target="_blank" href="https://www.jetbrains.com/idea/download/">IntelliJ IDEA download page</a>, and download the community edition for your platform.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-344.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once the download finishes, use the installer to install IntelliJ IDEA like any other software.</p>
<h2 id="heading-how-to-create-a-new-project-on-intellij-idea">How to Create a New Project on IntelliJ IDEA</h2>
<p>Use the shortcut from your start menu to start IntelliJ IDEA. The following window will show up:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-346.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Use the <strong>New Project</strong> button and a <strong>New Project</strong> window will show up:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-347.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Put a descriptive name for your project. Leave the rest of the options as they are and press the <strong>Create</strong> button.</p>
<p>The project creation shouldn't take longer than a moment and once it's done, the following window will show up:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-348.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>That's the project tool window on the left side. All your source code will live inside that <code>src</code> folder.</p>
<p>Right click on the <code>src</code> folder and go to <strong>New &gt; Java Class</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-349.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the next step, put a name, such as <code>Main</code> for your class and make sure <strong>Class</strong> is highlighted as the type.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-350.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>A new class will be created with a few lines of code.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-351.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Update the code as follows:</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">Main</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>{
        System.out.println(<span class="hljs-string">"Hello World!"</span>);
    }
}
</code></pre>
<p>To run this code, use the green play button on the right side of the top bar.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-352.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The code will run and the output will be shown in the integrated terminal at the bottom of the window.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/image-353.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Congratulations, you've successfully recreated the previously discussed <code>HelloWorld</code> program in IntelliJ IDEA.</p>
<h2 id="heading-how-to-work-with-variables-in-java">How to Work with Variables in Java</h2>
<p>To work with different kinds of data in Java, you can create variables of different types. For example, if you want to store your age in a new variable, you can do so like this:</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">Main</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-comment">// &lt;type&gt; &lt;name&gt;</span>
        <span class="hljs-keyword">int</span> age;

    }

}
</code></pre>
<p>You start by writing out the type of data or variable. Since <code>age</code> is a whole number, its type will be integer or <code>int</code> for short, followed by the name of the variable <code>age</code> and a semicolon.</p>
<p>At the moment, you've declared the variable but you haven't initialized it. In other words, the variable doesn't have any value. You can initialize the variable as follows:</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">Main</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-comment">// &lt;type&gt; &lt;name&gt;</span>
        <span class="hljs-keyword">int</span> age;

        <span class="hljs-comment">// &lt;name&gt; = &lt;value&gt;</span>
        age = <span class="hljs-number">27</span>;

        <span class="hljs-comment">// prints the age on the terminal</span>
        System.out.println(<span class="hljs-string">"I am "</span> + age + <span class="hljs-string">" years old."</span>);

    }

}
</code></pre>
<p>When assigning a value, you start by writing the name of the variable you want to initialize, followed by an equal sign (it's called the assignment operator) then the value you want to assign to the variable. And don't forget the semicolon at the end.</p>
<p>The <code>System.out.println();</code> function call will print the line <code>I am 27 years old.</code> to the console. In case you're wondering, using a plus sign is one of the many ways to dynamically print out variables in the middle of a sentence.</p>
<p>One thing that you have to keep in mind is you can not use an uninitialized variable in Java. So if you comment out the line <code>age = 27</code> by putting two forward slashes in front of it and try to compile the code, the compiler will throw the following error message at you:</p>
<pre><code>Exception <span class="hljs-keyword">in</span> thread <span class="hljs-string">"main"</span> java.lang.Error: Unresolved compilation problem: 
    The local variable age may not have been initialized

    at variables.Main.main(Main.java:<span class="hljs-number">13</span>)
</code></pre><p>The line <code>The local variable age may not have been initialized</code> indicates that the variable has not been initialized.</p>
<p>Instead of declaring and initializing the variable in different lines, you can do that in one go as follows:</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">Main</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-comment">// &lt;type&gt; &lt;name&gt; = &lt;value&gt;</span>
        <span class="hljs-keyword">int</span> age = <span class="hljs-number">27</span>;

        <span class="hljs-comment">// prints the age on the terminal</span>
        System.out.println(<span class="hljs-string">"I am "</span> + age + <span class="hljs-string">" years old."</span>);

    }

}
</code></pre>
<p>The code should be back to normal again. Also, you can change the value of a variable as many times as you want in your code.</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">Main</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> age = <span class="hljs-number">27</span>;

        <span class="hljs-comment">// updates the value to be 28 instead of 27</span>
        age = <span class="hljs-number">28</span>;

        System.out.println(<span class="hljs-string">"I am "</span> + age + <span class="hljs-string">" years old."</span>);

    }

}
</code></pre>
<p>In this code, the value of <code>age</code> will change from 27 to 28 because you're overwriting it just before printing.</p>
<p>Keep in mind, while you can assign values to a variables as many times as you want, you can not declare the same variable twice.</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">Main</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-comment">// &lt;type&gt; &lt;name&gt; = &lt;value&gt;</span>
        <span class="hljs-keyword">int</span> age = <span class="hljs-number">27</span>;

        <span class="hljs-keyword">int</span> age = <span class="hljs-number">28</span>;

        <span class="hljs-comment">// prints the age on the terminal</span>
        System.out.println(<span class="hljs-string">"I am "</span> + age + <span class="hljs-string">" years old."</span>);

    }

}
</code></pre>
<p>If you try to compile this code, the compiler will throw the following error message at you:</p>
<pre><code>Exception <span class="hljs-keyword">in</span> thread <span class="hljs-string">"main"</span> java.lang.Error: Unresolved compilation problem: 
    Duplicate local variable age

    at variables.Main.main(Main.java:<span class="hljs-number">9</span>)
</code></pre><p>The line <code>Duplicate local variable age</code> indicates that the variable has already been declared.</p>
<p>Apart from variables, you may find the term "literal" on the internet. Literals are variables with hardcoded values.</p>
<p>For example, here, <code>age = 27</code> and it's not dynamically calculated. You've written the value directly in the source code. So <code>age</code> is an integer literal.</p>
<h3 id="heading-what-are-the-rules-for-declaring-variables">What Are the Rules for Declaring Variables?</h3>
<p>There are some rules when it comes to naming your variables in Java. You can name it anything as long as it doesn't start with a number and it can't contain any spaces in the name.</p>
<p>Although, you can start a variable name with an underscore (_) or a dollar sign ($), not being mindful of their usage can make your code hard to read. Variable names are also case sensitive. So <code>age</code> and <code>AGE</code> are two different variables.</p>
<p>Another important thing to remember is you can not use any of the keywords reserved by Java. There are around 50 of them at present. You can learn about these keywords from the <a target="_blank" href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html">official documentation</a> but don't worry about memorizing them.</p>
<p>As you keep practicing, the important ones will slip into your neurons automatically. And if you still manage to mess up a variable declaration, the compiler will be there to remind you that something's wrong.</p>
<p>Apart from the rules, there are some conventions that you should follow:</p>
<ul>
<li>Start your variable name with small letter and not any special character (like an underscore or dollar sign).</li>
<li>If the variable name has multiple words, use camel case: <code>firstName</code>, <code>lastName</code></li>
<li>Don't use single letter names: <code>f</code>, <code>l</code></li>
</ul>
<p>As long as you follow these rules and conventions, you're good to go. If you'd like to learn more about naming conventions in general, <a target="_blank" href="https://www.freecodecamp.org/news/programming-naming-conventions-explained/">checkout my article on the topic</a>.</p>
<h3 id="heading-what-are-final-variables">What Are <code>final</code> Variables?</h3>
<p>A <code>final</code> variable in Java can be initialized only once. So if you declare a variable as <code>final</code>, you can not reassign it.</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">Main</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-comment">// final &lt;type&gt; &lt;name&gt; = &lt;value&gt;</span>
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> age = <span class="hljs-number">27</span>;

        age = <span class="hljs-number">28</span>;

        System.out.println(<span class="hljs-string">"I am "</span> + age + <span class="hljs-string">" years old."</span>);

    }

}
</code></pre>
<p>Since the <code>age</code> variable has been declared as <code>final</code>, the code will throw the following error message at you:</p>
<pre><code>Exception <span class="hljs-keyword">in</span> thread <span class="hljs-string">"main"</span> java.lang.Error: Unresolved compilation problem: 
    The final local variable age cannot be assigned. It must be blank and not using a compound assignment

    at variables.Main.main(Main.java:<span class="hljs-number">9</span>)
</code></pre><p>However, if you leave the variable uninitialized while declaring, the code will work:</p>
<pre><code>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) {
        <span class="hljs-comment">// final &lt;type&gt; &lt;name&gt;</span>
        final int age;

        age = <span class="hljs-number">28</span>;

        <span class="hljs-comment">// prints the age on the terminal</span>
        System.out.println(<span class="hljs-string">"I am "</span> + age + <span class="hljs-string">" years old."</span>);

    }

}
</code></pre><p>So, declaring a variable as <code>final</code> will limit your ability to reassign its value. If you leave it uninitialized, you'll be able to initialize it as usual.</p>
<h2 id="heading-what-are-the-primitive-data-types-in-java">What are the Primitive Data Types in Java?</h2>
<p>At a high level, there are two types of data in Java. There are the "primitives types" and the "non-primitive" or "reference types".</p>
<p>Primitive types store values. For example, <code>int</code> is a primitive type and it stores an integer value.</p>
<p>A reference type, on the other hand, stores the reference to a memory location where a dynamic object is being stored.</p>
<p>There are eight primitive data types in Java.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>TYPE</td><td>EXPLANATION</td></tr>
</thead>
<tbody>
<tr>
<td><code>byte</code></td><td>8-bit signed integer within the range of -128 to 127</td></tr>
<tr>
<td><code>short</code></td><td>16-bit signed integer within the range of -32,768 to 32,767</td></tr>
<tr>
<td><code>int</code></td><td>32-bit signed integer within the range of -2147483648 to 2147483647</td></tr>
<tr>
<td><code>long</code></td><td>64-bit signed integer within the range of -9223372036854775808 to 9223372036854775807</td></tr>
<tr>
<td><code>float</code></td><td>single-precision 32-bit floating point within the range of 1.4E-45 to 3.4028235E38</td></tr>
<tr>
<td><code>double</code></td><td>double-precision 64-bit floating point within the range of 4.9E-324 to 1.7976931348623157E308</td></tr>
<tr>
<td><code>boolean</code></td><td>It can be either <code>true</code> or <code>false</code></td></tr>
<tr>
<td><code>char</code></td><td>single 16-bit Unicode character within the range of <code>\u0000</code> (or 0) to <code>\uffff</code> (or 65,535 inclusive)</td></tr>
</tbody>
</table>
</div><p>Yeah yeah I know the table looks scary but don't stress yourself. You don't have to memorize them.</p>
<p>You will not need to think about these ranges very frequently, and even if you do, there are ways to print them out within your Java code.</p>
<p>However, if you do not understand what a bit is, I would recommend <a target="_blank" href="https://www.freecodecamp.org/news/binary-definition/">this short article</a> to learn about binary.</p>
<p>You've already learned about declaring an integer in the previous section. You can declare a <code>byte</code>, <code>short</code>, and <code>long</code> in the same way.</p>
<p>Declaring a <code>double</code> also works the same way, except you can assign a number with a decimal point instead of an integer:</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">Main</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">double</span> gpa = <span class="hljs-number">4.8</span>;

        System.out.println(<span class="hljs-string">"My GPA is "</span> + gpa + <span class="hljs-string">"."</span>);

    }
}
</code></pre>
<p>If you assign an <code>int</code> to the <code>double</code>, such as <code>4</code> instead of <code>4.8</code>, the output will be <code>4.0</code> instead of <code>4</code>, because <code>double</code> will always have a decimal point.</p>
<p>Since <code>double</code> and <code>float</code> are similar, you may think that replacing the <code>double</code> keyword with <code>float</code> will convert this variable to a floating point number – but that's not correct. You'll have to append a <code>f</code> or <code>F</code> after the value:</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">Main</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">float</span> gpa = <span class="hljs-number">4.8f</span>;

        System.out.println(<span class="hljs-string">"My GPA is "</span> + gpa + <span class="hljs-string">"."</span>);

    }
}
</code></pre>
<p>This happens because, by default, every number with a decimal point is treated as a <code>double</code> in Java. If you do not append the <code>f</code>, the compiler will think you're trying to assign a <code>double</code> value to a <code>float</code> variable.</p>
<p><code>boolean</code> data can hold either <code>true</code> or <code>false</code> values.</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">Main</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">boolean</span> isWeekend = <span class="hljs-keyword">false</span>;

        System.out.println(isWeekend); <span class="hljs-comment">// false</span>

    }
}
</code></pre>
<p>As you can imagine, <code>false</code> can be treated as a no and <code>true</code> can be treated as a yes. </p>
<p>Booleans will become much more useful once you've learned about conditional statements. So for now, just remember what they are and what they can hold.</p>
<p>The <code>char</code> type can hold any Unicode character within a certain range.</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">Main</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">char</span> percentSign = <span class="hljs-string">'%'</span>;

        System.out.println(percentSign); <span class="hljs-comment">// %</span>

    }
}
</code></pre>
<p>In this example, you've saved the percent sign within a <code>char</code> variable and printed it out on the terminal.</p>
<p>You can also use Unicode escape sequences to print out certain symbols.</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">Main</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">char</span> copyrightSymbol = <span class="hljs-string">'\u00A9'</span>;

        System.out.println(copyrightSymbol); <span class="hljs-comment">// ©</span>

    }
}
</code></pre>
<p>The Unicode escape sequence for the copyright symbol, for example, is <code>\u00A9</code> and you can find more Unicode escape sequences on <a target="_blank" href="https://www.rapidtables.com/code/text/unicode-characters.html">this website</a>.</p>
<p>Among these 8 types of data, you'll be working with <code>int</code>, <code>double</code>, <code>boolean</code>, and <code>char</code> majority of the time.</p>
<h3 id="heading-what-is-type-conversion-or-casting">What is Type Conversion or Casting?</h3>
<p>Type conversion in Java can be either "implicit" or "explicit". When the compiler converts a smaller type of data to a larger one automatically, it's known as an implicit or narrowing type conversion.</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">Main</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> number1 = <span class="hljs-number">8</span>;
        <span class="hljs-keyword">double</span> number2 = number1;

        System.out.println(number2); <span class="hljs-comment">// 8.0</span>
    }

}
</code></pre>
<p>Since a double is larger than an integer, the compiler could easily perform the conversion. If you try to do the reverse however, you'll face the following error from the compiler:</p>
<pre><code>Exception <span class="hljs-keyword">in</span> thread <span class="hljs-string">"main"</span> java.lang.Error: Unresolved compilation problem: 
    Type mismatch: cannot convert <span class="hljs-keyword">from</span> double to int

    at operators.Main.main(Main.java:<span class="hljs-number">7</span>)
</code></pre><p>When performing an implicit conversion, the flow of conversion should be as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/widening-conversion.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can of course go from a <code>short</code> to a <code>double</code>, for example, skipping the others in between. </p>
<p>You can also go from smaller data types to larger ones. That's called an explicit or widening type conversion.</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> datatypes;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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">double</span> number1 = <span class="hljs-number">8.5</span>;
        <span class="hljs-keyword">int</span> number2 = (<span class="hljs-keyword">int</span>) number1;

        System.out.println(number2); <span class="hljs-comment">// 8</span>
    }

}
</code></pre>
<p>Previously you've seen that if you try to convert a larger data type to a smaller one, the compiler complains. But when you add the <code>(int)</code> cast operator explicitly, you show the compiler who's boss.</p>
<p>In doing so, you lose a part of your data. If you change the initial <code>double</code> number from <code>8.5</code> to just <code>8.0</code>, you'll not lose any information. So whenever you're performing an explicit conversion, be careful.</p>
<p>You can also convert a <code>char</code> to an <code>int</code> as follows:</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">Main</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">char</span> character = <span class="hljs-string">'F'</span>;
        <span class="hljs-keyword">int</span> number = character;

        System.out.println(number); <span class="hljs-comment">// 70</span>
    }

}
</code></pre>
<p><code>70</code> is the ASCII code for the character <code>F</code> – that's why the output was like this. If you'd like to learn more about ASCII codes, my colleague <a target="_blank" href="https://www.freecodecamp.org/news/author/kris/">Kris Koishigawa</a> has written <a target="_blank" href="https://www.freecodecamp.org/news/ascii-table-hex-to-ascii-value-character-code-chart-2/">an excellent article</a> on the topic.</p>
<p>The flow of conversion in this case will be the opposite of what you've seen already.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/narrowing-conversion.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I'd suggest you to experiment by converting various values from one type to another and see what happens. This will deepen your understanding and make you confident.</p>
<h3 id="heading-what-are-wrapper-classes-in-java">What are Wrapper Classes in Java?</h3>
<p>Wrapper classes can wrap around primitive datatypes and turn them into reference types. Wrapper classes are available for all eight primitive data types.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Primitive Type</td><td>Wrapper Class</td></tr>
</thead>
<tbody>
<tr>
<td><code>int</code></td><td><code>Integer</code></td></tr>
<tr>
<td><code>long</code></td><td><code>Long</code></td></tr>
<tr>
<td><code>short</code></td><td><code>Short</code></td></tr>
<tr>
<td><code>byte</code></td><td><code>Byte</code></td></tr>
<tr>
<td><code>boolean</code></td><td><code>Boolean</code></td></tr>
<tr>
<td><code>char</code></td><td><code>Character</code></td></tr>
<tr>
<td><code>float</code></td><td><code>Float</code></td></tr>
<tr>
<td><code>double</code></td><td><code>Double</code></td></tr>
</tbody>
</table>
</div><p>You can use these wrapper classes as follows:</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">Main</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>{
        Integer age = <span class="hljs-number">27</span>;
        Double gpa = <span class="hljs-number">4.8</span>;

        System.out.println(age); <span class="hljs-comment">// 27</span>
        System.out.println(gpa); <span class="hljs-comment">// 4.8</span>
    }
}
</code></pre>
<p>All you have to do is replace the primitive data type with the equivalent wrapper class. These reference types also have methods for extracting the primitive type from them.</p>
<p>For example, <code>age.intValue()</code> will return the age as a primitive integer and the <code>gpa.doubleValue()</code> will return the GPA in a primitive double type.</p>
<p>There are such methods for all eight datatypes. Although you'll use the primitive types most of the time, these wrapper classes will be handy in some scenarios we'll discuss in a later section.</p>
<h2 id="heading-how-to-use-operators-in-java">How to Use Operators in Java</h2>
<p>Operators in programming are certain symbols that tell the compiler to perform certain operations such as arithmetic, relational, or logical operations.</p>
<p>Although there are six types of operators in Java, I won't talk about bitwise operators here. Discussing bitwise operators in a beginner guide can make it intimidating.</p>
<h3 id="heading-what-are-the-arithmetic-operators">What Are the Arithmetic Operators?</h3>
<p>Arithmetic operators are the ones that you can use to perform arithmetic operations. There are five of them:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>OPERATOR</td><td>OPERATION</td></tr>
</thead>
<tbody>
<tr>
<td><code>+</code></td><td>Addition</td></tr>
<tr>
<td><code>-</code></td><td>Subtraction</td></tr>
<tr>
<td><code>*</code></td><td>Multiplication</td></tr>
<tr>
<td><code>/</code></td><td>Division</td></tr>
<tr>
<td><code>%</code></td><td>Remainder (Modulo/Modulus)</td></tr>
</tbody>
</table>
</div><p>Addition, subtraction, multiplication, and division operations are pretty self-explanatory. Have a look at the following code example to understand:</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">Main</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> number1 = <span class="hljs-number">10</span>;
        <span class="hljs-keyword">int</span> number2 = <span class="hljs-number">5</span>;

        System.out.println(number1 + number2); <span class="hljs-comment">// 15</span>
        System.out.println(number1 - number2); <span class="hljs-comment">// 5</span>
        System.out.println(number1 * number2); <span class="hljs-comment">// 50</span>
        System.out.println(number1 / number2); <span class="hljs-comment">// 2</span>
        System.out.println(number1 % number2); <span class="hljs-comment">// 0</span>

    }

}
</code></pre>
<p>Outputs from the first four operations need no explanation. In the last operation, you've performed a modulo/modulus operation using the <code>%</code> symbol. The result is <code>0</code> because if you divide 10 by 2, there'll be nothing left (no remainder).</p>
<p>Addition and multiplication operations are quite simple. But, when performing a subtraction, if the first operand is larger than the second operand, the result will be a negative number, just like in real life.</p>
<p>The type of data you're working with makes a difference in the result of division and modulo operations.</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">Main</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> number1 = <span class="hljs-number">8</span>;
        <span class="hljs-keyword">int</span> number2 = <span class="hljs-number">5</span>;

        System.out.println(number1 / number2); <span class="hljs-comment">// 1</span>
    }

}
</code></pre>
<p>Although the result of this operation should've been 1.6 it didn't happen because in Java, if you divide an integer by another integer, the result will be an integer. But if you change both or one of them to a float/double, everything will be back to normal.</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">Main</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">double</span> number1 = <span class="hljs-number">8</span>;
        <span class="hljs-keyword">double</span> number2 = <span class="hljs-number">5</span>;

        System.out.println(number1 / number2); <span class="hljs-comment">// 1.6</span>
    }

}
</code></pre>
<p>This principle applies to the modulo operations as well. If both or one of the operands are a float/double, the result will be a float/double.</p>
<h3 id="heading-what-are-the-assignment-operators">What Are the Assignment Operators?</h3>
<p>You've already worked with the assignment operator in a previous section.</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">Main</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-comment">// &lt;type&gt; &lt;name&gt; = &lt;value&gt;</span>
        <span class="hljs-keyword">int</span> age = <span class="hljs-number">27</span>;

        <span class="hljs-comment">// prints the age on the terminal</span>
        System.out.println(age);

    }

}
</code></pre>
<p>When you use the <code>=</code> symbol to assign a value to a variable, it works as an assignment operator. But, this is not the only form of this operator.</p>
<p>Combining the regular assignment operator with the arithmetic operators, you can achieve different results.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>OPERATOR</td><td>OPERATION</td><td>EQUIVALENT TO</td></tr>
</thead>
<tbody>
<tr>
<td><code>+=</code></td><td><code>a += b</code></td><td><code>a = a + b</code></td></tr>
<tr>
<td><code>-=</code></td><td><code>a -= b</code></td><td><code>a = a - b</code></td></tr>
<tr>
<td><code>*=</code></td><td><code>a *= b</code></td><td><code>a = a * b</code></td></tr>
<tr>
<td><code>/=</code></td><td><code>a /= b</code></td><td><code>a = a / b</code></td></tr>
<tr>
<td><code>%=</code></td><td><code>a %= b</code></td><td><code>a = a % b</code></td></tr>
</tbody>
</table>
</div><p>The following code example should make things clearer:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> operators;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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">double</span> number1 = <span class="hljs-number">10</span>;
        <span class="hljs-keyword">double</span> number2 = <span class="hljs-number">5</span>;

        number1 += number2;

        System.out.println(number1); <span class="hljs-comment">// 15</span>
    }

}
</code></pre>
<p>The other operators work the same. They operate and then assign the resultant value to the left operand.</p>
<p>I could demonstrate the other ones using code but I think if you try them out yourself, you'll get a better understanding. After all, experimentation and practice are the only ways to solidify your knowledge.</p>
<h3 id="heading-what-are-the-relational-operators">What Are the Relational Operators?</h3>
<p>Relational operators are used to check the relation between operands. Such as whether an operand is equal to another operand or not.</p>
<p>These relational operators return either <code>true</code> or <code>false</code> depending on the operation you've performed.</p>
<p>There are six relational operators in Java.</p>
<table>
<thead>
<tr>
<th>OPERATOR</th>
<th>EXPLANATION</th>
<th>USAGE</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>==</code></td>
<td>Is Equal To</td>
<td><code>5 == 8</code> returns <code>false</code></td>
</tr>
<tr>
<td><code>!=</code></td>
<td>Is Not Equal To</td>
<td><code>5 != 8</code> returns <code>true</code></td>
</tr>
<tr>
<td><code>&gt;</code></td>
<td>Is Greater Than</td>
<td><code>5 &gt; 8</code> returns <code>false</code></td>
</tr>
<tr>
<td><code>&lt;</code></td>
<td>Is Less Than</td>
<td><code>5 &lt; 8</code> returns <code>true</code></td>
</tr>
<tr>
<td><code>&gt;=</code></td>
<td>Greater Than or Equal To</td>
<td><code>5 &gt;= 8</code> returns <code>false</code></td>
</tr>
<tr>
<td><code>&lt;=</code></td>
<td>Less Than or Equal To</td>
<td><code>5 &lt;= 8</code> returns <code>true</code></td>
</tr>
</tbody>
</table>

<p>The following code example demonstrates the usage of these operators:</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">Main</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">double</span> number1 = <span class="hljs-number">10</span>;
        <span class="hljs-keyword">double</span> number2 = <span class="hljs-number">5</span>;

        System.out.println(number1 == number2); <span class="hljs-comment">// false</span>
        System.out.println(number1 != number2); <span class="hljs-comment">// true</span>
        System.out.println(number1 &gt; number2); <span class="hljs-comment">// true</span>
        System.out.println(number1 &lt; number2); <span class="hljs-comment">// false</span>
        System.out.println(number1 &gt;= number2); <span class="hljs-comment">// true</span>
        System.out.println(number1 &lt;= number2); <span class="hljs-comment">// false</span>
    }

}
</code></pre>
<p>Practical usage of these operators will become much apparent to you once you've learned about conditional statements in a later section.</p>
<p>You can also use these operators with characters.</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">Main</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">char</span> smallLetter = <span class="hljs-string">'a'</span>;
        <span class="hljs-keyword">char</span> capitalLetter = <span class="hljs-string">'A'</span>;

        System.out.println(smallLetter &gt; capitalLetter); <span class="hljs-comment">// ???</span>
    }

}
</code></pre>
<p>What do you think the output of this code will be? Find out for yourself. Remember the ASCII values of the characters? They play a role in the output of this program.</p>
<h3 id="heading-what-are-the-logical-operators">What Are the Logical Operators?</h3>
<p>Imagine a scenario where a program you've made can only be used by people who are 18 and up but not over 40 years old. So the logic should be as follows:</p>
<pre><code>can run the program <span class="hljs-keyword">if</span> -&gt;
    age &gt;= <span class="hljs-number">18</span> and age &lt;= <span class="hljs-number">40</span>
</code></pre><p>Or in another scenario, a user has to be a student of your school or member of the library to borrow books. In this case the logic should be as follows:</p>
<pre><code>can borrow books <span class="hljs-keyword">if</span> -&gt;
    isSchoolStudent or isLibraryMember
</code></pre><p>These logical decisions can be made using logical operators. There are three such operators in Java.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>OPERATOR</td><td>USAGE</td><td>EXPLANATION</td></tr>
</thead>
<tbody>
<tr>
<td>Logical And (<code>&amp;&amp;</code>)</td><td><code>age &gt;= 18 &amp;&amp; age &lt;= 40</code></td><td>Evaluates to true, only if both conditions are true</td></tr>
<tr>
<td>Logical Or (`</td><td></td><td>`)</td><td>`isSchoolStudent</td><td></td><td>isLibraryMember`</td><td>Evaluates to true if one of the two or both conditions are true</td></tr>
<tr>
<td>Not (<code>!</code>)</td><td><code>!isLibraryMember</code></td><td>Evaluates to false if the inner condition evaluates to true and vise versa</td></tr>
</tbody>
</table>
</div><p>Let's see these operators in code. First, the logical <code>and</code> operator:</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">Main</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> age = <span class="hljs-number">20</span>;

        System.out.println(age &gt;= <span class="hljs-number">18</span> &amp;&amp; age &lt;= <span class="hljs-number">40</span>); <span class="hljs-comment">// true</span>
    }

}
</code></pre>
<p>In this case, there are two conditions on either side of the <code>&amp;&amp;</code> operator. If and only if both conditions evaluate to <code>true</code>, the <code>and</code> operation evaluates to <code>true</code>.</p>
<p>If the first condition evaluates to <code>false</code>, the computer will not evaluate the rest of the conditions and return <code>false</code>. Because if the first one evaluates to <code>false</code>, then there is no way for the entire operation to evaluate to <code>true</code>.</p>
<p>The logical <code>or</code> operator works similarly, but in this case, if any of the conditions are true then the entire operation will evaluate to true:</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">Main</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">boolean</span> isSchoolStudent = <span class="hljs-keyword">true</span>;
        <span class="hljs-keyword">boolean</span> isLibraryMember = <span class="hljs-keyword">false</span>;

        System.out.println(isSchoolStudent || isLibraryMember); <span class="hljs-comment">// true</span>
    }

}
</code></pre>
<p>If the first condition of a logical <code>or</code> operation evaluates to <code>true</code>, the computer will not evaluate the rest of the conditions and return <code>true</code>. Because if the first condition evaluates to <code>true</code> the operation will evaluate to <code>true</code> regardless of what the other conditions evaluate to.</p>
<p>Finally the <code>not</code> operator evaluates to the opposite of whatever its condition evaluates to. Take a look at the following code 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">Main</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">boolean</span> isLibraryMember = <span class="hljs-keyword">true</span>;

        System.out.println(isLibraryMember); <span class="hljs-comment">// true</span>
        System.out.println(!isLibraryMember); <span class="hljs-comment">// false</span>
    }

}
</code></pre>
<p>As you can see, the not operator returns the opposite of the given <code>boolean</code> value. The not operator is a unary operator, meaning it operates on a single operand.</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">Main</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">boolean</span> isLibraryMember = <span class="hljs-keyword">true</span>;
        <span class="hljs-keyword">boolean</span> isSchoolStudent = <span class="hljs-keyword">false</span>;

        System.out.println(!isSchoolStudent || isLibraryMember); <span class="hljs-comment">// true</span>
    }

}
</code></pre>
<p>In this example, the not operator turns <code>isSchoolStudent</code> into <code>true</code>, so the operation evaluates to <code>true</code>. However, if you modify the code as follows:</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">Main</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">boolean</span> isLibraryMember = <span class="hljs-keyword">true</span>;
        <span class="hljs-keyword">boolean</span> isSchoolStudent = <span class="hljs-keyword">false</span>;

        System.out.println(!(isSchoolStudent || isLibraryMember)); <span class="hljs-comment">// false</span>
    }

}
</code></pre>
<p>First, the logical or operation will take place and evaluate to <code>true</code>. The not operator will turn it into <code>false</code>.</p>
<p>Although you've used two operands with each operator, you can use as many as you want. You can also mix and match multiple operators together.</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">Main</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">boolean</span> isSchoolStudent = <span class="hljs-keyword">true</span>;
        <span class="hljs-keyword">boolean</span> isLibraryMember = <span class="hljs-keyword">false</span>;
        <span class="hljs-keyword">int</span> age = <span class="hljs-number">10</span>;

        System.out.println(isSchoolStudent || isLibraryMember &amp;&amp; age &gt; <span class="hljs-number">18</span>); <span class="hljs-comment">// ???</span>
    }

}
</code></pre>
<p>What do you think the output of this code will be? I'd recommend you find out by yourself. :)</p>
<h3 id="heading-what-are-the-unary-operators">What Are the Unary Operators?</h3>
<p>There are some operators that are used with one operand at a time and these are called the unary operators. Although there are five of them, I'll only discuss two.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>OPERATOR</td><td>EXPLANATION</td></tr>
</thead>
<tbody>
<tr>
<td>Increment (<code>++</code>)</td><td>Increments a given value by 1</td></tr>
<tr>
<td>Decrement (<code>--</code>)</td><td>Decrements a given value by 1</td></tr>
</tbody>
</table>
</div><p>The following code example will demonstrate them nicely:</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">Main</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> score = <span class="hljs-number">95</span>;
        <span class="hljs-keyword">int</span> turns = <span class="hljs-number">11</span>;

        score++;
        turns--;

        System.out.println(score); <span class="hljs-comment">// 96</span>
        System.out.println(turns); <span class="hljs-comment">// 10</span>
    }

}
</code></pre>
<p>You can also use the operators as prefixes:</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">Main</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> score = <span class="hljs-number">95</span>;
        <span class="hljs-keyword">int</span> turns = <span class="hljs-number">11</span>;

        ++score;
        --turns;

        System.out.println(score); <span class="hljs-comment">// 96</span>
        System.out.println(turns); <span class="hljs-comment">// 10</span>
    }

}
</code></pre>
<p>So far this is simple. But there are some slight differences between the postfix and prefix syntaxes that you need to understand. Look at the following code:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> operators;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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> score = <span class="hljs-number">95</span>;


        System.out.println(++score); <span class="hljs-comment">// 96</span>
        System.out.println(score); <span class="hljs-comment">// 96</span>
    }

}
</code></pre>
<p>This is expected behavior. The prefix decrement operator will work the same. But look what happens if you switch to the postfix version:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> operators;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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> score = <span class="hljs-number">95</span>;


        System.out.println(score++); <span class="hljs-comment">// 95</span>
        System.out.println(score); <span class="hljs-comment">// 96</span>
    }

}
</code></pre>
<p>Confusing, isn't it? What do you think is the actual value of the variable right now? It's 96. Let me explain.</p>
<p>When using the postfix syntax within a print function, the print function encounters the variable first and then increments it. That's why the second line prints out the newly updated value.</p>
<p>In case of the prefix syntax, the function encounters the increment operator first and performs the operation. Then it goes on to printing the updated value.</p>
<p>This little difference may catch you off guard if you're not careful. Or you try to avoid incrementing or decrementing within function calls.</p>
<h2 id="heading-how-to-work-with-strings-in-java">How to Work with Strings in Java</h2>
<p>The <code>String</code> type in Java is one of the most commonly used reference types. It's a collection of characters that you can use to form lines of text in your program.</p>
<p>There are two ways of creating new strings in Java. The first one is the literal way:</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">Main</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>{
        String name = <span class="hljs-string">"Farhan"</span>;

        System.out.println(<span class="hljs-string">"My name is "</span> + name + <span class="hljs-string">"."</span>);
    }

}
</code></pre>
<p>As you can see, declaring and using a <code>String</code> this way is not very different from declaring the primitive types in Java.</p>
<p>The second way to create a new <code>String</code> is by using the <code>new</code> operator.</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">Main</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-comment">// &lt;type&gt; &lt;name&gt; = new &lt;type&gt;(&lt;value&gt;)</span>
        String name = <span class="hljs-keyword">new</span> String(<span class="hljs-string">"Farhan"</span>);

        System.out.println(<span class="hljs-string">"My name is "</span> + name + <span class="hljs-string">"."</span>);
    }

}
</code></pre>
<p>This program will work exactly like the previous one but there's a slight difference between the two.</p>
<p>The JVM maintains a portion of your computer's memory for storing strings. This portion is called the string pool.</p>
<p>Whenever you create a new <code>String</code> in the literal way, the JVM first checks if that <code>String</code> already exists in the pool. If it does, JVM will reuse it. If it doesn't, then the JVM will create it.</p>
<p>On the other hand, when you use the <code>new</code> operator, the JVM will always create a new <code>String</code> object no matter what. The following program demonstrates this concept clearly:</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">Main</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>{
        String literalString1 = <span class="hljs-string">"abc"</span>;
        String literalString2 = <span class="hljs-string">"abc"</span>;

        String objectString1 = <span class="hljs-keyword">new</span> String(<span class="hljs-string">"abc"</span>);
        String objectString2 = <span class="hljs-keyword">new</span> String(<span class="hljs-string">"abc"</span>);

        System.out.println(literalString1 == literalString2);
        System.out.println(objectString1 == objectString2);

    }

}
</code></pre>
<p>As you may already know, the <code>==</code> operator is used for checking equality. The output of this program will be:</p>
<pre><code><span class="hljs-literal">true</span>
<span class="hljs-literal">false</span>
</code></pre><p>Since <code>abc</code> was already in the string pool, the <code>literalString2</code> variable reuses that. In case of the object strings however, both of them are different entities.</p>
<h3 id="heading-how-to-format-a-string">How to Format a String</h3>
<p>You've already seen the usage of the <code>+</code> operator to sew strings together or format them in a specific way.</p>
<p>That approach works until you have a lot of additions to a string. It's easy to mess up the placements of the quotation marks.</p>
<p>A better way to format a string is the <code>String.format()</code> method.</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">Main</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>{
        String name = <span class="hljs-string">"Farhan"</span>;
        <span class="hljs-keyword">int</span> age = <span class="hljs-number">27</span>;

        String formattedString = String.format(<span class="hljs-string">"My name is %s and I'm %d years old."</span>, name, age);

        System.out.println(formattedString);
    }

}
</code></pre>
<p>The method takes a string with format specifiers as its first argument and arguments to replace those specifiers as the later arguments.</p>
<p>In the code above, the <code>%s</code>, and <code>%d</code> characters are format specifiers. They're responsible for telling the compiler that this part of the string will be replaced with something.</p>
<p>Then the compiler will replace the <code>%s</code> with the <code>name</code> and the <code>%d</code> with the <code>age</code>. The order of the specifiers needs to match the order of the arguments and the arguments need to match the type of the specifier.</p>
<p>The <code>%s</code> and <code>%d</code> are not random. They are specific for string data and decimal integers. A chart of the commonly used specifiers are as follows:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Specifier</td><td>Data Type</td></tr>
</thead>
<tbody>
<tr>
<td><code>%b</code>, <code>%B</code></td><td>Boolean</td></tr>
<tr>
<td><code>%s</code>, <code>%S</code></td><td>String</td></tr>
<tr>
<td><code>%c</code>, <code>%C</code></td><td>Unicode Character</td></tr>
<tr>
<td><code>%d</code></td><td>Decimal Integer</td></tr>
<tr>
<td><code>%f</code></td><td>Floating Point Numbers</td></tr>
</tbody>
</table>
</div><p>There is also <code>%o</code> for octal integers, <code>%x</code> or <code>%X</code> for hexadecimal numbers, and <code>%e</code> or <code>%E</code> for scientific notations. But since, we won't discuss them in this book, I've left them out.</p>
<p>Just like the <code>%s</code> and <code>%d</code> specifiers you saw, you can use any of these specifiers for their corresponding data type. And just in case you're wondering, that <code>%f</code> specifier works for both floats and doubles.</p>
<h3 id="heading-how-to-get-the-length-of-a-string-or-check-if-its-empty-or-not">How to Get the Length of a String or Check if It's Empty or Not</h3>
<p>Checking the length of a string or making sure its not empty before performing some operation is a common task.</p>
<p>Every string object comes with a <code>length()</code> method that returns the length of that string. It's like the <code>length</code> property for arrays.</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">Main</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>{
        String name = <span class="hljs-string">"Farhan"</span>;

        System.out.println(String.format(<span class="hljs-string">"Length of this string is: %d."</span>, name.length())); <span class="hljs-comment">// 6</span>
    }

}
</code></pre>
<p>The method returns the length as an integer. So you can freely use it in conjunction with the integer format specifier.</p>
<p>To check if a string is empty or not, you can use the <code>isEmpty()</code> method. Like the <code>length()</code> method, it also comes with every string object.</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">Main</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>{
        String name = <span class="hljs-string">"Farhan"</span>;

        <span class="hljs-keyword">if</span> (name.isEmpty()) {
            System.out.println(<span class="hljs-string">"There is no name mentioned here"</span>);
        } <span class="hljs-keyword">else</span> {
            System.out.println(String.format(<span class="hljs-string">"Okay, I'll take care of %s."</span>, name));
        }
    }

}
</code></pre>
<p>The method returns a boolean value so you can use it directly in if statements. The program checks if the name is empty or not and prints out different responses based off of that.</p>
<h3 id="heading-how-to-split-and-join-strings">How to Split and Join Strings</h3>
<p>The <code>split()</code> method can split a string based on a regular expression.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        String name = <span class="hljs-string">"Farhan Hasin Chowdhury"</span>;

        System.out.println(Arrays.toString(name.split(<span class="hljs-string">" "</span>)));
    }

}
</code></pre>
<p>The method returns an array of strings. Each string in that array will be a substring from the original string. Here for example, you're breaking the string <code>Farhan Hasin Chowdhury</code> at each space. So the output will be <code>[Farhan, Hasin, Chowdhury]</code>.</p>
<p>Just a reminder that arrays are collections of multiple data of the same type.</p>
<p>Since the method takes a regex as argument, you can use regular expressions to perform more complex split operations.</p>
<p>You can also join this array back into a string like this:</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">Main</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>{
        String name = <span class="hljs-string">"Farhan Hasin Chowdhury"</span>;

        String substrings[] = name.split(<span class="hljs-string">" "</span>);

        String joinedName = String.join(<span class="hljs-string">" "</span>, substrings);

        System.out.println(joinedName); <span class="hljs-comment">// Farhan Hasin Chowdhury</span>
    }

}
</code></pre>
<p>The <code>join()</code> method can also help you in joining multiple strings together outside of an array.</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">Main</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>{
        System.out.println(String.join(<span class="hljs-string">" "</span>, <span class="hljs-string">"Farhan"</span>, <span class="hljs-string">"Hasin"</span>, <span class="hljs-string">"Chowdhury"</span>)); <span class="hljs-comment">// Farhan Hasin Chowdhury</span>
    }

}
</code></pre>
<h3 id="heading-how-to-convert-a-string-to-upper-or-lowercase">How to Convert a String to Upper or Lowercase</h3>
<p>Converting a string to upper or lower case is very straightforward in Java. There are the aptly named <code>toUpperCase()</code> and <code>toLowerCase()</code> methods to perform the tasks:</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">Main</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>{
        String name = <span class="hljs-string">"Farhan Hasin Chowdhury"</span>;

        System.out.println(name.toUpperCase()); <span class="hljs-comment">// FARHAN HASIN CHOWDHURY</span>

        System.out.println(name.toLowerCase()); <span class="hljs-comment">// farhan hasin chowdhury</span>
    }

}
</code></pre>
<h3 id="heading-how-to-compare-two-strings">How to Compare Two Strings</h3>
<p>Since strings are reference types, you can not compare them using the <code>=</code> operator.</p>
<p>The <code>equals()</code> method checks whether two strings are equal or not and the <code>equalsIgnoreCase()</code> method ignores their casing when comparing.</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">Main</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>{
        String name = <span class="hljs-string">"Farhan Hasin Chowdhury"</span>;
        String nameUpperCase = name.toUpperCase();

        System.out.println(name.equals(nameUpperCase)); <span class="hljs-comment">// false</span>

        System.out.println(name.equalsIgnoreCase(nameUpperCase)); <span class="hljs-comment">// true</span>
    }

}
</code></pre>
<h3 id="heading-how-to-replace-characters-or-substrings-in-a-string">How to Replace Characters or Substrings in a String</h3>
<p>The <code>replace()</code> method can replace characters or entire substrings from a given string.</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> strings;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        String loremIpsumStd = <span class="hljs-string">"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo."</span>;

        System.out.println(String.format(<span class="hljs-string">"Standard lorem ipsum text: %s"</span>, loremIpsumStd));

        String loremIpsumHalfTranslated = loremIpsumStd.replace(<span class="hljs-string">"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium"</span>, <span class="hljs-string">"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system"</span>);

        System.out.println(String.format(<span class="hljs-string">"Translated lorem ipsum text: %s"</span>, loremIpsumHalfTranslated));
    }

}
</code></pre>
<p>Here, the <code>loremIpsumStd</code> string contains a portion of the original lorem ipsum text. Then you're replacing the first line of that string and saving the new string in the <code>loremIpsumHalfTranslated</code> variable.</p>
<h3 id="heading-how-to-check-if-a-string-contains-a-substring-or-not">How to Check If a String Contains a Substring or Not</h3>
<p>The <code>contains()</code> method can check whether a given string contains a certain substring or not.</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">Main</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>{
        String lyric = <span class="hljs-string">"Roses are red, violets are blue"</span>;

        <span class="hljs-keyword">if</span> (lyric.contains(<span class="hljs-string">"blue"</span>)) {
            System.out.println(<span class="hljs-string">"The lyric has the word blue in it."</span>);
        } <span class="hljs-keyword">else</span> {
            System.out.println(<span class="hljs-string">"The lyric doesn't have the word blue in it."</span>);
        }
    }

}
</code></pre>
<p>The method returns a boolean value, so you can use the function in any conditional statement.</p>
<p>There were some of the most common string methods. If you'd like to learn about the other ones, feel free to consult <a target="_blank" href="https://docs.oracle.com/javase/7/docs/api/java/lang/String.html">the official documentation</a>.</p>
<h2 id="heading-what-are-the-different-ways-of-inputting-and-outputting-data">What Are the Different Ways of Inputting and Outputting Data?</h2>
<p>So far you've learned about the <code>System.out.println()</code> method to print out information on the terminal. You've also learned about the <code>String.format()</code> method in a previous section.</p>
<p>In this section, you'll learn about some siblings of the <code>System.out.println()</code> method. You'll also learn about taking input from the user.</p>
<p>Taking input from user is extremely easy in languages like Python. However in Java, it takes a few more lines of code.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Scanner;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        Scanner scanner = <span class="hljs-keyword">new</span> Scanner(System.in);

        System.out.print(<span class="hljs-string">"What's your name? "</span>);
        String name = scanner.nextLine();

        System.out.printf(<span class="hljs-string">"So %s. How old are you? "</span>, name);
        <span class="hljs-keyword">int</span> age = scanner.nextInt();

        System.out.printf(<span class="hljs-string">"Cool! %d is a good age to start programming."</span>, age);

        scanner.close();

    }

}
</code></pre>
<p>The <code>java.util.Scanner</code> class is necessary for taking user inputs. You can bring the class to your program using the <code>import</code> keyword.</p>
<p>Then, you'll need to create a new instance of the <code>Scanner</code> class using the <code>new</code> keyword. While creating the new instance, you'll have to let it know your desired input stream.</p>
<p>You may want to take input from the user or from a file. Whatever it is, you'll have to let the compiler know about it. The <code>System.in</code> stream is the standard input and output stream.</p>
<p>The scanner object has methods like <code>nextLine()</code> for taking string input, <code>nextInt()</code> for taking integer input, <code>nextDouble()</code> for taking double input and so on.</p>
<p>In the code above, the <code>scanner.nextLine()</code> method will ask for a string from the user and return the given input with a newline character appended.</p>
<p>Then the <code>scanner.nextInt()</code> method will ask for an integer and return the given number from the user.</p>
<p>You may be seeing the <code>System.out.printf()</code> method for the first time here. Well, apart from the <code>System.out.println()</code> method, there is also the <code>System.out.print()</code> method that prints out a given string without appending a newline character to it.</p>
<p>The <code>System.out.printf()</code> is kind of a combination of the <code>System.out.print()</code> and <code>String.format()</code> methods. You can use the previously discussed format specifiers in this method as well.</p>
<p>Once you're done with taking input, you'll need to close the scanner object. You can do that by simply calling the <code>scanner.close()</code> method.</p>
<p>Simple right? Let me complicate it a bit.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Scanner;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        Scanner scanner = <span class="hljs-keyword">new</span> Scanner(System.in);

        System.out.print(<span class="hljs-string">"What's your name? "</span>);
        String name = scanner.nextLine();

        System.out.printf(<span class="hljs-string">"So %s. How old are you? "</span>, name);
        <span class="hljs-keyword">int</span> age = scanner.nextInt();

        System.out.printf(<span class="hljs-string">"Cool! %d is a good age to start programming. \nWhat language would you prefer? "</span>, age);
        String language = scanner.nextLine();

        System.out.printf(<span class="hljs-string">"Ah! %s is a solid programming language."</span>, language);

        scanner.close();

    }

}
</code></pre>
<p>I've added a new <code>scanner.nextLine()</code> statement after the <code>scanner.nextInt()</code> method call. Will it work?</p>
<p>No, it won't. The program will simply skip the last input prompt and print out the last line. This behavior is not exclusive to just <code>scanner.nextInt()</code>. If you use <code>scanner.nextLine()</code> after any of the other <code>nextWhatever()</code> methods, you'll face this issue.</p>
<p>In short, this happens because when you press enter on the <code>scanner.nextInt()</code> method, it consumes the integer and leaves the newline character in the input buffer.</p>
<p>So when <code>scanner.nextLine()</code> is invoked, it consumes that newline character as the end of the input. The easiest solution to this problem is writing an additional <code>scanner.nextLine()</code> call after the other scanner method calls.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Scanner;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        Scanner scanner = <span class="hljs-keyword">new</span> Scanner(System.in);

        System.out.print(<span class="hljs-string">"What's your name? "</span>);
        String name = scanner.nextLine();

        System.out.printf(<span class="hljs-string">"So %s. How old are you? "</span>, name);
        <span class="hljs-keyword">int</span> age = scanner.nextInt();

        <span class="hljs-comment">// consumes the dangling newline character</span>
        scanner.nextLine();

        System.out.printf(<span class="hljs-string">"Cool! %d is a good age to start programming. \nWhat language would you prefer? "</span>, age);
        String language = scanner.nextLine();

        System.out.printf(<span class="hljs-string">"Ah! %s is a solid programming language."</span>, language);

        scanner.close();

    }

}
</code></pre>
<p>There is another way of solving this problem. But I won't get into that here. If you're interested, <a target="_blank" href="https://www.freecodecamp.org/news/java-scanner-nextline-call-gets-skipped-solved/">checkout my article on this topic</a>.</p>
<h2 id="heading-how-to-use-conditional-statements-in-java">How to Use Conditional Statements in Java</h2>
<p>You use conditional statements for making decision based on conditions.</p>
<p>It's done using the <code>if</code> statement as follows:</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">Main</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> age = <span class="hljs-number">20</span>;

        <span class="hljs-comment">// if (condition) {...}</span>
        <span class="hljs-keyword">if</span> (age &gt;= <span class="hljs-number">18</span> &amp;&amp; age &lt;= <span class="hljs-number">40</span>) {
            System.out.println(<span class="hljs-string">"you can use the program"</span>);
        }

    }

}
</code></pre>
<p>The statement starts with an <code>if</code> and then there is the condition inside a pair of parenthesis. If the condition evaluates to true, the code within the curly braces will be executed.</p>
<p>Code enclosed between a set of curly braces is known as a code block.</p>
<p>If you change the value of <code>age</code> to <code>50</code> the print statement will not be executed and there'll be no output on the console. For these kind of situations where the condition evaluates to <code>false</code>, you can add an <code>else</code> block:</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">Main</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> age = <span class="hljs-number">20</span>;

        <span class="hljs-keyword">if</span> (age &gt;= <span class="hljs-number">18</span> &amp;&amp; age &lt;= <span class="hljs-number">40</span>) {
            System.out.println(<span class="hljs-string">"you can use the program"</span>);
        } <span class="hljs-keyword">else</span> {
            System.out.println(<span class="hljs-string">"you can not use the program"</span>);
        }

    }

}
</code></pre>
<p>Now if the condition evaluates to <code>false</code>, the code within the <code>else</code> block will execute and you'll see <code>you can not use the program</code> printed on your terminal.</p>
<p>You can also have multiple conditions within an <code>if-else if-else</code> ladder:</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">Main</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> age = <span class="hljs-number">50</span>;
        <span class="hljs-keyword">boolean</span> isSchoolStudent = <span class="hljs-keyword">true</span>;
        <span class="hljs-keyword">boolean</span> isLibraryMember = <span class="hljs-keyword">false</span>;

        <span class="hljs-comment">// if (condition) {...}</span>
        <span class="hljs-keyword">if</span> (age &gt;= <span class="hljs-number">18</span> &amp;&amp; age &lt;= <span class="hljs-number">40</span>) {
            System.out.println(<span class="hljs-string">"you can use the program"</span>);
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (isSchoolStudent || isLibraryMember) {
            System.out.println(<span class="hljs-string">"you can use the program for a short time"</span>);
        } <span class="hljs-keyword">else</span> {
            System.out.println(<span class="hljs-string">"you can not use the program"</span>);
        }

    }

}
</code></pre>
<p>Now, if the first condition evaluates to <code>false</code> then the second condition will be tested. If the second one evaluates to <code>true</code> then the code within curly braces will be executed. If the conditions in both <code>if</code> statements evaluate to <code>false</code>, then the <code>else</code> block will be executed.</p>
<p>You can also nest <code>if</code> statements within other <code>if</code> statements as follows:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> operators;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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> age = <span class="hljs-number">20</span>;

        <span class="hljs-keyword">if</span> (age &gt;= <span class="hljs-number">18</span> &amp;&amp; age &lt;= <span class="hljs-number">40</span>) {
            <span class="hljs-keyword">boolean</span> isSchoolStudent = <span class="hljs-keyword">true</span>;
            <span class="hljs-keyword">boolean</span> isLibraryMember = <span class="hljs-keyword">false</span>;

            <span class="hljs-keyword">if</span> (isSchoolStudent || isLibraryMember) {
                System.out.println(<span class="hljs-string">"you can use the program"</span>);
            }
        } <span class="hljs-keyword">else</span> {
            System.out.println(<span class="hljs-string">"you can not use the program"</span>);
        }

    }

}
</code></pre>
<p>In this case, only if the first <code>if</code> statement evaluates to true will the inner <code>if</code> statement be tested.</p>
<h2 id="heading-what-is-a-switch-case-statement">What is a switch-case statement?</h2>
<p>Apart from the if-else blocks, there are also switch cases where you can define multiple cases based on a single switch.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Scanner;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        Scanner scanner = <span class="hljs-keyword">new</span> Scanner(System.in);

        System.out.print(<span class="hljs-string">"What is the first operand? "</span>);
        <span class="hljs-keyword">int</span> a =scanner.nextInt();

        <span class="hljs-comment">// consumes the dangling newline character</span>
        scanner.nextLine();

        System.out.print(<span class="hljs-string">"What is the second operand? "</span>);
        <span class="hljs-keyword">int</span> b = scanner.nextInt();

        <span class="hljs-comment">// consumes the dangling newline character</span>
        scanner.nextLine();

        System.out.print(<span class="hljs-string">"What operation would you like to perform? "</span>);
        String operation = scanner.nextLine();

        <span class="hljs-keyword">switch</span> (operation) {
            <span class="hljs-keyword">case</span> <span class="hljs-string">"sum"</span>:
                System.out.printf(<span class="hljs-string">"%d + %d = %d"</span>, a, b, a+b);
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">"sub"</span>:
                System.out.printf(<span class="hljs-string">"%d - %d = %d"</span>, a, b, a-b);
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">"mul"</span>:
                System.out.printf(<span class="hljs-string">"%d * %d = %d"</span>, a, b, a*b);
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">case</span> <span class="hljs-string">"div"</span>:
                <span class="hljs-keyword">if</span> (b == <span class="hljs-number">0</span>) {
                    System.out.print(<span class="hljs-string">"Can't divide by zero!"</span>);
                } <span class="hljs-keyword">else</span> {
                    System.out.printf(<span class="hljs-string">"%d / %d = %d"</span>, a, b, a / b);
                }
                <span class="hljs-keyword">break</span>;
            <span class="hljs-keyword">default</span>:
                System.out.printf(<span class="hljs-string">"Invalid Operation!"</span>);
        }

        scanner.close();

    }

}
</code></pre>
<p>This is a very simple calculator program. The program prompts the user for two numbers and then asks what operation they would like to perform.</p>
<p>Every switch-case statement will have one switch and multiple cases. When you say <code>case "sum"</code>, the program checks whether the value of the switch or the <code>operation</code> variable in this is <code>sum</code> or not.</p>
<p>If it matches, the case body will execute. If none of the cases match, the <code>default</code> case will be executed. </p>
<p>And about that <code>break</code> statement. It does what it sounds like: stops the program from going into the next case.</p>
<p>If you remove the <code>break</code> statements, all the cases will be executed one after the other until the <code>default</code> case has been reached.</p>
<h2 id="heading-what-is-variable-scope-in-java">What is Variable Scope in Java?</h2>
<p>Scope is the lifetime and accessibility of a variable. Depending on where you declare a variable you may or may not be able to access it from other places.</p>
<p>Take the following code snippet as an 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">Main</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> age = <span class="hljs-number">20</span>;

        <span class="hljs-keyword">if</span> (age &gt;= <span class="hljs-number">18</span> &amp;&amp; age &lt;= <span class="hljs-number">40</span>) {
            <span class="hljs-comment">// age variable is accessible here</span>
            <span class="hljs-comment">// booleans are not accessible here</span>

            <span class="hljs-keyword">boolean</span> isSchoolStudent = <span class="hljs-keyword">true</span>;
            <span class="hljs-keyword">boolean</span> isLibraryMember = <span class="hljs-keyword">false</span>;

            <span class="hljs-keyword">if</span> (isSchoolStudent || isLibraryMember) {
                <span class="hljs-comment">// booleans are accessible here</span>
                <span class="hljs-comment">// age variable is accessible here</span>

                System.out.println(<span class="hljs-string">"you can use the program"</span>);
            }
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-comment">// age variable is accessible here</span>
            <span class="hljs-comment">// booleans are not accessible here</span>

            System.out.println(<span class="hljs-string">"you can not use the program"</span>);
        }

    }

}
</code></pre>
<p>Here, the <code>age</code> variable is declared within the <code>class</code> code block. That means you can access this variable within the entire class without any issue. Since the variable is accessible in the entire class instance, it's an instance variable.</p>
<p>However, the <code>isSchoolStudent</code> and <code>isLibraryMember</code> variables have been declared within the first <code>if</code> statement code block. So it'll not be accessible outside of that code block.</p>
<p>But, it'll be accessible within any nested code block inside the first <code>if</code> block. These are called local variables.</p>
<p>There are also class variables declared using the <code>static</code> keyword but you'll learn about them in the object-oriented programming sections.</p>
<p>So for now, the rule of thumb is, a variable will be accessible within the code block it was declared at and any other code block nested inside the parent block.</p>
<h2 id="heading-what-are-default-values-of-variables-in-java">What Are Default Values of Variables in Java?</h2>
<p>You've learned that in Java, you need to initialize a variable after declaring it. Otherwise, you'll not be able to use that. Well that's not true in all cases.</p>
<p>If you declare a variable in the class level, that variable will be assigned a default value by the compiler.</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">Main</span> </span>{

    <span class="hljs-comment">// gets 0 as the value by default</span>
    <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> age;

    <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>{
        System.out.println(age); <span class="hljs-comment">// 0</span>
    }
}
</code></pre>
<p>Since the <code>main</code> method is <code>static</code>, it can only access <code>static</code> variables in the class level. I'll discuss <code>static</code> in greater detail in the object-oriented programming section.</p>
<p>But if you move the variable declaration inside the <code>main</code> method, it becomes local to that method and doesn't get any default value.</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">Main</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-comment">// remains uninitialized</span>
        <span class="hljs-keyword">int</span> age;

        System.out.println(age); <span class="hljs-comment">// fails to compile</span>
    }
}
</code></pre>
<p>This code will throw the <code>The local variable age may not have been initialized</code> error on compilation.</p>
<p>Variables get their default values based on their type. In most cases, it'll be <code>0</code> or <code>null</code>. I'm giving a list of all the primitive types and their default values:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Data Type</td><td>Default Value</td></tr>
</thead>
<tbody>
<tr>
<td><code>byte</code></td><td><code>0</code></td></tr>
<tr>
<td><code>short</code></td><td><code>0</code></td></tr>
<tr>
<td><code>int</code></td><td><code>0</code></td></tr>
<tr>
<td><code>long</code></td><td><code>0L</code></td></tr>
<tr>
<td><code>float</code></td><td><code>0.0f</code></td></tr>
<tr>
<td><code>double</code></td><td><code>0.0d</code></td></tr>
<tr>
<td><code>char</code></td><td><code>'\u0000'</code></td></tr>
<tr>
<td><code>boolean</code></td><td><code>false</code></td></tr>
</tbody>
</table>
</div><p>Any reference type will be assigned the value <code>null</code> by default. We'll discuss reference types, classes, and objects in the object-oriented programming sections.</p>
<h2 id="heading-how-to-work-with-arrays-in-java">How to Work with Arrays in Java</h2>
<p>You've already learned about declaring single variables and using them in your program. This is where arrays come in.</p>
<p>Arrays are data structures containing multiple value sof the same data type in sequential memory locations. Arrays can be of any primitive or non-primitive data type.</p>
<p>You can create an array in Java as follows:</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">Main</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-comment">// &lt;type&gt; &lt;name&gt;[] = new &lt;type&gt;[&lt;length&gt;]</span>
        <span class="hljs-keyword">char</span> vowels[] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">char</span>[<span class="hljs-number">5</span>];

    }
}
</code></pre>
<p>You start by typing out the type of data you want to hold in the array, <code>char</code> in this case. Then you write out the name of the array, <code>vowels</code> followed by a pair of square braces here. This pair of braces tells Java that you're declaring an array of characters and not a regular character variable.</p>
<p>Then you put an equal sign followed by the <code>new</code> operator used for creating new objects in Java. Since arrays are reference types in Java, <code>new</code> is required to create new instances.</p>
<p>You finish off the declaration by writing out the type again, followed by another pair of square braces enclosing the length of the array. Here, <code>5</code> means the array will hold five elements and not more than that.</p>
<p>When working with a single variable, you can refer to the variable simply by its name. But in case of an array, each element will have an index and arrays are zero-based. This means the first element in an array will have <code>0</code> as its index and not <code>1</code>.</p>
<p>To access an element in an array, you start by writing out the name of the array – in this case <code>vowels</code> followed by a pair of square braces enclosing your desired index. So if you want to access the first element in the array, you can do so as follows:</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">Main</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">char</span> vowels[] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">char</span>[<span class="hljs-number">5</span>];

        vowels[<span class="hljs-number">0</span>] = <span class="hljs-string">'a'</span>;
    }
}
</code></pre>
<p>At this point, <code>vowels[0]</code> is similar to a regular character variable. You can print it out, assign new value to it, perform calculations in case of number types, and so on. </p>
<p>Since the array is empty at this moment, I'm assigning the character <code>a</code> to the first index. You can assign the rest of the vowels to the rest of the indices as follows:</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">Main</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">char</span> vowels[] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">char</span>[<span class="hljs-number">5</span>];

        vowels[<span class="hljs-number">0</span>] = <span class="hljs-string">'a'</span>;
        vowels[<span class="hljs-number">1</span>] = <span class="hljs-string">'e'</span>;
        vowels[<span class="hljs-number">2</span>] = <span class="hljs-string">'i'</span>;
        vowels[<span class="hljs-number">3</span>] = <span class="hljs-string">'o'</span>;
        vowels[<span class="hljs-number">4</span>] = <span class="hljs-string">'u'</span>;

    }
}
</code></pre>
<p>Since the indices start at <code>0</code> they'll end at the length of the array - 1, which in this case is <code>4</code>. If you try to assign another element to the array like <code>vowels[4] = 'x';</code> the compiler will throw the following error:</p>
<pre><code>Exception <span class="hljs-keyword">in</span> thread <span class="hljs-string">"main"</span> java.lang.ArrayIndexOutOfBoundsException: Index <span class="hljs-number">5</span> out <span class="hljs-keyword">of</span> bounds <span class="hljs-keyword">for</span> length <span class="hljs-number">5</span>
    at arrays.Main.main(Main.java:<span class="hljs-number">18</span>)
</code></pre><p>Arrays can not be printed like regular variables. You'll have to use a loop or you'll have to convert the array into a string. Since, I haven't discussed loops yet, I'll use the second method.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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">char</span> vowels[] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">char</span>[<span class="hljs-number">5</span>];

        vowels[<span class="hljs-number">0</span>] = <span class="hljs-string">'a'</span>;
        vowels[<span class="hljs-number">1</span>] = <span class="hljs-string">'e'</span>;
        vowels[<span class="hljs-number">2</span>] = <span class="hljs-string">'i'</span>;
        vowels[<span class="hljs-number">3</span>] = <span class="hljs-string">'o'</span>;
        vowels[<span class="hljs-number">4</span>] = <span class="hljs-string">'u'</span>;

        System.out.println(<span class="hljs-string">"These are the vowels: "</span> + Arrays.toString(vowels));

    }
}
</code></pre>
<p>You'll need to first import the <code>java.util.Arrays;</code> and use the <code>Arrays.toString()</code> method to convert the array to a string. This class has a bunch of other interesting methods, but before discussing them, I'd like to show you how you can declare and initialize an array in one go.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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">char</span> vowels[] = {<span class="hljs-string">'a'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'u'</span>};

        System.out.println(<span class="hljs-string">"These are the vowels: "</span> + Arrays.toString(vowels));

    }
}
</code></pre>
<p>The left side of the declaration syntax remains unchanged. However, after the assignment operator, instead of using <code>new</code> you write out the individual array elements separated by comma and enclosed within a pair of curly braces.</p>
<p>In this case the compiler will count the number of elements in the array and use that as the length of the array.</p>
<p>If you do not know the length of an array, you can take a look at the <code>length</code> property.</p>
<p>In this case, <code>vowels.length</code> will be <code>5</code> since there are five elements in the array. The <code>length</code> property is an integer and is present in every array in Java.</p>
<p>Arrays can also be multidimensional. So far you've worked with arrays that look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/single-dimensional-array.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Single dimensional arrays like this are perfect when you want to store a series of values. But imagine someone's daily medicine routine in the form of a table:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/multi-dimensional-array-1.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The first row represents the seven days in a week and the columns represent how many times the patient should take their medicine out of three times a day. <code>0</code> means no and <code>1</code> means yes.</p>
<p>You can map this routine using a multidimensional array in your program:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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> medicineRoutine[][] = {
                {<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-number">6</span>, <span class="hljs-number">7</span>},
                {<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>},
                {<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>},
                {<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>},
        };

        System.out.println(Arrays.deepToString(medicineRoutine)); <span class="hljs-comment">// [[1, 2, 3, 4, 5, 6, 7], [0, 1, 1, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0, 0], [0, 0, 1, 1, 0, 1, 0]]</span>

    }
}
</code></pre>
<p>Multidimensional arrays can not be printed out using the regular <code>Arrays.toString()</code> method, you have to dig deeper.</p>
<p>Although the output doesn't look anything like the table, you can make it look like a table using some clever programming:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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> medicineRoutine[][] = {
                {<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-number">6</span>, <span class="hljs-number">7</span>},
                {<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>},
                {<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>},
                {<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>},
        };

        System.out.println(Arrays.deepToString(medicineRoutine).replace(<span class="hljs-string">"], "</span>, <span class="hljs-string">"]\n"</span>));
    }
}

<span class="hljs-comment">// [[1, 2, 3, 4, 5, 6, 7]</span>
<span class="hljs-comment">// [0, 1, 1, 0, 1, 1, 0]</span>
<span class="hljs-comment">// [1, 0, 1, 0, 1, 0, 0]</span>
<span class="hljs-comment">// [0, 0, 1, 1, 0, 1, 0]]</span>
</code></pre>
<p>You've already learned about the <code>replace()</code> method for strings. You're just replacing the ending square brace in each line with a square brace and a newline character.</p>
<p>The first row represents the 7 weekdays and the rest of the rows are medicine routines for each day. Each line in this table represents an array.</p>
<p>To access a single value from a multidimensional array, you'll need two indices. The first index determines the row and the second one determines the column.</p>
<p>So <code>medicineRoutine[2][3]</code> will select the element in index <code>3</code> of the third array. That element will be <code>0</code>. Working with multidimensional array can seem a bit tricky but practicing will make it much easier. </p>
<p>Since you can create arrays of any type in Java, why don't you try creating some other types of arrays by yourself, huh?</p>
<h3 id="heading-how-to-sort-an-array">How to Sort an Array</h3>
<p>One of the most common tasks that you will perform on arrays is sorting them. The <code>java.utils.Arrays</code> comes with the <code>Arrays.sort()</code> method to do just that:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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">char</span> vowels[] = {<span class="hljs-string">'e'</span>, <span class="hljs-string">'u'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'a'</span>};

        Arrays.sort(vowels);

        System.out.println(<span class="hljs-string">"The sorted array: "</span> + Arrays.toString(vowels)); <span class="hljs-comment">// [a, e, i, o , u]</span>

    }
}
</code></pre>
<p>The <code>Arrays.sort()</code> method takes the unsorted array as its argument and sorts it in place. So instead of getting a new sorted array in return, your original array itself will be sorted in ascending order.</p>
<p>By default, the method treats the first index of the array as its starting index and the length of the array as its ending index.</p>
<p>You can specify these two indices manually. For example, if you want to sort only <code>u, o, i</code> in ascending order and leave <code>e, a</code> as is, you can do so as follows:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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">char</span> vowels[] = {<span class="hljs-string">'e'</span>, <span class="hljs-string">'u'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'a'</span>};

        <span class="hljs-keyword">int</span> startIndex = <span class="hljs-number">1</span>;
        <span class="hljs-keyword">int</span> endIndex = <span class="hljs-number">4</span>;

        Arrays.sort(vowels, startIndex, endIndex);

        System.out.println(<span class="hljs-string">"The sorted array: "</span> + Arrays.toString(vowels)); <span class="hljs-comment">// [e, i, o, u , a]</span>

    }
}
</code></pre>
<p>This time, the method takes the array as the first parameter, the starting index as the second parameter, and the ending index as the third parameter. The rest of the behaviors stay the same as before.</p>
<h3 id="heading-how-to-perform-binary-search-on-an-array">How to Perform Binary Search on an Array</h3>
<p>Searching for values within a sorted value is another common task. The <code>Arrays.binarySearch()</code> method lets you search for items in a sorted array using the binary search algorithm.</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">Main</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">char</span> vowels[] = {<span class="hljs-string">'a'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'u'</span>};

        <span class="hljs-keyword">char</span> key = <span class="hljs-string">'i'</span>;

        <span class="hljs-keyword">int</span> foundItemIndex = Arrays.binarySearch(vowels, key);

        System.out.println(<span class="hljs-string">"The vowel 'i' is at index: "</span> + foundItemIndex); <span class="hljs-comment">// 2</span>

    }
}
</code></pre>
<p>The <code>Arrays.binarySearch()</code> method takes an array as its first parameter and the the search key (aka the item you're looking for) as its second parameter. It'll return the index of the found item as an integer.</p>
<p>You can store that index in an <code>int</code> and use that to access the element from the array as <code>vowels[foundItemIndex]</code>.</p>
<p>Note that the array has to be sorted in ascending order. If you're unsure of the array's ordering, use the <code>Arrays.sort()</code> method to sort it first.</p>
<p>By default, the method treats the first index of the array as its starting index and the length of the array as its ending index. But you can also specify those indices manually.</p>
<p>For example, if you want the search to take place from index <code>2</code> to index <code>4</code>, you can do so as follows:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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">char</span> vowels[] = {<span class="hljs-string">'a'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'u'</span>};

        <span class="hljs-keyword">char</span> key = <span class="hljs-string">'i'</span>;
        <span class="hljs-keyword">int</span> startIndex = <span class="hljs-number">2</span>;
        <span class="hljs-keyword">int</span> endIndex = <span class="hljs-number">4</span>;

        <span class="hljs-keyword">int</span> foundItemIndex = Arrays.binarySearch(vowels, startIndex, endIndex, key);

        System.out.println(<span class="hljs-string">"The vowel 'i' is at index: "</span> + foundItemIndex); <span class="hljs-comment">// 2</span>

    }
}
</code></pre>
<p>This time the method takes the array you want to search on as the first parameter, the starting index as the second parameter, the ending index as the third parameter, and the search key as the fourth parameter.</p>
<p>Now the search will take place within <code>i</code>, <code>o</code>, and <code>u</code>. So if you look for <code>a</code>, it'll not be found. In cases where the given item is not found, you'll get a negative index. The resultant negative index will vary based on a number of factors but I won't get into those here. If you're interested in learning more, <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-arrays-binarysearch-in-java/">check out my article on the topic</a>.</p>
<h3 id="heading-how-to-fill-an-array">How to Fill an Array</h3>
<p>You've already learned about initializing an array with values but you may sometimes want to fill an entire array with the same value. The <code>Arrays.fill()</code> method can do that for you:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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">char</span> vowels[] = {<span class="hljs-string">'e'</span>, <span class="hljs-string">'u'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'a'</span>};

        Arrays.fill(vowels, <span class="hljs-string">'x'</span>);

        System.out.println(<span class="hljs-string">"The filled array: "</span> + Arrays.toString(vowels)); <span class="hljs-comment">// [x, x, x, x, x]</span>

    }
}
</code></pre>
<p>Like the <code>Arrays.sort()</code> method, <code>Arrays.fill()</code> also performs its operation in place. It takes your array as the first parameter, the value you want to fill the array with as the second parameter, and updates the original array in place.</p>
<p>This method also treats the first index as the starting index and the length of the array as the ending index. You can specify these indices manually as follows:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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">char</span> vowels[] = {<span class="hljs-string">'e'</span>, <span class="hljs-string">'u'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'a'</span>};

        <span class="hljs-keyword">int</span> startIndex = <span class="hljs-number">1</span>;
        <span class="hljs-keyword">int</span> endIndex = <span class="hljs-number">4</span>;

        Arrays.fill(vowels, startIndex, endIndex, <span class="hljs-string">'x'</span>);

        System.out.println(<span class="hljs-string">"The filled array: "</span> + Arrays.toString(vowels)); <span class="hljs-comment">// [e, x, x, x, a]</span>

    }
}
</code></pre>
<p>This time the method takes your array as the first argument, the starting index as the second argument, the ending index as the third argument, and the filler as the fourth argument.</p>
<h3 id="heading-how-to-make-copies-of-an-array">How to Make Copies of an Array</h3>
<p>Since arrays in Java are of reference types, copying them using the assignment operator can cause some unexpected behavior.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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> oddNumbers[] = {<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>};
        <span class="hljs-keyword">int</span> copyOfOddNumbers[] = oddNumbers;

        Arrays.fill(oddNumbers, <span class="hljs-number">0</span>);

        System.out.println(<span class="hljs-string">"The copied array: "</span> + Arrays.toString(copyOfOddNumbers)); <span class="hljs-comment">// [0, 0, 0]</span>

    }
}
</code></pre>
<p>Although you've made changes to the source array, the copy reflects them as well. This happens because when you use the assignment operator to copy an array, the copy references the original array in the memory.</p>
<p>To properly copy an array, you can use the <code>Arrays.copyOf()</code> method as follows:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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> oddNumbers[] = {<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>};
        <span class="hljs-keyword">int</span> copyOfOddNumbers[] = Arrays.copyOf(oddNumbers, oddNumbers.length);

        Arrays.fill(oddNumbers, <span class="hljs-number">0</span>);

        System.out.println(<span class="hljs-string">"The copied array: "</span> + Arrays.toString(copyOfOddNumbers)); <span class="hljs-comment">// [1, 3, 5]</span>

    }
}
</code></pre>
<p>The method takes the source array as its first argument and the desired length of the new array as the second argument. If you want the length to be the same, simply pass the length of the original array using the <code>length</code> property.</p>
<p>If you put a smaller length, any value after that will be cut off and if you put a larger length, the new indices will be filled with the default value of the array data type.</p>
<p>There is another method <code>Arrays.copyOfRange()</code> that can copy a portion of an array to a new one:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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> oddNumbers[] = {<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>, <span class="hljs-number">11</span>, <span class="hljs-number">13</span>, <span class="hljs-number">15</span>};

        <span class="hljs-keyword">int</span> startIndex = <span class="hljs-number">2</span>;
        <span class="hljs-keyword">int</span> endIndex = <span class="hljs-number">7</span>;

        <span class="hljs-keyword">int</span> copyOfOddNumbers[] = Arrays.copyOfRange(oddNumbers, startIndex, endIndex);

        System.out.println(<span class="hljs-string">"The copied array: "</span> + Arrays.toString(copyOfOddNumbers)); <span class="hljs-comment">// [5, 7, 9, 11, 13]</span>

    }
}
</code></pre>
<p>This method takes the source array as its first argument, then the start index and finally the end index. </p>
<p>Keep in mind, the ending index is not inclusive. That's why 15 is absent from the new array. But if you want to include the last index of the array, use the length of the original array as the ending index.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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> oddNumbers[] = {<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>, <span class="hljs-number">11</span>, <span class="hljs-number">13</span>, <span class="hljs-number">15</span>};

        <span class="hljs-keyword">int</span> startIndex = <span class="hljs-number">2</span>;
        <span class="hljs-keyword">int</span> endIndex = oddNumbers.length;

        <span class="hljs-keyword">int</span> copyOfOddNumbers[] = Arrays.copyOfRange(oddNumbers, startIndex, endIndex);

        System.out.println(<span class="hljs-string">"The copied array: "</span> + Arrays.toString(copyOfOddNumbers)); <span class="hljs-comment">// [5, 7, 9, 11, 13, 15]</span>

    }
}
</code></pre>
<p>Now the new array will also include 15 in it. You can also put a higher number than the length of the source array. In that case the newly added indices will contain the default value of the array data type.</p>
<h3 id="heading-how-to-compare-two-arrays">How to Compare Two Arrays</h3>
<p>If you try two check if two arrays are the same or not in Java using the equal relational operator, you'll get some unexpected results.</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">Main</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> oddNumbers1[] = {<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>, <span class="hljs-number">11</span>, <span class="hljs-number">13</span>, <span class="hljs-number">15</span>};
        <span class="hljs-keyword">int</span> oddNumbers2[] = {<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>, <span class="hljs-number">11</span>, <span class="hljs-number">13</span>, <span class="hljs-number">15</span>};

        System.out.println(oddNumbers1 == oddNumbers2); <span class="hljs-comment">// false</span>
    }
}
</code></pre>
<p>Even though the two arrays are identical, the output of the program is <code>false</code>. Since arrays are reference types, the relational operator will check whether they are the same instance or not.</p>
<p>To compare two arrays in Java, you can use the <code>Arrays.equals()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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> oddNumbers1[] = {<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>, <span class="hljs-number">11</span>, <span class="hljs-number">13</span>, <span class="hljs-number">15</span>};
        <span class="hljs-keyword">int</span> oddNumbers2[] = {<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>, <span class="hljs-number">11</span>, <span class="hljs-number">13</span>, <span class="hljs-number">15</span>};

        System.out.println(Arrays.equals(oddNumbers1, oddNumbers2)); <span class="hljs-comment">// true</span>
    }
}
</code></pre>
<p>However, if you change even a single element in either of these arrays, the output will be <code>false</code> since the arrays will not remain identical anymore.</p>
<p>You can also compare multidimensional arrays, but for that you'll have to use the <code>Arrays.deepEquals()</code> method instead of the regular one.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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> medicineRoutine[][] = {
                {<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-number">6</span>, <span class="hljs-number">7</span>},
                {<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>},
                {<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>},
                {<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>},
        };

        <span class="hljs-keyword">int</span> medicineRoutine2[][] = {
                {<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-number">6</span>, <span class="hljs-number">7</span>},
                {<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>},
                {<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>},
                {<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>},
        };

        System.out.println(Arrays.deepEquals(medicineRoutine, medicineRoutine2)); <span class="hljs-comment">// true</span>
    }
}
</code></pre>
<p>This method calls itself each time it encounters a new array inside the parent array. </p>
<p>These were some of the most common methods inside the <code>java.util.Arrays</code> class. You can consult <a target="_blank" href="https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html">the official documentation</a> if you'd like to learn more.</p>
<h2 id="heading-how-to-use-loops-in-java">How to Use Loops in Java</h2>
<p>If you ever need to repeat a task for a set number of times, you can use a loop. Loops can be of three types: they are <code>for</code> loops, <code>for...each</code> loops, and <code>while</code> loops.</p>
<h3 id="heading-for-loop">For Loop</h3>
<p>For loops are probably the most common types of loops that you'll see on the internet.</p>
<p>Every for loop consists of three parts. The initialization, condition, and update expression. The looping happens in multiple steps.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/for-loop-generic-2.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you want to print the numbers from 0 to 10 using a for loop, you can do so as follows:</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">Main</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">for</span> (<span class="hljs-keyword">int</span> number = <span class="hljs-number">0</span>; number &lt;= <span class="hljs-number">10</span>; number++) {
            System.out.println(number);
        }
    }
}

<span class="hljs-comment">// 0</span>
<span class="hljs-comment">// 1</span>
<span class="hljs-comment">// 2</span>
<span class="hljs-comment">// 3</span>
<span class="hljs-comment">// 4</span>
<span class="hljs-comment">// 5</span>
<span class="hljs-comment">// 6</span>
<span class="hljs-comment">// 7</span>
<span class="hljs-comment">// 8</span>
<span class="hljs-comment">// 9</span>
<span class="hljs-comment">// 10</span>
</code></pre>
<p>The flowchart for this loop looks like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/for-loop-number-1.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<ol>
<li>In the beginning of the loop, you initialize a new integer named <code>number</code> with the initial value of <code>0</code>.</li>
<li>Then you check whether the <code>number</code> is less than or equal to <code>10</code> or not.</li>
<li>If its less than or equal to <code>10</code>, you execute the statement inside the loop block and print out the number on the terminal.</li>
<li>Then you update the number variable by incrementing its value by 1.</li>
<li>The loop goes back to checking whether the value of number is still less than or equal or not.</li>
</ol>
<p>As long as the value of number remains less than or equal to 10, the loop goes on. The moment the value of the <code>number</code> variable becomes <code>11</code>, the loop ends.</p>
<p>You can use a for loop to loop over an array as follows:</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">Main</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> fibonacciNumbers[] = {<span class="hljs-number">0</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>, <span class="hljs-number">55</span>};

        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> index = <span class="hljs-number">0</span>; index &lt; fibonacciNumbers.length; index++) {
            System.out.println(fibonacciNumbers[index]);
        }
    }
}
</code></pre>
<p>The flowchart for this loop will be as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/for-loop-fibo.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Since the last index of the array is one less than its length, you run the loop as long as the index is less than the array length. The moment the index becomes equal to the length of the array, you exit the loop.</p>
<p>One of the fun things that you can do with loops is printing out multiplication tables. For example, the multiplication table for 5 will be as follows:</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">Main</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> number = <span class="hljs-number">5</span>;

        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> multiplier = <span class="hljs-number">1</span>; multiplier &lt;= <span class="hljs-number">10</span>; multiplier++) {
            System.out.println(String.format(<span class="hljs-string">"%d x %d = %d"</span>, number, multiplier, number * multiplier));
        }
    }
}

<span class="hljs-comment">// 5 x 1 = 5</span>
<span class="hljs-comment">// 5 x 2 = 10</span>
<span class="hljs-comment">// 5 x 3 = 15</span>
<span class="hljs-comment">// 5 x 4 = 20</span>
<span class="hljs-comment">// 5 x 5 = 25</span>
<span class="hljs-comment">// 5 x 6 = 30</span>
<span class="hljs-comment">// 5 x 7 = 35</span>
<span class="hljs-comment">// 5 x 8 = 40</span>
<span class="hljs-comment">// 5 x 9 = 45</span>
<span class="hljs-comment">// 5 x 10 = 50</span>
</code></pre>
<p>Loops can also be nested. Which means you can put one loop inside another. You can print out the multiplication table of all the numbers from 1 to 10 using nested loops:</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">Main</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">for</span> (<span class="hljs-keyword">int</span> number = <span class="hljs-number">1</span>; number &lt;= <span class="hljs-number">10</span>; number++) {
            System.out.println(String.format(<span class="hljs-string">"\nmultiplication table of %d"</span>, number));
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> multiplier = <span class="hljs-number">1</span>; multiplier &lt;= <span class="hljs-number">10</span>; multiplier++) {
                System.out.println(String.format(<span class="hljs-string">"%d x %d = %d"</span>, number, multiplier, number * multiplier));
            }
        }
    }
}
</code></pre>
<p>I wouldn't dare printing out the output here. Instead, try out the code by yourself. Draw out each iteration of the loop on a piece of paper so that you understand what's happening on each step.</p>
<h3 id="heading-for-each-loop">For-Each Loop</h3>
<p>If you want to iterate over a collection like an array and perform some operation on each element of that collection, you can use a for...each loop.</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">Main</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> fibonacciNumbers[] = {<span class="hljs-number">0</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>, <span class="hljs-number">55</span>};

        <span class="hljs-keyword">for</span>(<span class="hljs-keyword">int</span> number : fibonacciNumbers) {
            System.out.println(number);
        }
    }
}
</code></pre>
<p>In the case of a for-each loop, the type of the item needs to match the type of the collection you're working with. Here, the array is of type integer so the item in the loop is of type integer.</p>
<p>This does the same task as the previously shown for loop. But in this one, you don't have to keep track of the index or use the square braces to access the elements. It looks cleaner and is less error prone.</p>
<h3 id="heading-while-loop">While Loop</h3>
<p>If you want to execute a bunch of code until a certain condition is met, you can use a while loop.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/while-loop-generic.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>There are no initialization or update steps in a while loop. Whatever happens, happens within the loop body. If you rewrite the program for printing out the multiplication table of 5 using a while loop, it'll be as follows:</p>
<pre><code>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) {
        int number = <span class="hljs-number">5</span>;
        int multiplier = <span class="hljs-number">1</span>;

        <span class="hljs-keyword">while</span> (multiplier &lt;= <span class="hljs-number">10</span>) {
            System.out.println(<span class="hljs-built_in">String</span>.format(<span class="hljs-string">"%d x %d = %d"</span>, number, multiplier, number*multiplier));

            multiplier++;
        }
    }
}

<span class="hljs-comment">// 5 x 1 = 5</span>
<span class="hljs-comment">// 5 x 2 = 10</span>
<span class="hljs-comment">// 5 x 3 = 15</span>
<span class="hljs-comment">// 5 x 4 = 20</span>
<span class="hljs-comment">// 5 x 5 = 25</span>
<span class="hljs-comment">// 5 x 6 = 30</span>
<span class="hljs-comment">// 5 x 7 = 35</span>
<span class="hljs-comment">// 5 x 8 = 40</span>
<span class="hljs-comment">// 5 x 9 = 45</span>
<span class="hljs-comment">// 5 x 10 = 50</span>
</code></pre><p>Although, while loops are not as common as for loops in the real world, learning about them is worth it.</p>
<h3 id="heading-do-while-loop">Do-While Loop</h3>
<p>The final type of loop you'll learn about is the do-while loop. It kind of reverses the order of the regular while loop – so instead of checking the condition before executing the loop body, you execute the loop body first and then check the condition.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/do-while-loop-generic.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The multiplication table code implemented using a do-while loop will be as follows:</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">Main</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> number = <span class="hljs-number">5</span>;
        <span class="hljs-keyword">int</span> multiplier = <span class="hljs-number">1</span>;

        <span class="hljs-keyword">do</span> {
            System.out.println(String.format(<span class="hljs-string">"%d x %d = %d"</span>, number, multiplier, number*multiplier));

            multiplier++;
        } <span class="hljs-keyword">while</span> (multiplier &lt;= <span class="hljs-number">10</span>);
    }
}

<span class="hljs-comment">// 5 x 1 = 5</span>
<span class="hljs-comment">// 5 x 2 = 10</span>
<span class="hljs-comment">// 5 x 3 = 15</span>
<span class="hljs-comment">// 5 x 4 = 20</span>
<span class="hljs-comment">// 5 x 5 = 25</span>
<span class="hljs-comment">// 5 x 6 = 30</span>
<span class="hljs-comment">// 5 x 7 = 35</span>
<span class="hljs-comment">// 5 x 8 = 40</span>
<span class="hljs-comment">// 5 x 9 = 45</span>
<span class="hljs-comment">// 5 x 10 = 50</span>
</code></pre>
<p>Do-while loops are very useful when you need to perform some operation until the user gives a specific input. Such as, show a menu until user presses the "x" key.</p>
<h2 id="heading-how-to-work-with-array-lists-in-java">How to Work with Array Lists in Java</h2>
<p>Arrays in Java are not resizable. Once you've set a length for an array, you can not change it any way. The <code>ArrayList</code> class in Java mitigates this limitation.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        ArrayList&lt;Integer&gt; oddNumbers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

        oddNumbers.add(<span class="hljs-number">1</span>);
        oddNumbers.add(<span class="hljs-number">3</span>);
        oddNumbers.add(<span class="hljs-number">5</span>);
        oddNumbers.add(<span class="hljs-number">7</span>);
        oddNumbers.add(<span class="hljs-number">9</span>);

        System.out.println(oddNumbers.toString()); <span class="hljs-comment">// [1, 3, 5, 7, 9]</span>
    }
}
</code></pre>
<p>To create array lists, you'll need to import the <code>java.util.ArrayList</code> class at the top of your source file.</p>
<p>Then you start by writing <code>ArrayList</code> and then inside a pair of less than-greater than signs, you'll write the data type for the elements. Then you'll add the name of the array list itself followed by the assignment operator and <code>new ArrayList&lt;&gt;()</code>.</p>
<p>You can not create array lists of primitive types, so you'll have to use the corresponding wrapper class.</p>
<p>Although these elements have zero-based indices like arrays, you can not use the square brace notation to access them. Instead, you'll have to use the <code>get()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        ArrayList&lt;Integer&gt; oddNumbers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

        oddNumbers.add(<span class="hljs-number">1</span>);
        oddNumbers.add(<span class="hljs-number">3</span>);
        oddNumbers.add(<span class="hljs-number">5</span>);
        oddNumbers.add(<span class="hljs-number">7</span>);
        oddNumbers.add(<span class="hljs-number">9</span>);

        System.out.println(oddNumbers.get(<span class="hljs-number">2</span>)); <span class="hljs-comment">// 5</span>
    }
}
</code></pre>
<p>The <code>get()</code> method will get the value in the given index. Just like <code>get()</code> you can use the <code>set()</code> method to update the value of an element.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.time.LocalDate;
<span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        ArrayList&lt;Integer&gt; oddNumbers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

        oddNumbers.add(<span class="hljs-number">1</span>);
        oddNumbers.add(<span class="hljs-number">3</span>);
        oddNumbers.add(<span class="hljs-number">5</span>);
        oddNumbers.add(<span class="hljs-number">7</span>);
        oddNumbers.add(<span class="hljs-number">9</span>);

        oddNumbers.set(<span class="hljs-number">2</span>, <span class="hljs-number">55</span>);

        System.out.println(oddNumbers.get(<span class="hljs-number">2</span>)); <span class="hljs-comment">// 55</span>
    }
}
</code></pre>
<p>The first parameter to the <code>set()</code> method is the index and the second one is the updated value.</p>
<p>There is no <code>length</code> property like in an array but you can use the <code>size()</code> method on any array list to find out its length.</p>
<pre><code><span class="hljs-keyword">import</span> java.util.ArrayList;

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) {
        ArrayList&lt;Integer&gt; oddNumbers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

        oddNumbers.add(<span class="hljs-number">1</span>);
        oddNumbers.add(<span class="hljs-number">3</span>);
        oddNumbers.add(<span class="hljs-number">5</span>);
        oddNumbers.add(<span class="hljs-number">7</span>);
        oddNumbers.add(<span class="hljs-number">9</span>);

        System.out.println(oddNumbers.size()); <span class="hljs-comment">// 5</span>
    }
}
</code></pre><p>You can remove elements from an array list using the remove method:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        ArrayList&lt;Integer&gt; oddNumbers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

        oddNumbers.add(<span class="hljs-number">1</span>);
        oddNumbers.add(<span class="hljs-number">3</span>);
        oddNumbers.add(<span class="hljs-number">5</span>);
        oddNumbers.add(<span class="hljs-number">7</span>);
        oddNumbers.add(<span class="hljs-number">9</span>);

        oddNumbers.remove(Integer.valueOf(<span class="hljs-number">7</span>));
        oddNumbers.remove(Integer.valueOf(<span class="hljs-number">9</span>));

        System.out.println(oddNumbers.toString()); <span class="hljs-comment">// [1, 3, 5]</span>
    }
}
</code></pre>
<p>The <code>remove()</code> method can remove an element by value or by index. If you pass a primitive integer value to the method, it'll remove the element in the given index.</p>
<p>But if you pass an object like in this code, the method will find and delete that given element. The <code>valueOf()</code> method is present in all wrapper classes and it can convert a primitive value to a reference type.</p>
<h3 id="heading-how-to-add-or-remove-multiple-elements">How to Add or Remove Multiple Elements</h3>
<p>You've already seen examples of the <code>add()</code> and <code>remove()</code> methods. There are two other methods <code>addAll()</code> and <code>removeAll()</code> for working with multiple elements.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        ArrayList&lt;Integer&gt; oddNumbers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

        oddNumbers.add(<span class="hljs-number">1</span>);
        oddNumbers.add(<span class="hljs-number">3</span>);
        oddNumbers.add(<span class="hljs-number">5</span>);

        ArrayList&lt;Integer&gt; moreOddNumbers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

        moreOddNumbers.add(<span class="hljs-number">7</span>);
        moreOddNumbers.add(<span class="hljs-number">9</span>);
        moreOddNumbers.add(<span class="hljs-number">11</span>);

        oddNumbers.addAll(moreOddNumbers); <span class="hljs-comment">// [1, 3, 5, 7, 9, 11]</span>

        System.out.println(oddNumbers.toString());

        oddNumbers.removeAll(moreOddNumbers);

        System.out.println(oddNumbers.toString()); <span class="hljs-comment">// [1, 3, 5]</span>
    }
}
</code></pre>
<p>Both methods accept collections as their parameter. In the code above, you're creating two separate array lists and joining them using the <code>addAll()</code> method. </p>
<p>Then you remove the elements from the second array list using the <code>removeAll()</code> method and the array list goes back to its original state.</p>
<p>You can also drop all elements from an array list using the <code>clear()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        ArrayList&lt;Integer&gt; oddNumbers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

        oddNumbers.add(<span class="hljs-number">1</span>);
        oddNumbers.add(<span class="hljs-number">3</span>);
        oddNumbers.add(<span class="hljs-number">5</span>);

        oddNumbers.clear();

        System.out.println(oddNumbers.toString()); <span class="hljs-comment">// []</span>
    }
}
</code></pre>
<p>The method doesn't require any parameter at all and also doesn't return any value. It just empties your array list in a single call.</p>
<h3 id="heading-how-to-remove-elements-based-on-a-condition">How to Remove Elements Based on a Condition</h3>
<p>The <code>removeIf()</code> method can remove elements from an array list if they meet a certain condition:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        ArrayList&lt;Integer&gt; numbers = <span class="hljs-keyword">new</span> ArrayList&lt;&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">10</span>; i++) {
            numbers.add(i);
        }

        System.out.println(numbers.toString()); <span class="hljs-comment">// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</span>

        numbers.removeIf(number -&gt; number % <span class="hljs-number">2</span> == <span class="hljs-number">1</span>);

        System.out.println(numbers.toString()); <span class="hljs-comment">// [0, 2, 4, 6, 8, 10]</span>
    }
}
</code></pre>
<p>The method takes a lambda expression as a parameter. Lambda expressions are like unnamed methods. They can receive parameters and work with them.</p>
<p>Here, the <code>removeIf()</code> method will loop over the array list and pass each element to the lambda expression as the value of the <code>number</code> variable.</p>
<p>Then the lambda expression will check whether the given number is divisible by 2 or not and return <code>true</code> or <code>false</code> based on that.</p>
<p>If the lambda expression returns <code>true</code>, the <code>removeIf()</code> method will keep the value. Otherwise the value will be deleted.</p>
<h3 id="heading-how-to-clone-and-compare-array-lists">How to Clone and Compare Array Lists</h3>
<p>To make a duplicate of an array list, you can use the <code>clone()</code> method.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        ArrayList&lt;Integer&gt; numbers = <span class="hljs-keyword">new</span> ArrayList&lt;&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">10</span>; i++) {
            numbers.add(i);
        }

        ArrayList&lt;Integer&gt; numbersCloned = (ArrayList&lt;Integer&gt;)numbers.clone();

        System.out.println(numbersCloned.equals(numbers)); <span class="hljs-comment">// true</span>
    }
}
</code></pre>
<p>The <code>clone()</code> method returns an object, so you'll have to cast it to a proper array list manually. You can compare two array lists using the <code>equals()</code> method just like in arrays.</p>
<h3 id="heading-how-to-check-if-an-element-is-present-or-the-array-list-is-empty">How to Check if an Element Is Present or the Array List Is Empty</h3>
<p>You can use the <code>contains()</code> method to check if an array list contains a given element or not:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        ArrayList&lt;Integer&gt; oddNumbers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

        oddNumbers.add(<span class="hljs-number">1</span>);
        oddNumbers.add(<span class="hljs-number">3</span>);
        oddNumbers.add(<span class="hljs-number">5</span>);
        oddNumbers.add(<span class="hljs-number">7</span>);
        oddNumbers.add(<span class="hljs-number">9</span>);

        System.out.println(oddNumbers.isEmpty()); <span class="hljs-comment">// false</span>
        System.out.println(oddNumbers.contains(<span class="hljs-number">5</span>)); <span class="hljs-comment">// true</span>
    }
}
</code></pre>
<p>If you want to check if an array list is empty or not, just call the <code>isEmpty()</code> method on it and you'll get a boolean in return.</p>
<h3 id="heading-how-to-sort-an-array-list">How to Sort an Array List</h3>
<p>You can sort an array list in different orders using the <code>sort()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.Comparator;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        ArrayList&lt;Integer&gt; oddNumbers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

        oddNumbers.add(<span class="hljs-number">5</span>);
        oddNumbers.add(<span class="hljs-number">7</span>);
        oddNumbers.add(<span class="hljs-number">1</span>);
        oddNumbers.add(<span class="hljs-number">9</span>);
        oddNumbers.add(<span class="hljs-number">3</span>);

        System.out.println(oddNumbers.toString()); [<span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">1</span>, <span class="hljs-number">9</span>, <span class="hljs-number">3</span>]

        oddNumbers.sort(Comparator.naturalOrder());

        System.out.println(oddNumbers.toString()); [<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>]
    }
}
</code></pre>
<p>The <code>sort()</code> method takes a comparator as its parameter. A comparator imposes the order of sorting on the array list.</p>
<p>You can sort the array list in reverse order just by changing the passed comparator:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.Comparator;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        ArrayList&lt;Integer&gt; oddNumbers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

        oddNumbers.add(<span class="hljs-number">5</span>);
        oddNumbers.add(<span class="hljs-number">7</span>);
        oddNumbers.add(<span class="hljs-number">1</span>);
        oddNumbers.add(<span class="hljs-number">9</span>);
        oddNumbers.add(<span class="hljs-number">3</span>);

        System.out.println(oddNumbers.toString()); <span class="hljs-comment">// [5, 7, 1, 9, 3]</span>

        oddNumbers.sort(Comparator.reverseOrder());

        System.out.println(oddNumbers.toString()); <span class="hljs-comment">// [9, 7, 5, 3, 1]</span>
    }
}
</code></pre>
<p>Comparators have other usages as well but those are out of the scope of this book.</p>
<h3 id="heading-how-to-keep-common-elements-from-two-array-lists">How to Keep Common Elements From Two Array Lists</h3>
<p>Think of a scenario where you have two array lists. Now you'll have to find out which elements are present in both array lists and remove the rest from the first array list.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        ArrayList&lt;Integer&gt; oddNumbers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

        oddNumbers.add(<span class="hljs-number">1</span>);
        oddNumbers.add(<span class="hljs-number">3</span>);
        oddNumbers.add(<span class="hljs-number">5</span>);

        ArrayList&lt;Integer&gt; moreOddNumbers = <span class="hljs-keyword">new</span> ArrayList&lt;Integer&gt;();

        moreOddNumbers.add(<span class="hljs-number">5</span>);
        moreOddNumbers.add(<span class="hljs-number">7</span>);
        moreOddNumbers.add(<span class="hljs-number">9</span>);

        oddNumbers.retainAll(moreOddNumbers);

        System.out.println(oddNumbers.toString()); <span class="hljs-comment">// [5]</span>
    }
}
</code></pre>
<p>The <code>retainAll()</code> method can get rid of the uncommon elements from the first array list for you. You'll need to call the method on the array list you want to operate on and pass the second array list as a parameter.</p>
<h3 id="heading-how-to-perform-an-action-on-all-elements-of-an-array-list">How to Perform an Action on All Elements of an Array List</h3>
<p>You've already learned about looping in previous sections. Well, array lists have a <code>forEach()</code> method of their own that takes a lambda expression as parameter and can perform an action on all the elements of the array list.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        ArrayList&lt;Integer&gt; oddNumbers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

        oddNumbers.add(<span class="hljs-number">1</span>);
        oddNumbers.add(<span class="hljs-number">3</span>);
        oddNumbers.add(<span class="hljs-number">5</span>);
        oddNumbers.add(<span class="hljs-number">7</span>);
        oddNumbers.add(<span class="hljs-number">9</span>);

        oddNumbers.forEach(number -&gt; {
            number = number * <span class="hljs-number">2</span>;
            System.out.printf(<span class="hljs-string">"%d "</span>, number); <span class="hljs-comment">// 2 6 10 14 18</span>
        });

        System.out.println(oddNumbers.toString()); <span class="hljs-comment">// [1, 3, 5, 7, 9]</span>
    }
}
</code></pre>
<p>Last time, the lambda expression you saw was a single line – but they can be bigger. Here, the <code>forEach()</code> method will loop over the array list and pass each element to the lambda expression as the value of the <code>number</code> variable.</p>
<p>The lambda expression will then multiply the supplied value by 2 and print it out on the terminal. However, the original array list will be unchanged.</p>
<h2 id="heading-how-to-work-with-hash-maps-in-java">How to Work With Hash Maps in Java</h2>
<p>Hash maps in Java can store elements in key-value pairs. This collection type is comparable to dictionaries in Python and objects in JavaScript.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.HashMap;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        HashMap&lt;String, Double&gt; prices = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

        prices.put(<span class="hljs-string">"apple"</span>, <span class="hljs-number">2.0</span>);
        prices.put(<span class="hljs-string">"orange"</span>, <span class="hljs-number">1.8</span>);
        prices.put(<span class="hljs-string">"guava"</span>, <span class="hljs-number">1.5</span>);
        prices.put(<span class="hljs-string">"berry"</span>, <span class="hljs-number">2.5</span>);
        prices.put(<span class="hljs-string">"banana"</span>, <span class="hljs-number">1.0</span>);

        System.out.printf(prices.toString()); <span class="hljs-comment">// {orange=1.8, banana=1.0, apple=2.0, berry=2.5, guava=1.5}</span>
    }
}
</code></pre>
<p>To create hash maps, you'll first have to import the <code>java.util.HashMap</code> class at the top of your source file.</p>
<p>Then you start by writing <code>HashMap</code> and then inside a pair of less than-greater than signs, you'll write the data type for the key and the value.</p>
<p>Here, the keys will be strings and values will be doubles. After that the assignment operator, followed by <code>new HashMap&lt;&gt;()</code>.</p>
<p>You can use the <code>put()</code> method to put a record in the hash map. The method takes the key as the first parameter and its corresponding value as the second parameter.</p>
<p>There is also the <code>putIfAbsent()</code> method that adds the given element only if it already doesn't exist in the hash map.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.HashMap;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        HashMap&lt;String, Double&gt; prices = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

        prices.put(<span class="hljs-string">"apple"</span>, <span class="hljs-number">2.0</span>);
        prices.put(<span class="hljs-string">"orange"</span>, <span class="hljs-number">1.8</span>);
        prices.put(<span class="hljs-string">"guava"</span>, <span class="hljs-number">1.5</span>);
        prices.put(<span class="hljs-string">"berry"</span>, <span class="hljs-number">2.5</span>);
        prices.put(<span class="hljs-string">"banana"</span>, <span class="hljs-number">1.0</span>);

        prices.putIfAbsent(<span class="hljs-string">"guava"</span>, <span class="hljs-number">2.9</span>);

        System.out.println(prices.toString()); <span class="hljs-comment">// {orange=1.8, banana=1.0, apple=2.0, berry=2.5, guava=1.5}</span>
    }
}
</code></pre>
<p>You can use the <code>get()</code> method to bring out a value from the hash map. The method takes the key as its parameter.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.HashMap;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        HashMap&lt;String, Double&gt; prices = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

        prices.put(<span class="hljs-string">"apple"</span>, <span class="hljs-number">2.0</span>);
        prices.put(<span class="hljs-string">"orange"</span>, <span class="hljs-number">1.8</span>);
        prices.put(<span class="hljs-string">"guava"</span>, <span class="hljs-number">1.5</span>);
        prices.put(<span class="hljs-string">"berry"</span>, <span class="hljs-number">2.5</span>);
        prices.put(<span class="hljs-string">"banana"</span>, <span class="hljs-number">1.0</span>);

        System.out.println(prices.get(<span class="hljs-string">"banana"</span>)); <span class="hljs-comment">// 1.000000</span>
    }
}
</code></pre>
<p>There is another variation of the this method. The <code>getOrDefault()</code> method works like <code>get()</code> but if the given key is not found, it'll return a specified default value.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.HashMap;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        HashMap&lt;String, Double&gt; prices = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

        prices.put(<span class="hljs-string">"apple"</span>, <span class="hljs-number">2.0</span>);
        prices.put(<span class="hljs-string">"orange"</span>, <span class="hljs-number">1.8</span>);
        prices.put(<span class="hljs-string">"guava"</span>, <span class="hljs-number">1.5</span>);
        prices.put(<span class="hljs-string">"berry"</span>, <span class="hljs-number">2.5</span>);
        prices.put(<span class="hljs-string">"banana"</span>, <span class="hljs-number">1.0</span>);

        System.out.println(prices.getOrDefault(<span class="hljs-string">"jackfruit"</span>, <span class="hljs-number">0.0</span>)); <span class="hljs-comment">// 0.0</span>
    }
}
</code></pre>
<p>The default value has to match the type of the values in the hash map. You can update a value in a hash map using the <code>replace()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.HashMap;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        HashMap&lt;String, Double&gt; prices = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

        prices.put(<span class="hljs-string">"apple"</span>, <span class="hljs-number">2.0</span>);
        prices.put(<span class="hljs-string">"orange"</span>, <span class="hljs-number">1.8</span>);
        prices.put(<span class="hljs-string">"guava"</span>, <span class="hljs-number">1.5</span>);
        prices.put(<span class="hljs-string">"berry"</span>, <span class="hljs-number">2.5</span>);
        prices.put(<span class="hljs-string">"banana"</span>, <span class="hljs-number">1.0</span>);

        prices.replace(<span class="hljs-string">"berry"</span>, <span class="hljs-number">2.8</span>);

        System.out.printf(prices.toString()); <span class="hljs-comment">// {orange=1.8, banana=1.0, apple=2.0, berry=2.8, guava=1.5}</span>
    }
}
</code></pre>
<p>For removing elements from a hash map, you can use the aptly named <code>remove()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.HashMap;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        HashMap&lt;String, Double&gt; prices = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

        prices.put(<span class="hljs-string">"apple"</span>, <span class="hljs-number">2.0</span>);
        prices.put(<span class="hljs-string">"orange"</span>, <span class="hljs-number">1.8</span>);
        prices.put(<span class="hljs-string">"guava"</span>, <span class="hljs-number">1.5</span>);
        prices.put(<span class="hljs-string">"berry"</span>, <span class="hljs-number">2.5</span>);
        prices.put(<span class="hljs-string">"banana"</span>, <span class="hljs-number">1.0</span>);

        prices.remove(<span class="hljs-string">"guava"</span>);

        System.out.printf(prices.toString()); <span class="hljs-comment">// {orange=1.8, banana=1.0, apple=2.0, berry=2.5}</span>
    }
}
</code></pre>
<p>If you ever need to know how many entries are there in a hash map, you can do so by using the <code>size()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.HashMap;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        HashMap&lt;String, Double&gt; prices = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

        prices.put(<span class="hljs-string">"apple"</span>, <span class="hljs-number">2.0</span>);
        prices.put(<span class="hljs-string">"orange"</span>, <span class="hljs-number">1.8</span>);
        prices.put(<span class="hljs-string">"guava"</span>, <span class="hljs-number">1.5</span>);
        prices.put(<span class="hljs-string">"berry"</span>, <span class="hljs-number">2.5</span>);
        prices.put(<span class="hljs-string">"banana"</span>, <span class="hljs-number">1.0</span>);

        System.out.println(prices.size()); <span class="hljs-comment">// 5</span>
    }
}
</code></pre>
<p>Finally if you want to clear a hash map in Java, you can do so by using the <code>clear()</code> method.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.HashMap;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        HashMap&lt;String, Double&gt; prices = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

        prices.put(<span class="hljs-string">"apple"</span>, <span class="hljs-number">2.0</span>);
        prices.put(<span class="hljs-string">"orange"</span>, <span class="hljs-number">1.8</span>);
        prices.put(<span class="hljs-string">"guava"</span>, <span class="hljs-number">1.5</span>);
        prices.put(<span class="hljs-string">"berry"</span>, <span class="hljs-number">2.5</span>);
        prices.put(<span class="hljs-string">"banana"</span>, <span class="hljs-number">1.0</span>);

        prices.clear();

        System.out.println(prices.toString()); <span class="hljs-comment">// {}</span>
    }
}
</code></pre>
<p>Just like in the array lists, the method doesn't take any argument or return any value.</p>
<h3 id="heading-how-to-put-in-or-replace-multiple-elements-in-a-hash-map">How to Put in or Replace Multiple Elements in a Hash Map</h3>
<p>If you want to put multiple elements into a hash map in a single go, you can do so by using the <code>putAll()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.HashMap;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        HashMap&lt;String, Double&gt; prices = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

        prices.put(<span class="hljs-string">"apple"</span>, <span class="hljs-number">2.0</span>);
        prices.put(<span class="hljs-string">"orange"</span>, <span class="hljs-number">1.8</span>);
        prices.put(<span class="hljs-string">"guava"</span>, <span class="hljs-number">1.5</span>);
        prices.put(<span class="hljs-string">"berry"</span>, <span class="hljs-number">2.5</span>);
        prices.put(<span class="hljs-string">"banana"</span>, <span class="hljs-number">1.0</span>);

        HashMap&lt;String, Double&gt; morePrices = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

        prices.put(<span class="hljs-string">"jackfruit"</span>, <span class="hljs-number">2.9</span>);
        prices.put(<span class="hljs-string">"pineapple"</span>, <span class="hljs-number">1.1</span>);
        prices.put(<span class="hljs-string">"tomato"</span>, <span class="hljs-number">0.8</span>);

        prices.putAll(morePrices);

        System.out.println(prices.toString()); <span class="hljs-comment">// {orange=1.8, banana=1.0, apple=2.0, berry=2.5, pineapple=1.1, tomato=0.8, guava=1.5, jackfruit=2.9}</span>
    }
}
</code></pre>
<p>The method takes another hash map as its parameter and adds its elements to the one the method has been called upon.</p>
<p>You can also use the <code>replaceAll()</code> method to update multiple values in a hash map.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.HashMap;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        HashMap&lt;String, Double&gt; prices = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

        prices.put(<span class="hljs-string">"apple"</span>, <span class="hljs-number">2.0</span>);
        prices.put(<span class="hljs-string">"orange"</span>, <span class="hljs-number">1.8</span>);
        prices.put(<span class="hljs-string">"guava"</span>, <span class="hljs-number">1.5</span>);
        prices.put(<span class="hljs-string">"berry"</span>, <span class="hljs-number">2.5</span>);
        prices.put(<span class="hljs-string">"banana"</span>, <span class="hljs-number">1.0</span>);

        prices.replaceAll((fruit, price) -&gt; price * <span class="hljs-number">2</span>);

        System.out.println(prices.toString()); <span class="hljs-comment">// {orange=3.6, banana=2.0, apple=4.0, berry=5.0, guava=3.0}</span>
    }
}
</code></pre>
<p>The replace all method iterates over the hashmap and passes each key value pair to the lambda expression.</p>
<p>The first parameter to the lambda expression is the key and the second one is the value. Inside the lambda expression, you perform your actions.</p>
<h3 id="heading-how-to-check-if-a-hash-map-contains-an-item-or-if-its-empty">How to Check if a Hash Map Contains an Item or if It’s Empty</h3>
<p>You can use the methods <code>containsKey()</code> and <code>containsValue()</code> for checking if a hash map contains a value or not.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.HashMap;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        HashMap&lt;String, Double&gt; prices = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

        prices.put(<span class="hljs-string">"apple"</span>, <span class="hljs-number">2.0</span>);
        prices.put(<span class="hljs-string">"orange"</span>, <span class="hljs-number">1.8</span>);
        prices.put(<span class="hljs-string">"guava"</span>, <span class="hljs-number">1.5</span>);
        prices.put(<span class="hljs-string">"berry"</span>, <span class="hljs-number">2.5</span>);
        prices.put(<span class="hljs-string">"banana"</span>, <span class="hljs-number">1.0</span>);

        System.out.println(prices.containsKey(<span class="hljs-string">"banana"</span>)); <span class="hljs-comment">// true</span>
        System.out.println(prices.containsValue(<span class="hljs-number">2.5</span>)); <span class="hljs-comment">// true</span>
    }
}
</code></pre>
<p>Difference between the two methods is that the <code>containsKey()</code> method checks if the given key exists or not and the <code>containsValue()</code> method checks if the given value exists or not.</p>
<p>And if you want to check if a hash map is empty or not, you can do so by using the <code>isEmpty()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.HashMap;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        HashMap&lt;String, Double&gt; prices = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

        prices.put(<span class="hljs-string">"apple"</span>, <span class="hljs-number">2.0</span>);
        prices.put(<span class="hljs-string">"orange"</span>, <span class="hljs-number">1.8</span>);
        prices.put(<span class="hljs-string">"guava"</span>, <span class="hljs-number">1.5</span>);
        prices.put(<span class="hljs-string">"berry"</span>, <span class="hljs-number">2.5</span>);
        prices.put(<span class="hljs-string">"banana"</span>, <span class="hljs-number">1.0</span>);

        System.out.println(prices.isEmpty()); <span class="hljs-comment">// false</span>
    }
}
</code></pre>
<p>Since the method returns a boolean value, you can use it within if-else statements.</p>
<h3 id="heading-how-to-perform-an-action-on-all-elements-of-a-hash-map">How to Perform an Action on All Elements of a Hash Map</h3>
<p>Like the array lists, hash maps also have their own <code>forEach()</code> method that you can use to loop over the hash map and repeat a certain action over each entry.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.HashMap;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        HashMap&lt;String, Double&gt; prices = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

        prices.put(<span class="hljs-string">"apple"</span>, <span class="hljs-number">2.0</span>);
        prices.put(<span class="hljs-string">"orange"</span>, <span class="hljs-number">1.8</span>);
        prices.put(<span class="hljs-string">"guava"</span>, <span class="hljs-number">1.5</span>);
        prices.put(<span class="hljs-string">"berry"</span>, <span class="hljs-number">2.5</span>);
        prices.put(<span class="hljs-string">"banana"</span>, <span class="hljs-number">1.0</span>);

        System.out.println(<span class="hljs-string">"prices after discounts"</span>);

        prices.forEach((fruit, price) -&gt; {
            System.out.println(fruit + <span class="hljs-string">" - "</span> + (price - <span class="hljs-number">0.5</span>));
        });
    }
}

<span class="hljs-comment">// prices after discounts</span>
<span class="hljs-comment">// orange - 1.3</span>
<span class="hljs-comment">// banana - 0.5</span>
<span class="hljs-comment">// apple - 1.5</span>
<span class="hljs-comment">// berry - 2.0</span>
<span class="hljs-comment">// guava - 1.0</span>
</code></pre>
<p>The method loops over each entry and passes the key and value to the lambda expression. Inside the lambda expression body, you can do whatever you want.</p>
<h2 id="heading-classes-and-objects-in-java">Classes and Objects in Java</h2>
<p>Here's a <a target="_blank" href="https://en.wikipedia.org/wiki/Object-oriented_programming">helpful definition of object-oriented programming</a>:</p>
<blockquote>
<p>OOP (Object-oriented programming) is a programming paradigm based on the concept of "objects", which can contain data and code: data in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods).</p>
</blockquote>
<p>Imagine a library management system where members of the library can log in, take a look at the books they have already borrowed, request new ones, and so on.</p>
<p>In this system the users and the books can all be objects. These objects will have their own properties such as name and birthday (in case of a user) and title and author in case of the books.</p>
<p>Classes in object oriented programming are blueprints for the aforementioned objects. We've already discussed the possible properties of the user and book objects.</p>
<p>To create a new <code>User</code> class, right click on the <code>src</code> folder once again. Then go to <strong>New &gt; Java Class</strong>, name it <code>User</code>, and hit enter.</p>
<p>Keeping the previously discussed properties in mind, your code for the <code>User</code> class should be as follows:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.time.LocalDate;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    String name;
    LocalDate birthDay;
}
</code></pre>
<p>The <code>LocalDate</code> is a reference data type that represents a date. Now go back to the <code>Main.java</code> file and create a new instance of this class:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.time.LocalDate;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        User user = <span class="hljs-keyword">new</span> User();

        user.name = <span class="hljs-string">"Farhan"</span>;
        user.birthDay = LocalDate.parse(<span class="hljs-string">"1996-07-15"</span>);

        System.out.printf(<span class="hljs-string">"%s was born on %s."</span>, user.name, user.birthDay.toString()); <span class="hljs-comment">// Farhan was born on 15th July 1996.</span>
    }
}
</code></pre>
<p>Creating a new user is not very different from creating a new string or array. You start by writing out the name of the class then the instance or object name.</p>
<p>Then you put the assignment operator followed by the <code>new</code> keyword and the constructor call. The constructor is a special method that initializes the object.</p>
<p>The constructor has initialized the object properties with default values which is <code>null</code> for all these reference types.</p>
<p>You can access the properties of the object by writing out the name of the object followed by a dot and then the name of the property.</p>
<p>The <code>LocalDate.parse()</code> method can parse a date from a given string. Since the <code>birthDay</code> is a reference type, you'll have to use the <code>toString()</code> method to print out on the console.</p>
<h3 id="heading-what-is-a-method">What is a Method?</h3>
<p>The variables or properties of a class describe the state of its objects. Methods on the other hand describes the behavior.</p>
<p>For example, you can have a method within your <code>User</code> class that calculates the user's age.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.time.Period;
<span class="hljs-keyword">import</span> java.time.LocalDate;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    String name;
    LocalDate birthDay;

    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">age</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> Period.between(<span class="hljs-keyword">this</span>.birthDay, LocalDate.now()).getYears();
    }
}
</code></pre>
<p>Here, the <code>this</code> keyword represents the current instance of the class. You start by writing out the return type of the method. Since the age of a user is an integer, the return type of this method will be <code>int</code>.</p>
<p>After the return type, you write the name of the method, followed by a pair of parenthesis.</p>
<p>Then you write the method body within a pair of curly braces. The <code>Period</code> class in Java expresses a time frame in the ISO-8601 calendar system. The <code>LocalDate.now()</code> method returns the current date.</p>
<p>So the <code>Period.between(this.birthDay, LocalDate.now()).getYears()</code> method call will return the difference between the current date and the date of birth in years.</p>
<p>Now back in the <code>Main.java</code> file, you can call this method as follows:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.time.LocalDate;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        User user = <span class="hljs-keyword">new</span> User();

        user.name = <span class="hljs-string">"Farhan"</span>;
        user.birthDay = LocalDate.parse( <span class="hljs-string">"1996-07-15"</span>);

        System.out.printf(<span class="hljs-string">"%s is %s years old."</span>, user.name, user.age()); <span class="hljs-comment">// Farhan a 26 years old.</span>
    }
}
</code></pre>
<p>Methods can also accept parameters. For example, if you want to create a method <code>borrow()</code> for inserting new books into the list of borrowed books for this user, you can do so as follows:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.time.LocalDate;
<span class="hljs-keyword">import</span> java.time.Period;
<span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    String name;
    LocalDate birthDay;

    ArrayList&lt;String&gt; borrowedBooks = <span class="hljs-keyword">new</span> ArrayList&lt;String&gt;();

    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">age</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> Period.between(<span class="hljs-keyword">this</span>.birthDay, LocalDate.now()).getYears();
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">borrow</span><span class="hljs-params">(String bookTitle)</span> </span>{
        <span class="hljs-keyword">this</span>.borrowedBooks.add(bookTitle);
    }
}
</code></pre>
<p>Back in the <code>Main.java</code> file, you can call this method as follows:</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">Main</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>{
        User user = <span class="hljs-keyword">new</span> User();

        user.name = <span class="hljs-string">"Farhan"</span>;

        user.borrow(<span class="hljs-string">"Carmilla"</span>);
        user.borrow(<span class="hljs-string">"Hard West"</span>);

        System.out.printf(<span class="hljs-string">"%s has borrowed these books: %s"</span>, user.name, user.borrowedBooks.toString()); <span class="hljs-comment">// Farhan has borrowed these books: [Carmilla, Hard West]</span>
    }
}
</code></pre>
<p>Let's create a class for the books as well:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span> </span>{
    String title;
    ArrayList&lt;String&gt; authors = <span class="hljs-keyword">new</span> ArrayList&lt;String&gt;();
}
</code></pre>
<p>Books often have multiple authors. Now you can create a new book instance back in the <code>Main.java</code> file.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.time.LocalDate;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        User user = <span class="hljs-keyword">new</span> User();
        user.name = <span class="hljs-string">"Farhan"</span>;
        user.birthDay = LocalDate.parse( <span class="hljs-string">"1996-07-15"</span>);

        Book book = <span class="hljs-keyword">new</span> Book();
        book.title = <span class="hljs-string">"Carmilla"</span>;
        book.authors.add(<span class="hljs-string">"Sheridan Le Fanu"</span>);

        System.out.printf(<span class="hljs-string">"%s is written by %s"</span>, book.title, book.authors.toString()); <span class="hljs-comment">// Carmilla is written by [Sheridan Le Fanu]</span>

    }
}
</code></pre>
<p>Now let's go back to the <code>User.java</code> file and create a relationship between the users and the books:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.time.LocalDate;
<span class="hljs-keyword">import</span> java.time.Period;
<span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    String name;
    LocalDate birthDay;

    ArrayList&lt;Book&gt; borrowedBooks = <span class="hljs-keyword">new</span> ArrayList&lt;Book&gt;();

    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">age</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> Period.between(<span class="hljs-keyword">this</span>.birthDay, LocalDate.now()).getYears();
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">borrow</span><span class="hljs-params">(Book book)</span> </span>{
        <span class="hljs-keyword">this</span>.borrowedBooks.add(book);
    }
}
</code></pre>
<p>Instead of using an array list of strings, you're now using an array list of books to store the books borrowed by this user.</p>
<p>Since the argument type of the method has changed, you'll have to update the code in the <code>Main.java</code> file accordingly:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.time.LocalDate;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        User user = <span class="hljs-keyword">new</span> User();
        user.name = <span class="hljs-string">"Farhan"</span>;
        user.birthDay = LocalDate.parse( <span class="hljs-string">"1996-07-15"</span>);

        Book book = <span class="hljs-keyword">new</span> Book();
        book.title = <span class="hljs-string">"Carmilla"</span>;
        book.authors.add(<span class="hljs-string">"Sheridan Le Fanu"</span>);

        user.borrow(book);

        System.out.printf(<span class="hljs-string">"%s has borrowed these books: %s"</span>, user.name, user.borrowedBooks.toString()); <span class="hljs-comment">// Farhan has borrowed these books: [Book@30dae81]</span>
    }
}
</code></pre>
<p>Everything works out fine except the fact that book information has not been printed properly.</p>
<p>I hope you remember the <code>toString()</code> method. When you call <code>user.borrowedBooks.toString()</code> the compiler realizes that the items stored in the arraylist are objects or reference types. So it starts calling the <code>toString()</code> methods inside those items.</p>
<p>The problem is, there is no proper implementation of <code>toString()</code> in your <code>Book</code> class. Open <code>Book.java</code> and update its code as follows:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span> </span>{
    String title;
    ArrayList&lt;String&gt; authors = <span class="hljs-keyword">new</span> ArrayList&lt;String&gt;();

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> String.format(<span class="hljs-string">"%s by %s"</span>, <span class="hljs-keyword">this</span>.title, <span class="hljs-keyword">this</span>.authors.toString());
    }
}
</code></pre>
<p>The <code>toString()</code> method now returns a nicely formatted string instead of the object reference. Run the code once again and this time the output should be <code>Farhan has borrowed these books: [Carmilla by [Sheridan Le Fanu]]</code>.</p>
<p>As you can see, being able to design your software around real-life entities makes it a lot more relatable. Although there is just an array list and a bunch of strings in play, it feels like as if a real book borrowing operation is going on.</p>
<h3 id="heading-what-is-method-overloading">What is Method Overloading?</h3>
<p>In Java, multiple methods can have the same name if their parameters are different. This is called method overloading.</p>
<p>One example can be the <code>borrow()</code> method on the <code>User</code> class. Right now, it accepts a single book as its parameter. Let's make an overloaded version which can accept an array of books instead.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.time.LocalDate;
<span class="hljs-keyword">import</span> java.time.Period;
<span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> LocalDate birthDay;
    <span class="hljs-keyword">private</span> ArrayList&lt;Book&gt; borrowedBooks = <span class="hljs-keyword">new</span> ArrayList&lt;Book&gt;();

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.name;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>{
        <span class="hljs-keyword">this</span>.name = name;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getBorrowedBooks</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.borrowedBooks.toString();
    }

    User (String name, String birthDay) {
        <span class="hljs-keyword">this</span>.name = name;
        <span class="hljs-keyword">this</span>.birthDay = LocalDate.parse(birthDay);
    }

    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">age</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> Period.between(<span class="hljs-keyword">this</span>.birthDay, LocalDate.now()).getYears();
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">borrow</span><span class="hljs-params">(Book book)</span> </span>{
        borrowedBooks.add(book);
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">borrow</span><span class="hljs-params">(Book[] books)</span> </span>{
        borrowedBooks.addAll(Arrays.asList(books));
    }
}
</code></pre>
<p>The return type and name of the new method is identical to the previous one, but this one accepts an array of <code>Book</code> objects instead of a single object.</p>
<p>Let's update the <code>Main.java</code> file to make use of this overloaded method.</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">Main</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>{
        User user = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"Farhan"</span>, <span class="hljs-string">"1996-07-15"</span>);

        Book book1 = <span class="hljs-keyword">new</span> Book(<span class="hljs-string">"Carmilla"</span>, <span class="hljs-keyword">new</span> String[]{<span class="hljs-string">"Sheridan Le Fanu"</span>});
        Book book2 = <span class="hljs-keyword">new</span> Book(<span class="hljs-string">"Frankenstein"</span>, <span class="hljs-keyword">new</span> String[]{<span class="hljs-string">"Mary Shelley"</span>});
        Book book3 = <span class="hljs-keyword">new</span> Book(<span class="hljs-string">"Dracula"</span>, <span class="hljs-keyword">new</span> String[]{<span class="hljs-string">"Bram Stoker"</span>});

        user.borrow(<span class="hljs-keyword">new</span> Book[]{book1, book2});

        user.borrow(book3);

        System.out.printf(<span class="hljs-string">"%s has borrowed these books: %s"</span>, user.getName(), user.getBorrowedBooks());
    }
}
</code></pre>
<p>As you can see, the <code>borrow()</code> method now accepts an array of books or a single book object without any issue.</p>
<h2 id="heading-what-are-constructors-in-java">What are Constructors in Java?</h2>
<p>Constructors are a special kind of method that exists in every class, and whenever you create a new object from a class, the compiler calls it.</p>
<p>Since the method is called during the construction of an object, it's called a constructor. By default, a constructor assigns default values to all its properties.</p>
<p>To override the default constructor, you need to create a new method under your classes with the same name as the class.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.time.LocalDate;
<span class="hljs-keyword">import</span> java.time.Period;
<span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    <span class="hljs-keyword">public</span> String name;
    <span class="hljs-keyword">public</span> LocalDate birthDay;
    <span class="hljs-keyword">public</span> ArrayList&lt;Book&gt; borrowedBooks = <span class="hljs-keyword">new</span> ArrayList&lt;Book&gt;();

    User (String name, String birthDay) {
        <span class="hljs-keyword">this</span>.name = name;
        <span class="hljs-keyword">this</span>.birthDay = LocalDate.parse(birthDay);
    }

    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">age</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> Period.between(<span class="hljs-keyword">this</span>.birthDay, LocalDate.now()).getYears();
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">borrow</span><span class="hljs-params">(Book book)</span> </span>{
        <span class="hljs-keyword">this</span>.borrowedBooks.add(book);
    }
}
</code></pre>
<p>Now that you have a constructor, instead of parsing the date from a string in the <code>Main.java</code> file, you can do that here.</p>
<p>This is because the format of the birthday is the concern of the <code>User</code> class and the <code>Main</code> class doesn't need to bother about it.</p>
<p>Same treatment for the book class as well:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span> </span>{
    <span class="hljs-keyword">public</span> String title;
    <span class="hljs-keyword">public</span> ArrayList&lt;String&gt; authors = <span class="hljs-keyword">new</span> ArrayList&lt;String&gt;();

    Book(String title, String[] authors) {
        <span class="hljs-keyword">this</span>.title = title;
        <span class="hljs-keyword">this</span>.authors = <span class="hljs-keyword">new</span> ArrayList&lt;String&gt;(Arrays.asList(authors));
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> String.format(<span class="hljs-string">"%s by %s"</span>, <span class="hljs-keyword">this</span>.title, <span class="hljs-keyword">this</span>.authors.toString());
    }
}
</code></pre>
<p>Again, the type of the <code>authors</code> collection is not a concern of the <code>Main</code> class. The most basic way of working with a bunch of values in Java is an array.</p>
<p>So you'll receive the author names as an array from the <code>Main</code> class and create an array list out of it in the <code>Book</code> class.</p>
<p>Now you'll have to pass those parameters to the constructor when creating a new user or book object in the <code>Main.java</code> file.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        User user = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"Farhan"</span>, <span class="hljs-string">"1996-07-15"</span>);

        Book book = <span class="hljs-keyword">new</span> Book(<span class="hljs-string">"Carmilla"</span>, <span class="hljs-keyword">new</span> String[]{<span class="hljs-string">"Sheridan Le Fanu"</span>});

        user.borrow(book);

        System.out.printf(<span class="hljs-string">"%s has borrowed these books: %s"</span>, user.name, user.borrowedBooks.toString()); <span class="hljs-comment">// Farhan has borrowed these books: [Carmilla, Hard West]</span>
    }
}
</code></pre>
<p>Look how much cleaner it already looks. But soon it'll look better.</p>
<h2 id="heading-what-are-access-modifiers-in-java">What Are Access Modifiers in Java?</h2>
<p>You've already seen the keyword <code>public</code> multiple times. This is one of the access modifiers in Java. </p>
<p>There are four access modifiers in Java:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Primitive Type</td><td>Wrapper Class</td></tr>
</thead>
<tbody>
<tr>
<td>Default</td><td>Accessible within the package</td></tr>
<tr>
<td>Public</td><td>Accessible everywhere</td></tr>
<tr>
<td>Private</td><td>Accessible within the class</td></tr>
<tr>
<td>Protected</td><td>Accessible within the class and subclasses</td></tr>
</tbody>
</table>
</div><p>For now, I'll discuss the <code>Default</code>, <code>Public</code> and <code>Private</code> access modifiers. <code>Protected</code> will be discussed in a later section.</p>
<p>You've already learned about classes. Packages are collections of multiple classes separated by their functionality.</p>
<p>For example, if you're making a game, you can put all the physics-related classes in a separate package and the graphics-related ones in a different one.</p>
<p>Packages are outside of the scope of this book, but as you keep working on larger and larger projects, you'll get the hang of them.</p>
<p>The <code>Public</code> access modifier is pretty self-explanatory. These variables, methods, or classes are accessible from any other class or package in your project.</p>
<p>The <code>Private</code> ones, on the other hand, are the opposite. They're only available within their class.</p>
<p>Take the <code>User</code> class, for example. The name and birthday of a user shouldn't be accessible from the outside.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.time.LocalDate;
<span class="hljs-keyword">import</span> java.time.Period;
<span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> LocalDate birthDay;
    <span class="hljs-keyword">private</span> ArrayList&lt;Book&gt; borrowedBooks = <span class="hljs-keyword">new</span> ArrayList&lt;Book&gt;();

    User (String name, String birthDay) {
        <span class="hljs-keyword">this</span>.name = name;
        <span class="hljs-keyword">this</span>.birthDay = LocalDate.parse(birthDay);
    }

    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">age</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> Period.between(<span class="hljs-keyword">this</span>.birthDay, LocalDate.now()).getYears();
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">borrow</span><span class="hljs-params">(Book book)</span> </span>{
        borrowedBooks.add(book);
    }
}
</code></pre>
<p>That's better. Update the <code>Book</code> class as well to hide the title and author information from the outside world.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span> </span>{
    <span class="hljs-keyword">private</span> String title;
    <span class="hljs-keyword">private</span> ArrayList&lt;String&gt; authors = <span class="hljs-keyword">new</span> ArrayList&lt;String&gt;();

    Book(String title, String[] authors) {
        <span class="hljs-keyword">this</span>.title = title;
        <span class="hljs-keyword">this</span>.authors = <span class="hljs-keyword">new</span> ArrayList&lt;String&gt;(Arrays.asList(authors));
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> String.format(<span class="hljs-string">"%s by %s"</span>, <span class="hljs-keyword">this</span>.title, <span class="hljs-keyword">this</span>.authors.toString());
    }
}
</code></pre>
<p>Since the properties have become private now, the <code>System.out.println()</code> line in the <code>Main.java</code> file will fail to directly access them and will cause an issue.</p>
<p>The solution to this program is writing public methods that other classes can use to access these properties.</p>
<h2 id="heading-what-are-the-getter-and-setter-methods-in-java">What Are the Getter and Setter Methods in Java?</h2>
<p>Getters and setters are public methods in classes used to read and write private properties.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.time.LocalDate;
<span class="hljs-keyword">import</span> java.time.Period;
<span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> LocalDate birthDay;
    <span class="hljs-keyword">private</span> ArrayList&lt;Book&gt; borrowedBooks = <span class="hljs-keyword">new</span> ArrayList&lt;Book&gt;();

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.name;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getBirthDay</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.birthDay.toString();
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getBorrowedBooks</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.borrowedBooks.toString();
    }

    User (String name, String birthDay) {
        <span class="hljs-keyword">this</span>.name = name;
        <span class="hljs-keyword">this</span>.birthDay = LocalDate.parse(birthDay);
    }

    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">age</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> Period.between(<span class="hljs-keyword">this</span>.birthDay, LocalDate.now()).getYears();
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">borrow</span><span class="hljs-params">(Book book)</span> </span>{
        borrowedBooks.add(book);
    }
}
</code></pre>
<p>The <code>getName()</code> and <code>getBorrowedBooks()</code> are responsible for returning the value of the <code>name</code> and <code>borrowedBooks</code> variables.</p>
<p>You never actually access the birthday variable out of the <code>age()</code> method, so a getter is not necessary.</p>
<p>Since the type of the <code>borrowedBooks</code> variable is not a concern of the <code>Main</code> class, the getter makes sure to return the value in the proper format.</p>
<p>Now update the code in the <code>Main.java</code> file to make use of these methods:</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">Main</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>{
        User user = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"Farhan"</span>, <span class="hljs-string">"1996-07-15"</span>);

        Book book = <span class="hljs-keyword">new</span> Book(<span class="hljs-string">"Carmilla"</span>, <span class="hljs-keyword">new</span> String[]{<span class="hljs-string">"Sheridan Le Fanu"</span>});

        user.borrow(book);

        System.out.printf(<span class="hljs-string">"%s has borrowed these books: %s"</span>, user.getName(), user.getBorrowedBooks());
    }
}
</code></pre>
<p>Excellent. It has become even cleaner and easier to read. Like getters, there are setters for writing values to the private properties.</p>
<p>For example, you may want to allow the user to change their name or birthday. The <code>borrow()</code> method already works as a setter for the <code>borrowedBooks</code> array list.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.time.LocalDate;
<span class="hljs-keyword">import</span> java.time.Period;
<span class="hljs-keyword">import</span> java.util.ArrayList;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> LocalDate birthDay;
    <span class="hljs-keyword">private</span> ArrayList&lt;Book&gt; borrowedBooks = <span class="hljs-keyword">new</span> ArrayList&lt;Book&gt;();

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.name;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>{
        <span class="hljs-keyword">this</span>.name = name;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setBirthDay</span><span class="hljs-params">(String birthDay)</span> </span>{
        <span class="hljs-keyword">this</span>.birthDay = LocalDate.parse(birthDay);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getBorrowedBooks</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.borrowedBooks.toString();
    }

    User (String name, String birthDay) {
        <span class="hljs-keyword">this</span>.name = name;
        <span class="hljs-keyword">this</span>.birthDay = LocalDate.parse(birthDay);
    }

    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">age</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> Period.between(<span class="hljs-keyword">this</span>.birthDay, LocalDate.now()).getYears();
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">borrow</span><span class="hljs-params">(Book book)</span> </span>{
        borrowedBooks.add(book);
    }
}
</code></pre>
<p>Now you can call the <code>setName()</code> method with whatever name you want to set to the user. Similarly, the <code>setBirthDay()</code> method can set the birthday.</p>
<p>You can implement some getters and setters for the <code>Book</code> class as well.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span> </span>{
    <span class="hljs-keyword">private</span> String title;
    <span class="hljs-keyword">private</span> ArrayList&lt;String&gt; authors = <span class="hljs-keyword">new</span> ArrayList&lt;String&gt;();

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getTitle</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.title;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setTitle</span><span class="hljs-params">(String title)</span> </span>{
        <span class="hljs-keyword">this</span>.title = title;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getAuthors</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.authors.toString();
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setTitle</span><span class="hljs-params">(String[] authors)</span> </span>{
        <span class="hljs-keyword">this</span>.authors = <span class="hljs-keyword">new</span> ArrayList&lt;String&gt;(Arrays.asList(authors));
    }

    Book(String title, String[] authors) {
        <span class="hljs-keyword">this</span>.title = title;
        <span class="hljs-keyword">this</span>.authors = <span class="hljs-keyword">new</span> ArrayList&lt;String&gt;(Arrays.asList(authors));
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> String.format(<span class="hljs-string">"%s by %s"</span>, <span class="hljs-keyword">this</span>.title, <span class="hljs-keyword">this</span>.authors.toString());
    }
}
</code></pre>
<p>Now you can not access those properties directly. Instead you'll have to use one of the getters or setters.</p>
<h2 id="heading-what-is-inheritance-in-java">What is Inheritance in Java?</h2>
<p>Inheritance is another big feature of object oriented programming. Imagine you have three kinds of books. The regular ones, e-books, and audio books.</p>
<p>Although they have similarities such as title and author, they also have some differences. For example, the regular books and e-books have page count whereas audio books have run time. The e-books also have format such as PDF or EPUB.</p>
<p>So using the same class for all three of them is not an option. That doesn't mean you'll have to create three separate classes with minor differences, though. You can just create separate classes for e-books and audio books and make them inherit the properties and methods from the <code>Book</code> class.</p>
<p>Let's begin by adding the page count in the <code>Book</code> class:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span> </span>{
    <span class="hljs-keyword">private</span> String title;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> pageCount;
    <span class="hljs-keyword">private</span> ArrayList&lt;String&gt; authors = <span class="hljs-keyword">new</span> ArrayList&lt;String&gt;();

    Book(String title, <span class="hljs-keyword">int</span> pageCount, String[] authors) {
        <span class="hljs-keyword">this</span>.title = title;
        <span class="hljs-keyword">this</span>.pageCount = pageCount;
        <span class="hljs-keyword">this</span>.authors = <span class="hljs-keyword">new</span> ArrayList&lt;String&gt;(Arrays.asList(authors));
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">length</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> String.format(<span class="hljs-string">"%s is %d pages long."</span>, <span class="hljs-keyword">this</span>.title, <span class="hljs-keyword">this</span>.pageCount);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> String.format(<span class="hljs-string">"%s by %s"</span>, <span class="hljs-keyword">this</span>.title, <span class="hljs-keyword">this</span>.authors.toString());
    }
}
</code></pre>
<p>Since you're not going to use getters and setters in these examples, cleaning up seemed like a good idea. The <code>length()</code> method returns the length of the book as a string.</p>
<p>Now create a new Java class named <code>AudioBook</code> and put the following code in it:</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">AudioBook</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Book</span></span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> runTime;

    AudioBook(String title, String[] authors, <span class="hljs-keyword">int</span> runTime) {
        <span class="hljs-keyword">super</span>(title, <span class="hljs-number">0</span>, authors);

        <span class="hljs-keyword">this</span>.runTime = runTime;
    }
}
</code></pre>
<p>The <code>extends</code> keyword lets the compiler know that this class is a subclass of the <code>Book</code> class. This means that this class inherits all the properties and methods from the parent class.</p>
<p>Inside the <code>AudioBook</code> constructor method, you set the run time for the audio book which is fine – but you'll also have to manually call the constructor of the parent class.</p>
<p>The <code>super</code> keyword in Java refers to the parent class, so <code>super(title, 0, authors)</code> essentially calls the parent constructor method with the necessary parameters.</p>
<p>Since the audio books don't have any pages, setting the page count to zero can be an easy solution.</p>
<p>Or you can create an overloaded version of the <code>Book</code> constructor method that doesn't require the page count.</p>
<p>Next, create another Java class named <code>Ebook</code> with the following code:</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">Ebook</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Book</span></span>{
    <span class="hljs-keyword">private</span> String format;

    Ebook(String title, <span class="hljs-keyword">int</span> pageCount, String[] authors, String format) {
        <span class="hljs-keyword">super</span>(title, pageCount, authors);

        <span class="hljs-keyword">this</span>.format = format;
    }
}
</code></pre>
<p>This class is largely identical to the <code>Book</code> class except the fact that it has a format property.</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">Main</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>{
        Book book = <span class="hljs-keyword">new</span> Book(<span class="hljs-string">"Carmilla"</span>, <span class="hljs-number">200</span>, <span class="hljs-keyword">new</span> String[]{<span class="hljs-string">"Sheridan Le Fanu"</span>});
        Ebook ebook = <span class="hljs-keyword">new</span> Ebook(<span class="hljs-string">"Frankenstein"</span>, <span class="hljs-number">220</span>, <span class="hljs-keyword">new</span> String[]{<span class="hljs-string">"Mary Shelley"</span>}, <span class="hljs-string">"EPUB"</span>);
        AudioBook audioBook = <span class="hljs-keyword">new</span> AudioBook(<span class="hljs-string">"Dracula"</span>, <span class="hljs-keyword">new</span> String[]{<span class="hljs-string">"Bram Stoker"</span>}, <span class="hljs-number">160</span>);

        System.out.println(book.toString()); <span class="hljs-comment">// Carmilla by [Sheridan Le Fanu]</span>
        System.out.println(ebook.toString()); <span class="hljs-comment">// Frankenstein by [Mary Shelley]</span>
        System.out.println(audioBook.toString()); <span class="hljs-comment">// Dracula by [Bram Stoker]</span>
    }
}
</code></pre>
<p>So far everything is working fine. But do you remember the <code>length()</code> method you wrote inside the <code>Book</code> class? It'll work for the regular books but will break in the e-books.</p>
<p>That's because the page count property is marked as <code>private</code> and no other class except <code>Book</code> will be able to access it. The title is also a <code>private</code> property.</p>
<p>Open the <code>Book.java</code> file and mark the <code>title</code> and <code>pageCount</code> properties as protected.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span> </span>{
    <span class="hljs-keyword">protected</span> String title;
    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">int</span> pageCount;
    <span class="hljs-keyword">private</span> ArrayList&lt;String&gt; authors = <span class="hljs-keyword">new</span> ArrayList&lt;String&gt;();

    Book(String title, <span class="hljs-keyword">int</span> pageCount, String[] authors) {
        <span class="hljs-keyword">this</span>.title = title;
        <span class="hljs-keyword">this</span>.pageCount = pageCount;
        <span class="hljs-keyword">this</span>.authors = <span class="hljs-keyword">new</span> ArrayList&lt;String&gt;(Arrays.asList(authors));
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">length</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> String.format(<span class="hljs-string">"%s is %d pages long."</span>, <span class="hljs-keyword">this</span>.title, <span class="hljs-keyword">this</span>.pageCount);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> String.format(<span class="hljs-string">"%s by %s"</span>, <span class="hljs-keyword">this</span>.title, <span class="hljs-keyword">this</span>.authors.toString());
    }
}
</code></pre>
<p>This'll make them accessible from the subclasses. The audio books have another problem with the <code>length()</code> method.</p>
<p>Audio books don't have a page count. They have run times and this difference will break the length method.</p>
<p>One way to solve this problem is by overriding the <code>length()</code> method.</p>
<h2 id="heading-how-to-override-a-method-in-java">How to Override a Method in Java</h2>
<p>As the name suggests, overriding means cancelling the effect of a method by replacing it with something else.</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">AudioBook</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Book</span></span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> runTime;

    AudioBook(String title, String[] authors, <span class="hljs-keyword">int</span> runTime) {
        <span class="hljs-keyword">super</span>(title, <span class="hljs-number">0</span>, authors);

        <span class="hljs-keyword">this</span>.runTime = runTime;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">length</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> String.format(<span class="hljs-string">"%s is %d minutes long."</span>, <span class="hljs-keyword">this</span>.title, <span class="hljs-keyword">this</span>.runTime);
    }
}
</code></pre>
<p>You override a method from the parent class by rewriting the method in the subclass. The <code>@Override</code> keyword is an annotation. Annotations in Java are metadata.</p>
<p>It's not mandatory to annotate the method like this. But if you do, the compiler will know that the annotated method overrides a parent method and will make sure you're following all the rules of overriding.</p>
<p>For example, if you make a mistake in the method name and it doesn't match any method from the parent, the compiler will let you know that the method is not overriding anything.</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">Main</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>{
        AudioBook audioBook = <span class="hljs-keyword">new</span> AudioBook(<span class="hljs-string">"Dracula"</span>, <span class="hljs-keyword">new</span> String[]{<span class="hljs-string">"Bram Stoker"</span>}, <span class="hljs-number">160</span>);

        System.out.println(audioBook.length()); <span class="hljs-comment">// Dracula is 160 minutes long.</span>
    }
}
</code></pre>
<p>Cool, isn't it? Whenever overriding a method in Java, keep in mind that both the original and overridden method must have the same return type, same name, and same parameters.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I would like to thank you from the bottom of my heart for the time you've spent on reading this book. I hope you've enjoyed your time and have learned all the fundamental concepts of Java.</p>
<p>This handbook is not frozen in time. I'll keep working on it and I'll update it with improvements, new content, and more. You can provide anonymous opinions and suggestion on the handbook <a target="_blank" href="https://forms.gle/RYPzQybBEYNc5q9g9">in this form</a>.</p>
<p>Apart from this one, I've written full-length handbooks on other complicated topics available for free on <a target="_blank" href="https://www.freecodecamp.org/news/author/farhanhasin/">freeCodeCamp</a>.</p>
<p>These handbooks are part of my mission to simplify hard to understand technologies for everyone. Each of these handbooks takes a lot of time and effort to write.</p>
<p>If you've enjoyed my writing and want to keep me motivated, consider leaving starts on <a target="_blank" href="https://github.com/fhsinchy/">GitHub</a> and endorse me for relevant skills on <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>.</p>
<p>I'm always open to suggestions and discussions on <a target="_blank" href="https://twitter.com/frhnhsin">Twitter</a> or <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>. Hit me up with direct messages.</p>
<p>In the end, consider sharing the resources with others, because:</p>
<blockquote>
<p>In open source, we feel strongly that to really do something well, you have to get a lot of people involved. — Linus Torvalds</p>
</blockquote>
<p>Till the next one, stay safe and keep learning.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Java scanner.nextLine() Method Call Gets Skipped Error [SOLVED] ]]>
                </title>
                <description>
                    <![CDATA[ There's a common error that tends to stump new Java programmers. It happens when you group together a bunch of input prompts and one of the scanner.nextLine() method calls gets skipped – without any signs of failure or error. Take a look at the follo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/java-scanner-nextline-call-gets-skipped-solved/</link>
                <guid isPermaLink="false">66b0ab405e73cf343a5cc05a</guid>
                
                    <category>
                        <![CDATA[ error ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Fri, 26 Aug 2022 21:01:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/08/java-scanner-nextline-call-gets-skipped-solved.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>There's a common error that tends to stump new Java programmers. It happens when you group together a bunch of input prompts and one of the <code>scanner.nextLine()</code> method calls gets skipped – without any signs of failure or error.</p>
<p>Take a look at the following code snippet, for example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Scanner;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        Scanner scanner = <span class="hljs-keyword">new</span> Scanner(System.in);

        System.out.print(<span class="hljs-string">"What's your name? "</span>);
        String name = scanner.nextLine();

        System.out.printf(<span class="hljs-string">"So %s. How old are you? "</span>, name);
        <span class="hljs-keyword">int</span> age = scanner.nextInt();

        System.out.printf(<span class="hljs-string">"Cool! %d is a good age to start programming. \nWhat language would you prefer? "</span>, age);
        String language = scanner.nextLine();

        System.out.printf(<span class="hljs-string">"Ah! %s is a solid programming language."</span>, language);

        scanner.close();

    }

}
</code></pre>
<p>The first <code>scanner.nextLine()</code> call prompts the user for their name. Then the <code>scanner.nextInt()</code> call prompts the user for their age. The last <code>scanner.nextLine()</code> call prompts the user for their preferred programming language. Finally, you close the scanner object and call it a day.</p>
<p>It's very basic Java code involving a <code>scanner</code> object to take input from the user, right? Let's try to run the program and see what happens.</p>
<p>If you did run the program, you may have noticed that the program asks for the name, then the age, and then skips the last prompt for the preferred programming language and abruptly ends. That's what we're going to solve today.</p>
<h2 id="heading-why-does-the-scannernextline-call-get-skipped-after-the-scannernextint-call">Why Does the <code>scanner.nextLine()</code> Call Get Skipped After the <code>scanner.nextInt()</code> Call?</h2>
<p>This behavior is not exclusive to just the <code>scanner.nextInt()</code> method. If you call the <code>scanner.nextLine()</code> method after any of the other <code>scanner.nextWhatever()</code> methods, the program will skip that call.</p>
<p>Well, this has to do with how the two methods work. The first <code>scanner.nextLine()</code> prompts the user for their name.</p>
<p>When the user inputs the name and presses enter, <code>scanner.nextLine()</code> consumes the name and the enter or the newline character at the end. </p>
<p>Which means the input buffer is now empty. Then the <code>scanner.nextInt()</code> prompts the user for their age. The user inputs the age and presses enter.</p>
<p>Unlike the <code>scanner.nextLine()</code> method, the <code>scanner.nextInt()</code> method only consumes the integer part and leaves the enter or newline character in the input buffer.</p>
<p>When the third <code>scanner.nextLine()</code> is called, it finds the enter or newline character still existing in the input buffer, mistakes it as the input from the user, and returns immediately.</p>
<p>As you can see, like many real life problems, this is caused by misunderstanding between the user and the programmer.</p>
<p>There are two ways to solve this problem. You can either consume the newline character after the <code>scanner.nextInt()</code> call takes place, or you can take all the inputs as strings and parse them to the correct data type later on.</p>
<h2 id="heading-how-to-clear-the-input-buffer-after-the-scannernextint-call-takes-place">How to Clear the Input Buffer After the <code>scanner.nextInt()</code> Call Takes Place</h2>
<p>It's easier than you think. All you have to do is put an additional <code>scanner.nextLine()</code> call after the <code>scanner.nextInt()</code> call takes place.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Scanner;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        Scanner scanner = <span class="hljs-keyword">new</span> Scanner(System.in);

        System.out.print(<span class="hljs-string">"What's your name? "</span>);
        String name = scanner.nextLine();

        System.out.printf(<span class="hljs-string">"So %s. How old are you? "</span>, name);
        <span class="hljs-keyword">int</span> age = scanner.nextInt();

        <span class="hljs-comment">// consumes the dangling newline character</span>
        scanner.nextLine();

        System.out.printf(<span class="hljs-string">"Cool! %d is a good age to start programming. \nWhat language would you prefer? "</span>, age);
        String language = scanner.nextLine();

        System.out.printf(<span class="hljs-string">"Ah! %s is a solid programming language."</span>, language);

        scanner.close();

    }

}
</code></pre>
<p>Although this solution works, you'll have to add additional <code>scanner.nextLine()</code> calls whenever you call any of the other methods. It's fine for smaller programs but in larger ones, this can get very ugly very quick.</p>
<h2 id="heading-how-to-parse-inputs-taken-using-the-scannernextline-method">How to Parse Inputs Taken Using the <code>scanner.nextLine()</code> Method</h2>
<p>All the wrapper classes in Java contain methods for parsing string values. For example, the <code>Integer.parseInt()</code> method can parse an integer value from a given string.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Scanner;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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>{
        Scanner scanner = <span class="hljs-keyword">new</span> Scanner(System.in);

        System.out.print(<span class="hljs-string">"What's your name? "</span>);
        String name = scanner.nextLine();

        System.out.printf(<span class="hljs-string">"So %s. How old are you? "</span>, name);
        <span class="hljs-comment">// parse the integer from the string</span>
        <span class="hljs-keyword">int</span> age = Integer.parseInt(scanner.nextLine());

        System.out.printf(<span class="hljs-string">"Cool! %d is a good age to start programming. \nWhat language would you prefer? "</span>, age);
        String language = scanner.nextLine();

        System.out.printf(<span class="hljs-string">"Ah! %s is a solid programming language."</span>, language);

        scanner.close();

    }

}
</code></pre>
<p>This is a cleaner way of mixing multiple types of input prompts in Java. As long as you're being careful about what the user is putting in, the parsing should be alright.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>I'd like to thank you from the bottom of my heart for taking interest in my writing. I hope it has helped you in one way or another. </p>
<p>If it did, feel free to share with your connections. If you want to get in touch, I'm available on <a target="_blank" href="https://twitter.com/frhnhsin">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Arrays.binarySearch() in Java ]]>
                </title>
                <description>
                    <![CDATA[ In this article, I'm going to show you how to use the Arrays.binarySearch() method in Java. What is Arrays.binarySearch() in Java?  According to the official docs on the Arrays.binarySearch() method: (It) Searches the specified array of bytes for th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-arrays-binarysearch-in-java/</link>
                <guid isPermaLink="false">66b0ab3e6a48f420e310e616</guid>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Tue, 23 Aug 2022 15:31:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/10/binarysearch-arrays-java.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, I'm going to show you how to use the <code>Arrays.binarySearch()</code> method in Java.</p>
<h2 id="heading-what-is-arraysbinarysearch-in-java">What is <code>Arrays.binarySearch()</code> in Java?</h2>
<p> According to the <a target="_blank" href="https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(byte[],%20byte)">official docs</a> on the <code>Arrays.binarySearch()</code> method:</p>
<blockquote>
<p>(It) Searches the specified array of bytes for the specified value using the binary search algorithm.   </p>
<p>The array must be sorted (as by the <a target="_blank" href="https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort(byte[])"><code>sort(byte[])</code></a> method) prior to making this call. If it is not sorted, the results are undefined.   </p>
<p>If the array contains multiple elements with the specified value, there is no guarantee which one will be found.</p>
</blockquote>
<p>Simply put, the <code>Arrays.binarySearch()</code> method can look for a given element in a sorted array and return its index if found.</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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">char</span> vowels[] = {<span class="hljs-string">'a'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'u'</span>};

        <span class="hljs-keyword">char</span> key = <span class="hljs-string">'i'</span>;

        <span class="hljs-keyword">int</span> foundItemIndex = Arrays.binarySearch(vowels, key);

        System.out.println(<span class="hljs-string">"The given vowel is at index: "</span> + foundItemIndex);

    }
}
</code></pre>
<p>The <code>Arrays.binarySearch()</code> method takes the array you want to search as the first argument and the key you're looking for as the second argument. The output from this program will be:</p>
<pre><code>The given vowel is at index: <span class="hljs-number">2</span>
</code></pre><p>Remember, the method returns the index of the found item and not the item itself. So you can store the index in an integer like the one used in this example.</p>
<p>By default, the method uses the first index of the array as the starting point for the search and the length of the array as the ending point of the search. So in this case, the starting index is <code>0</code> and the ending index is <code>6</code>.</p>
<p>Instead of using the default starting and ending indices, you can define them yourself. For example, if you want to perform the search from index <code>2</code> to index <code>4</code>, you can do so as follows:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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">char</span> vowels[] = {<span class="hljs-string">'a'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'u'</span>};

        <span class="hljs-keyword">char</span> key = <span class="hljs-string">'i'</span>;
        <span class="hljs-keyword">int</span> startIndex = <span class="hljs-number">2</span>;
        <span class="hljs-keyword">int</span> endIndex = <span class="hljs-number">4</span>;

        <span class="hljs-keyword">int</span> foundItemIndex = Arrays.binarySearch(vowels, startIndex, endIndex, key);

        System.out.println(<span class="hljs-string">"The given vowel is at index: "</span> + foundItemIndex);

    }
}
</code></pre>
<p>In this case, the <code>Arrays.binarySearch()</code> method takes the array you want to search as the first argument, the starting index as the second argument, the ending index as the third argument, and the key as the fourth argument.</p>
<p>As long as you keep the ending index within the length of the array, the method should work fine. If you exceed that, however, you'll get the <code>Array index out of range</code> exception.</p>
<p>This is simple right? The method returns the index of the element if found. But what happens if it doesn't find the given element?</p>
<h2 id="heading-what-happens-when-arraysbinarysearch-doesnt-find-the-given-element">What Happens When <code>Arrays.binarySearch()</code> Doesn't Find the Given Element?</h2>
<p>Once again according to the <a target="_blank" href="https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(byte[],%20byte)">official docs</a> on the <code>Arrays.binarySearch()</code> method:</p>
<blockquote>
<p>(The method returns the) index of the search key, if it is contained in the array within the specified range; otherwise, <code>(-(_insertion point_) - 1)</code>.   </p>
<p>The <em>insertion point</em> is defined as the point at which the key would be inserted into the array: the index of the first element in the range greater than the key, or <code>toIndex</code> (ending index) if all elements in the range are less than the specified key.   </p>
<p>Note that this guarantees that the return value will be &gt;= 0 if and only if the key is found.</p>
</blockquote>
<p>Not very clear right? Let me explain. The first line states that the method will return the index of the search key if found in the array.</p>
<p>But if not found, the output will be equal to the value of <code>(-(_insertion point_) - 1)</code>. Here, based on the search key, the <code>insertion point</code> can have different values.</p>
<p>Assume we have an array <code>[5, 6, 7, 8, 9, 10]</code> and a search key <code>0</code> which is clearly not in the array. In this case, the search key is smaller than all the elements of the array. But the first element that is larger than the search key is <code>5</code>. So in this case the <code>insertion point</code> will be:</p>
<pre><code>(-(the index <span class="hljs-keyword">of</span> the first element larger than the search key) - <span class="hljs-number">1</span>) = (<span class="hljs-number">0</span> - <span class="hljs-number">1</span>) = <span class="hljs-number">-1</span>
</code></pre><p>You can implement this into a code snippet as follows:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> arrays;

<span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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> numbers[] = {<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>};

        System.out.println(Arrays.binarySearch(numbers, <span class="hljs-number">0</span>)); <span class="hljs-comment">// -1</span>
    }
}
</code></pre>
<p>Again assume we have an array <code>[5, 6, 7, 8, 9, 10]</code> and a search key <code>12</code> which is clearly not in the array. In this case, the search key is larger than all the elements of the array. So in this case the <code>insertion point</code> will be:</p>
<pre><code>(-(the ending index (-(<span class="hljs-number">6</span>) - <span class="hljs-number">1</span>) = (<span class="hljs-number">-6</span> - <span class="hljs-number">1</span>) = <span class="hljs-number">-7</span>
</code></pre><p>Remember, when you don't define an ending index manually, the method uses the length of the array as the ending index which in this case is <code>6</code>.</p>
<p>You can implement this into a code snippet as follows:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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> numbers[] = {<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>};

        System.out.println(Arrays.binarySearch(numbers, <span class="hljs-number">12</span>)); <span class="hljs-comment">// -7</span>
    }
}
</code></pre>
<p>However, the results will change if you define the starting and ending indices manually as follows:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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> numbers[] = {<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>};

        <span class="hljs-keyword">int</span> startIndex = <span class="hljs-number">1</span>;
        <span class="hljs-keyword">int</span> endIndex = <span class="hljs-number">3</span>;

        System.out.println(Arrays.binarySearch(numbers, startIndex, endIndex, <span class="hljs-number">5</span>)); <span class="hljs-comment">// -2</span>
        System.out.println(Arrays.binarySearch(numbers, startIndex, endIndex, <span class="hljs-number">10</span>)); <span class="hljs-comment">// -4</span>

    }
}
</code></pre>
<p>Try calculating the values by yourself. You can also use the <code>Arrays.binarySearch()</code> method with characters like this:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</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">char</span> vowels[] = {<span class="hljs-string">'a'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'u'</span>};

        <span class="hljs-keyword">char</span> key = <span class="hljs-string">'i'</span>;
        <span class="hljs-keyword">int</span> startIndex = <span class="hljs-number">2</span>;
        <span class="hljs-keyword">int</span> endIndex = <span class="hljs-number">4</span>;

        System.out.println(Arrays.binarySearch(vowels, startIndex, endIndex, key));

    }
}
</code></pre>
<p>The same principles apply in this case when the given search key is not found. But when comparing between a character in the array and a given search key, the <a target="_blank" href="https://www.ascii-code.com/">ASCII code</a> of the corresponding character will be used. So <code>A (65)</code> will be smaller than <code>a (97)</code>. Keep this in mind when cross checking outputs from your program.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>That was pretty much it for this one. I hope you now understand how to use the <code>Arrays.binarySearch()</code> method. </p>
<p>If you have any questions or just want to communicate with me, I'm on <a target="_blank" href="https://twitter.com/frhnhsin">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>. Hit me up with direct messages.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Programming Naming Conventions – Camel, Snake, Kebab, and Pascal Case Explained ]]>
                </title>
                <description>
                    <![CDATA[ If you've been programming for a while, you may have heard the words "camel case" or "pascal case". And maybe you're wondering what those terms mean. Well, let me explain. What are Naming Conventions in Programming? Apart from the hard and fast rules... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/programming-naming-conventions-explained/</link>
                <guid isPermaLink="false">66b0ab435e73cf343a5cc05d</guid>
                
                    <category>
                        <![CDATA[ Naming Conventions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Mon, 22 Aug 2022 15:16:55 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/08/Programming-Naming-Conventions-Explained.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you've been programming for a while, you may have heard the words "camel case" or "pascal case". And maybe you're wondering what those terms mean. Well, let me explain.</p>
<h2 id="heading-what-are-naming-conventions-in-programming">What are Naming Conventions in Programming?</h2>
<p>Apart from the hard and fast rules that we get with every programming language, there are also conventions. These are sets of standards that are generally accepted by the majority of developers out there.</p>
<p>Among all sorts of conventions, naming conventions are some of the most common. Because as programmers, we name a lot of things. Such as variables, functions, classes, methods, interfaces and so on.</p>
<p>Throughout the years, developers have used different case types to name different entities in their code. And four of them have proved to be the most popular ones. They are:</p>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-camel-case">Camel Case</a></li>
<li><a class="post-section-overview" href="#heading-what-is-snake-case">Snake Case</a></li>
<li><a class="post-section-overview" href="#heading-what-is-kebab-case">Kebab Case</a></li>
<li><a class="post-section-overview" href="#heading-what-is-pascal-case">Pascal Case</a></li>
</ul>
<p>Let's have a look at some examples so you can see how these work, shall we?</p>
<h2 id="heading-what-is-camel-case">What is Camel Case?</h2>
<p>In camel case, you start a name with a small letter. If the name has multiple words, the later words will start with a capital letter: </p>
<p>Here are some examples of camel case: <code>firstName</code> and <code>lastName</code>.</p>
<h2 id="heading-what-is-snake-case">What is Snake Case?</h2>
<p>Like in camel case, you start the name with a small letter in snake case. If the name has multiple words, the later words will start with small letters and you use a underscore (_) to separate the words. </p>
<p>Here are some examples of snake case: <code>first_name</code> and <code>last_name</code>.</p>
<h2 id="heading-what-is-kebab-case">What is Kebab Case?</h2>
<p>Kebab case is similar to snake case, but you use a hyphen (-) instead of an underscore (_) to separate the words.</p>
<p>Here are some examples of kebab case: <code>first-name</code> and <code>last-name</code>.</p>
<h2 id="heading-what-is-pascal-case">What is Pascal Case?</h2>
<p>Unlike the previous examples, names in pascal case start with a capital letter. In case of the names with multiple words, all words will start with capital letters.</p>
<p>Here are some examples of pascal case: <code>FirstName</code> and <code>LastName</code>.</p>
<h2 id="heading-when-to-use-each-naming-convention">When to Use Each Naming Convention</h2>
<p>Now, based on the language you're working on and what you're naming, the preferred case type can change. </p>
<p>For example, according to the <a target="_blank" href="https://peps.python.org/pep-0008/">PEP 8 – Style Guide for Python Code</a>, variable and function names should use snake case:</p>
<pre><code class="lang-python">user_name = <span class="hljs-string">'Farhan'</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">reverse_name</span>(<span class="hljs-params">name</span>):</span>
    <span class="hljs-keyword">return</span> name[::<span class="hljs-number">-1</span>]
</code></pre>
<p>Let's take a look at JavaScript now. According to the <a target="_blank" href="https://github.com/airbnb/javascript">Airbnb JavaScript Style Guide</a>, variable and function names should use camel case:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> userName = <span class="hljs-string">"Farhan"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reverseName</span>(<span class="hljs-params">name</span>) </span>{
     <span class="hljs-keyword">return</span> name.split(<span class="hljs-string">""</span>).reverse().join(<span class="hljs-string">""</span>);
}
</code></pre>
<p>Although Python and JavaScript require you to follow different conventions when you're naming variables and functions, both languages require you to use pascal case when naming a class.</p>
<p>Style guides are available for more or less all popular programming languages. Here are some of the most commonly used:</p>
<ul>
<li>Python - <a target="_blank" href="https://peps.python.org/pep-0008/">PEP 8 – Style Guide for Python Code</a></li>
<li>JavaScript - <a target="_blank" href="https://github.com/airbnb/javascript">Airbnb JavaScript Style Guide</a></li>
<li>Java - <a target="_blank" href="https://www.cs.cornell.edu/courses/JavaAndDS/JavaStyle.html">Java style guide</a></li>
<li>C# - <a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions">C# Coding Convention</a></li>
<li>Go - <a target="_blank" href="https://github.com/uber-go/guide/blob/master/style.md">Uber Go Style Guide</a></li>
<li>C++ - <a target="_blank" href="https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines">C++ Core Guidelines</a></li>
<li>PHP - <a target="_blank" href="https://www.php-fig.org/psr/psr-12/">PSR-12: Extended Coding Style</a></li>
</ul>
<p>These are some of the guides I've referred to in the past. There are other guides as well. Feel free to do your own research and pick the one you like. Just make sure the guide you're following is actually well regarded by the developer community.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>These are the most popular naming conventions that you should be aware of. If you'd like to learn more about the different naming conventions, you can read through the style guide for the language you're using.</p>
<p>Knowing the conventions of the language you're learning is important. While not following conventions will not break your code, it'll make it less consistent and harder to work with.</p>
<p>Following these simple conventions, on the other hand, will make your code a lot more readable and easier to work with. So do yourself and others a favor and follow the conventions.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python Print Without Newline [SOLVED] ]]>
                </title>
                <description>
                    <![CDATA[ If you're familiar with Python, you may have noticed that the built-in function print() doesn't need an explicit \n character at the end of each line.  This means that the output from the following snippet of code print('freeCodeCamp Curriculum') pri... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-print-without-newline-solved/</link>
                <guid isPermaLink="false">66b0ab4a6a48f420e310e618</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Tue, 10 May 2022 16:18:38 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/05/Python-Print-Without-Newline--SOLVED-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're familiar with Python, you may have noticed that the built-in function <code>print()</code> doesn't need an explicit <code>\n</code> character at the end of each line. </p>
<p>This means that the output from the following snippet of code</p>
<pre><code class="lang-python">print(<span class="hljs-string">'freeCodeCamp Curriculum'</span>)
print(<span class="hljs-string">'freeCodeCamp News'</span>)
print(<span class="hljs-string">'freeCodeCamp YouTube Channel'</span>)
</code></pre>
<p>will be:</p>
<pre><code class="lang-shell">freeCodeCamp Curriculum
freeCodeCamp News
freeCodeCamp YouTube Channel
</code></pre>
<p>This happens because the <code>print()</code> function adds the <code>\n</code> character to the end of each printed line. Although most of the time this is a convenience, you may sometimes want to print out lines without the <code>\n</code> character.</p>
<p>In this article, you'll learn how to change the end of each print statement. And you'll also learn a number of other ways to modify how the built-in function behaves by default.</p>
<h2 id="heading-how-to-print-without-a-newline-in-python">How to Print Without a Newline in Python</h2>
<p>According to the <a target="_blank" href="https://docs.python.org/3/library/functions.html#print">official documentation</a> for the <code>print()</code> function, the function signature is as follows:</p>
<pre><code>print(*objects, sep=<span class="hljs-string">' '</span>, end=<span class="hljs-string">'\n'</span>, file=sys.stdout, flush=False)
</code></pre><p>As you can see the function takes five arguments in total. The first one is the object(s) that you want to print on the terminal. Then there is the separator (which you'll learn about in a later section), and the <code>end</code> parameter.</p>
<p>The default value of the <code>end</code> parameter is <code>\n</code>, which means a newline character will be appended to each line printed on the terminal. </p>
<p>To change this behavior, you can simply override this parameter as follows:</p>
<pre><code class="lang-python">print(<span class="hljs-string">'freeCodeCamp Curriculum'</span>, end=<span class="hljs-string">', '</span>)
print(<span class="hljs-string">'freeCodeCamp News'</span>, end=<span class="hljs-string">', '</span>)
print(<span class="hljs-string">'freeCodeCamp YouTube Channel'</span>)
</code></pre>
<p>Since, I've changed the value of <code>end</code> to a comma, the output will be <code>freeCodeCamp Curriculum, freeCodeCamp News, freeCodeCamp YouTube Channel</code> instead of the three separate lines. </p>
<p>You can use any character as the value of <code>end</code>. If you'd want nothing at the end of lines, simply use an empty string.</p>
<h2 id="heading-how-to-print-with-a-separator-in-python">How to Print With a Separator in Python</h2>
<p>Remember the <code>sep</code> argument in the function signature? In this section, you'll learn about its usage. </p>
<p>You may or may not know already that the <code>print()</code> function can take multiple objects at once to print out as follows:</p>
<pre><code class="lang-python">print(<span class="hljs-string">'freeCodeCamp Curriculum'</span>, <span class="hljs-string">'freeCodeCamp News'</span>, <span class="hljs-string">'freeCodeCamp YouTube Channel'</span>)
</code></pre>
<p>The output from this code will be:</p>
<pre><code class="lang-shell">freeCodeCamp Curriculum, freeCodeCamp News, freeCodeCamp YouTube Channel
</code></pre>
<p>As you can see, the function has printed the three strings in a single line separated by commas. If you want to use something else like a dash as a separator, you can do so as follows:</p>
<pre><code class="lang-python">print(<span class="hljs-string">'freeCodeCamp Curriculum'</span>, <span class="hljs-string">'freeCodeCamp News'</span>, <span class="hljs-string">'freeCodeCamp YouTube Channel'</span>, sep=<span class="hljs-string">' - '</span>)
</code></pre>
<p>The output from this code will be:</p>
<pre><code class="lang-shell">freeCodeCamp Curriculum - freeCodeCamp News - freeCodeCamp YouTube Channel
</code></pre>
<p>I hope you've got the idea. Like the <code>end</code> argument, you can use more or less any valid string as the value of the <code>sep</code> argument.</p>
<h2 id="heading-how-to-print-to-a-file-in-python">How to Print to a File in Python</h2>
<p>Instead of printing things to the terminal, you can also use the <code>print()</code> function to print stuff directly to a file. </p>
<p>The <code>print()</code> function takes another argument <code>file</code> which defaults to <code>sys.stdout</code> or the standard output. It's the default file descriptor where a process can write output.</p>
<p>You can override this to write to a file instead as follows:</p>
<pre><code class="lang-python"><span class="hljs-keyword">with</span> open(<span class="hljs-string">'output.txt'</span>, <span class="hljs-string">'w'</span>) <span class="hljs-keyword">as</span> f:
    print(<span class="hljs-string">'freeCodeCamp'</span>, file=f)
</code></pre>
<p>First, you open a file called <code>output.txt</code> as <code>f</code> and pass that as the value of the <code>file</code> argument. If you run the code a new file will be created and inside that file will be your output.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The <code>print()</code> function is one of the most commonly used functions in Python. So having a good understanding of the different usages of this built-in function can increase your productivity. </p>
<p>There is also another argument, <code>flush</code>, in the function. It's a boolean and setting it to <code>True</code> will flush the output on every execution.</p>
<p>I also have a personal blog where I write about random tech stuff, so if you're interested in something like that, checkout <a target="_blank" href="https://farhan.dev">https://farhan.dev</a>. If you have any questions or are confused about anything – or just want to get in touch – I'm available on <a target="_blank" href="https://twitter.com/frhnhsin">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Python Code Example Handbook – Simple Python Program Examples for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Python is a high-level, general purpose, interpreted programming language. It's well-known for being very easy to learn yet powerful, and it has many uses in many different fields. If you're someone trying to get started with Python, it's easy to get... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-code-examples-simple-python-program-example/</link>
                <guid isPermaLink="false">66b0ab45d28cb2f6cba9413e</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Wed, 04 May 2022 17:20:38 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/Python-Code-Examples-Handbook-Mockup.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Python is a high-level, general purpose, interpreted programming language. It's well-known for being very easy to learn yet powerful, and it has many uses in many different fields.</p>
<p>If you're someone trying to get started with Python, it's easy to get lost among all the excellent learning resources on the internet. </p>
<p>Now this article isn't trying to be another head in that crowd. Rather, here I'll introduce you to Python basics and I'll point you in the right direction.</p>
<p>In this article, I'll introduce to the fundamentals of the Python programming language with the help of a ton of code examples. I'll explain them in great detail and include links for further study. </p>
<p>Once I've introduced you to the language at a basic level, I'll suggest you some excellent learning resources and explain how to make the best of them.</p>
<p>While I'll explain the code examples thoroughly, I'm assuming that you're familiar with common programming concepts such as expressions, statements, variables, functions, and so on. So I'll not spend time explaining these programming concepts in detail – rather I'll focus on Python's way of implementing/using them.</p>
<p>Without any further ado, let's jump in!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-high-level-overview-of-python">High Level Overview of Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-hello-world-in-python">How to Write Hello, World! in Python</a></li>
<li><a class="post-section-overview" href="#heading-variables-in-python">Variables in Python</a></li>
<li><a class="post-section-overview" href="#heading-data-types-in-python">Data Types in Python</a></li>
<li><a class="post-section-overview" href="#how-to-write-comments-in-python">How to Write Comments in Python</a></li>
<li><a class="post-section-overview" href="#heading-strings-in-python">Strings in Python</a></li>
<li><a class="post-section-overview" href="#heading-numbers-in-python">Numbers in Python</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-user-input-in-python">How to Handle User Input in Python</a></li>
<li><a class="post-section-overview" href="#if-else-elif-in-python">if-else-elif in Python</a></li>
<li><a class="post-section-overview" href="#heading-match-case-in-python">match-case in Python</a></li>
<li><a class="post-section-overview" href="#heading-lists-and-tuples-in-python">Lists and Tuples in Python</a></li>
<li><a class="post-section-overview" href="#heading-loops-in-python">Loops in Python</a></li>
<li><a class="post-section-overview" href="#heading-dictionaries-in-python">Dictionaries in Python</a></li>
<li><a class="post-section-overview" href="#heading-functions-in-python">Functions in Python</a></li>
<li><a class="post-section-overview" href="#heading-additional-python-learning-resources">Additional Python Learning Resources</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-high-level-overview-of-python">High Level Overview of Python</h2>
<p>Before I jump into coding, you'll need to have Python installed and ready to go on your system. Depending on the system you're running – Windows, macOS or Linux – the installation process will differ.</p>
<p>If you're on Windows, my fellow freeCodeCamp author <a target="_blank" href="https://www.freecodecamp.org/news/author/fahimbinamin/">Md. Fahim Bin Amin</a> has written an excellent guide on <a target="_blank" href="https://www.freecodecamp.org/news/how-to-install-python-in-windows-operating-system/">How to Install Python on Windows</a>. Another author <a target="_blank" href="https://www.freecodecamp.org/news/author/dillionmegida/">Dillion Megida</a> has written another excellent article on <a target="_blank" href="https://www.freecodecamp.org/news/how-to-install-python-3-on-mac-and-update-the-python-version-macos-homebrew-command-guide/">How to Install Python 3 on Mac</a>.</p>
<p>Some platforms, such as some of the modern Linux distributions, come with a fairly up-to-date version of Python pre-installed. So if you're on Linux, execute the following command to check your version of Python:</p>
<pre><code class="lang-shell">python3 --version
</code></pre>
<p>Having any version of Python 3 installed on your system will suffice. Apart from Python, you'll also need a code editor or IDE well suited for writing Python code.</p>
<p>In my <a target="_blank" href="https://www.freecodecamp.org/news/python-ide-best-ides-and-editors-for-python/">Python IDE – Best IDEs and Editors for Python</a> article I've listed three of the best code editors and IDEs that you may use for writing Python code.</p>
<p>So if you have Python and a code editor or IDE ready to go, let's move on to writing your first piece of Python code.</p>
<h3 id="heading-how-to-write-hello-world-in-python">How to Write Hello, World! in Python</h3>
<p>Somewhere in your computer, create a new file named <code>program.py</code> and put the following code in it:</p>
<pre><code class="lang-python">print(<span class="hljs-string">'Hello, World!'</span>)
</code></pre>
<p>To run this code, open your terminal inside the directory where you've put the <code>program.py</code> file and execute the following command:</p>
<pre><code class="lang-shell"># on Windows and macOS
python program.py

# on Linux
python3 program.py
</code></pre>
<p>The output of the code will be whatever you've passed as the parameter of the <code>print()</code> function, which in the case of this code snippet is:</p>
<pre><code class="lang-shell">Hello, World!
</code></pre>
<p>As you may have already guessed, <code>print()</code> is a built-in Python function that prints whatever you give it on the console. The function can print strings, numbers, expressions – more or less anything that you can throw at it.</p>
<pre><code class="lang-python">print(<span class="hljs-string">'Hello, World!'</span>)
print(<span class="hljs-number">100</span>)
print(<span class="hljs-number">5</span> + <span class="hljs-number">5</span>)
</code></pre>
<p>The first statement prints out the string <code>Hello, World!</code> just like before. The second one prints out a number and the third one prints out the result of the <code>5 + 5</code> expression:</p>
<pre><code class="lang-shell">Hello, World!
100
10
</code></pre>
<p>One thing that you may or may not have noticed is that the three print statements have been outputted in three separate lines. Whereas in other languages such as C/C++/C#/Java you have to append a newline character explicitly.</p>
<p>As it turns out, <code>print()</code> functions as newline character by default and you can override this default behavior as follows:</p>
<pre><code class="lang-python">print(<span class="hljs-string">'Hello, World!'</span>, end=<span class="hljs-string">' | '</span>)
print(<span class="hljs-number">100</span>, end=<span class="hljs-string">' | '</span>)
print(<span class="hljs-number">5</span> + <span class="hljs-number">5</span>)
</code></pre>
<p>Now the output of the program will be:</p>
<pre><code class="lang-shell">Hello, World! | 100 | 10
</code></pre>
<p>Which means any string you pass as the value of the <code>end</code> parameter will be used as the terminating character of the printed line. </p>
<p>Here, I've used <code>|</code> as the terminating character of the first two statements. However, I've used the default newline character as the terminating character of the last statement.</p>
<p>You can learn more about the <code>print()</code> function by playing around with it or by reading the <a target="_blank" href="https://docs.python.org/3/library/functions.html#print">official docs</a> on the function.</p>
<h3 id="heading-variables-in-python">Variables in Python</h3>
<p>To declare a variable in Python, you start by writing out the name of the variable, then an equals sign, followed by the value of the variable:</p>
<pre><code class="lang-python">name = <span class="hljs-string">'Farhan'</span>

print(<span class="hljs-string">'My name is '</span> + name)
</code></pre>
<p>Output of this code will be:</p>
<pre><code class="lang-shell">My name is Farhan
</code></pre>
<p>As you can see, there is no special keyword for declaring a variable. Python is smart enough to get the type of the variable from the value you're assigning. </p>
<p>In the example above, the <code>name</code> variable contains the <code>Farhan</code> string. Since the word <code>Farhan</code> is within quotes, Python will treat this variable as a string.</p>
<p>In Python, you can concatenate two strings using the plus sign. That's what we've done in the <code>print()</code> statement above. But if you change the code as follows:</p>
<pre><code class="lang-python">name = <span class="hljs-string">'Farhan'</span>
age = <span class="hljs-number">27</span>

print(<span class="hljs-string">'My name is '</span> + name)
print(<span class="hljs-string">'I am '</span> + age + <span class="hljs-string">'years old'</span>)
</code></pre>
<p>And try to run this program, you'll face the following problem:</p>
<pre><code class="lang-shell">My name is Farhan
Traceback (most recent call last):
  File "C:\Users\shovi\repos\python-playground\hello-world.py", line 5, in &lt;module&gt;
    print('I am ' + age + 'years old')
TypeError: can only concatenate str (not "int") to str
</code></pre>
<p>As you can see, strings can be concatenated with strings only, and the <code>age</code> variable is an integer. There is a better way of embedding variables within string statements.</p>
<pre><code class="lang-python">name = <span class="hljs-string">'Farhan'</span>
age = <span class="hljs-number">27</span>

print(<span class="hljs-string">f'My name is <span class="hljs-subst">{name}</span>'</span>)
print(<span class="hljs-string">f'I am <span class="hljs-subst">{age}</span> years old'</span>)
</code></pre>
<p>I hope you've noticed the <code>f</code> in the beginning of the strings inside the <code>print()</code> statements. This <code>f</code> turns the strings into f-strings. These strings are evaluated at runtime, so inside a f-string, you can put any valid Python statement within curly braces. This makes embedding variables or even simple logic within strings very easy.</p>
<p>You can re-declare your variables anywhere within the program. You can even change their types if you wish to.</p>
<pre><code class="lang-python">a = <span class="hljs-string">'this is a string'</span>

a = <span class="hljs-number">10</span>

print(a)
</code></pre>
<p>This is a completely valid program and the value of <code>a</code> will be printed as <code>10</code> since you've overridden the initial value on the second line.</p>
<h3 id="heading-data-types-in-python">Data Types in Python</h3>
<p>In Python, there four main literal types that you need to be aware of:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Type</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td>Integer</td><td>1</td></tr>
<tr>
<td>Floating Point</td><td>2.0</td></tr>
<tr>
<td>Boolean</td><td>True</td></tr>
<tr>
<td>String</td><td>'freeCodeCamp'</td></tr>
</tbody>
</table>
</div><p>Integers and floating points are self-explanatory. A boolean can be either <code>true</code> or <code>false</code>, and strings in Python can be enclosed within either single quotes or double quotes. I prefer using single quotes. You may use the one you like but try not to mix both types of quotes together.</p>
<h3 id="heading-comments-in-python">Comments in Python</h3>
<p>Comments in Python start with a hash symbol:</p>
<pre><code class="lang-python"><span class="hljs-comment"># this is a comment</span>
</code></pre>
<p>Comments written using a hash can only be single line. If you want to write multi-line comment in Python, you'll have to use quotes as follows:</p>
<pre><code class="lang-python"><span class="hljs-string">'''this is a comment
 that goes on
 and on
 and on...'''</span>
</code></pre>
<p>Commenting your code as needed is a good way of documenting it. But make sure you're not adding comments where the code can be easily understood by just looking at it.</p>
<h3 id="heading-strings-in-python">Strings in Python</h3>
<p>Strings in Python are ordered collections of Unicode characters. Strings can not be modified at runtime. You've already seen how to declare a string. In this section you'll learn about common string operations.</p>
<p>In a string, each character will have an index. And like arrays, string indexes are zero-based.</p>
<pre><code class="lang-python">name = <span class="hljs-string">'Farhan'</span>

<span class="hljs-comment"># F -&gt; 0</span>
<span class="hljs-comment"># a -&gt; 1</span>
<span class="hljs-comment"># r -&gt; 2</span>
<span class="hljs-comment"># h -&gt; 3</span>
<span class="hljs-comment"># a -&gt; 4</span>
<span class="hljs-comment"># n -&gt; 5</span>
</code></pre>
<p>These characters can be accessed using these indexes as follows:</p>
<pre><code class="lang-python">name = <span class="hljs-string">'Farhan'</span>

print(name[<span class="hljs-number">0</span>])
print(name[<span class="hljs-number">1</span>])
print(name[<span class="hljs-number">2</span>])
print(name[<span class="hljs-number">3</span>])
print(name[<span class="hljs-number">4</span>])
print(name[<span class="hljs-number">5</span>])
</code></pre>
<p>The output of this program will be as follows:</p>
<pre><code class="lang-shell">F
a
r
h
a
n
</code></pre>
<p>Another fun thing that you can do using these indexes is slicing. Assume that you want to take out a part from a string.</p>
<pre><code class="lang-python">name = <span class="hljs-string">'Farhan'</span>

print(name[<span class="hljs-number">0</span>:<span class="hljs-number">3</span>])
</code></pre>
<p>The output of this program will be:</p>
<pre><code class="lang-shell">Far
</code></pre>
<p>In this example, <code>name[0:3]</code> means print starting from index <code>0</code> to index <code>3</code>. Now you may think that <code>h</code> is at index <code>3</code> and you'll be right about that. But the thing about slicing is, it doesn't include the character at the ending index.</p>
<p>If you'd like to learn more about slicing, there is an article titled <a target="_blank" href="https://www.freecodecamp.org/news/how-to-substring-a-string-in-python/">How to Substring a String in Python</a> that you may find useful.</p>
<p>You can use the <code>len()</code> function to figure out the length of a string as follows:</p>
<pre><code class="lang-python">name = <span class="hljs-string">'Farhan'</span>

print(len(name))
</code></pre>
<p>Output from this program will be <code>6</code> since there are six characters in the string.</p>
<p>Python has a ton of string methods, but demonstrating each of them isn't possible here so I'll demonstrate some of the most common ones.</p>
<p>The first method is <code>capitalize()</code>. This method returns a copy of the given string with its first character capitalized and the rest lowercased.</p>
<pre><code class="lang-python">print(<span class="hljs-string">'python is awesome'</span>.capitalize())
</code></pre>
<p>Output of this code will be <code>Python is awesome</code>. If you want to convert the entire sentence to uppercase, there is the <code>upper()</code> method:</p>
<pre><code class="lang-python">print(<span class="hljs-string">'python is awesome'</span>.upper())
</code></pre>
<p>Output of this code will be <code>PYTHON IS AWESOME</code>. You can do the opposite using the <code>lower()</code> method:</p>
<pre><code class="lang-python">print(<span class="hljs-string">'PYTHON IS AWESOME'</span>.lower())
</code></pre>
<p>The output of this code will be <code>python is awesome</code>. There are the <code>isupper()</code> and <code>islower()</code> methods to check whether a string is in uppercase or lowercase.</p>
<pre><code class="lang-python">print(<span class="hljs-string">'PYTHON IS AWESOME'</span>.islower())
print(<span class="hljs-string">'PYTHON IS AWESOME'</span>.isupper())
</code></pre>
<p>Output of this code will be as follows:</p>
<pre><code class="lang-shell">False
True
</code></pre>
<p>If you want to replace all occurrences of a substring within a string, you can do so by using the <code>replace()</code> method:</p>
<pre><code class="lang-python">print(<span class="hljs-string">'python is awesome'</span>.replace(<span class="hljs-string">'python'</span>, <span class="hljs-string">'freeCodeCamp'</span>))
</code></pre>
<p>This code will replace all occurrences of <code>python</code> with <code>freeCodeCamp</code>  in the given string.</p>
<p>Finally, there are the <code>split()</code> and <code>join()</code> methods. The first one splits a string into a list:</p>
<pre><code class="lang-python">print(<span class="hljs-string">'python is awesome'</span>.split(<span class="hljs-string">' '</span>))
</code></pre>
<p>The method takes a delimiter to split the string on. Here, I've used space as the delimiter. Output of this code will be <code>['python', 'is', 'awesome']</code>. This is a list. We haven't covered lists yet but we will soon. For now, understand that they're like arrays.</p>
<p>You can produce a new string using the elements of an iterable, that is a list, using the <code>join()</code> method:</p>
<pre><code class="lang-python">print(<span class="hljs-string">' '</span>.join([<span class="hljs-string">'python'</span>, <span class="hljs-string">'is'</span>, <span class="hljs-string">'awesome'</span>]))
</code></pre>
<p>I've called the <code>join()</code> method on a space so the result of this code will be a string joined using spaces in between as follows:</p>
<pre><code class="lang-python">python <span class="hljs-keyword">is</span> awesome
</code></pre>
<p>If you want to learn more about all the string methods in Python, feel free to consult the <a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#string-methods">official documentation</a>.</p>
<h3 id="heading-numbers-in-python">Numbers in Python</h3>
<p>Numbers in Python can be of integer, floating point, and complex types. In this article, I'll only discuss operations related to the real numbers – that is, integers and floating points.</p>
<p>You can perform addition, subtraction, multiplication, and division operations using integers and floating point numbers like in any other programming language:</p>
<pre><code class="lang-python">a = <span class="hljs-number">10</span>
b = <span class="hljs-number">5</span>

print(a+b)
print(a-b)
print(a*b)
print(a/b)
</code></pre>
<p>Output from this snippet of code will be as follows:</p>
<pre><code class="lang-shell">15
5
50
2.0
</code></pre>
<p>One thing to keep in mind is that even if you perform a division operation between two integers, the result will always be a floating point. If you want the result to be an integer, you can do so as follows:</p>
<pre><code class="lang-python">a = <span class="hljs-number">10</span>
b = <span class="hljs-number">5</span>

print(a//b)
</code></pre>
<p>This time the result will be an integer. Be careful that if there are any numbers after the decimal point, they'll be chopped off.</p>
<p>If you'd like to learn more about the numeric types in Python, feel free to consult the <a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex">official documentation</a>.</p>
<h3 id="heading-how-to-handle-user-input-in-python">How to Handle User Input in Python</h3>
<p>For taking input from the user, there is the <code>input()</code> function.</p>
<pre><code class="lang-python">name = input(<span class="hljs-string">'What is your name? '</span>)

print(<span class="hljs-string">f'Your name is <span class="hljs-subst">{name}</span>'</span>)
</code></pre>
<p>The output from this program will be as follows:</p>
<pre><code class="lang-shell">What is your name? Farhan
Your name is Farhan
</code></pre>
<p>The <code>input()</code> function saves the user input as a string even if the user inputs a number. So if you're taking a number as input from the user, be sure to convert it to the appropriate data type.</p>
<h3 id="heading-if-elif-else-in-python">if-elif-else in Python</h3>
<p>Like any other programming language, Python has the usual <code>if-elif-else</code> statements.</p>
<pre><code class="lang-python">a = float(input(<span class="hljs-string">'First: '</span>))
b = float(input(<span class="hljs-string">'Second: '</span>))
op = input(<span class="hljs-string">'Operation (sum/sub/mul/div): '</span>)

<span class="hljs-keyword">if</span> op == <span class="hljs-string">'sum'</span>:
    print(<span class="hljs-string">f'a + b = <span class="hljs-subst">{a+b}</span>'</span>)
<span class="hljs-keyword">elif</span> op == <span class="hljs-string">'sub'</span>:
    print(<span class="hljs-string">f'a - b = <span class="hljs-subst">{a-b}</span>'</span>)
<span class="hljs-keyword">elif</span> op == <span class="hljs-string">'mul'</span>:
    print(<span class="hljs-string">f'a * b = <span class="hljs-subst">{a*b}</span>'</span>)
<span class="hljs-keyword">elif</span> op == <span class="hljs-string">'div'</span>:
    print(<span class="hljs-string">f'a / b = <span class="hljs-subst">{a/b}</span>'</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">'Invalid Operation!'</span>)
</code></pre>
<p>This is a very simple calculator program. Depending on the operation you choose, the calculator will perform one of the mentioned operations. </p>
<p>In Python, code blocks such as the <code>if</code> block or the <code>elif</code> block or the <code>else</code> block start with the keyword and a colon.</p>
<p>Indentation is crucial in Python and if you indent code within a code block inappropriately, the code will fail to run.</p>
<h3 id="heading-match-case-in-python">match-case in Python</h3>
<p>In Python, a <code>match-case</code> is equivalent to a <code>switch-case</code> statement in other programming languages. The aforementioned calculator program can be rewritten using <code>match-case</code> as follows:</p>
<pre><code class="lang-python">a = float(input(<span class="hljs-string">'First: '</span>))
b = float(input(<span class="hljs-string">'Second: '</span>))
op = input(<span class="hljs-string">'Operation (sum/sub/mul/div): '</span>)

match op:
    case <span class="hljs-string">'sum'</span>:
        print(<span class="hljs-string">f'a + b = <span class="hljs-subst">{a+b}</span>'</span>)
    case <span class="hljs-string">'sub'</span>:
        print(<span class="hljs-string">f'a - b = <span class="hljs-subst">{a-b}</span>'</span>)
    case <span class="hljs-string">'mul'</span>:
        print(<span class="hljs-string">f'a * b = <span class="hljs-subst">{a*b}</span>'</span>)
    case <span class="hljs-string">'div'</span>:
        print(<span class="hljs-string">f'a / b = <span class="hljs-subst">{a/b}</span>'</span>)
    case _:
        print(<span class="hljs-string">'Invalid Operation!'</span>)
</code></pre>
<p>Again, depending on the value of <code>op</code>, one of the cases will be performed. If the input from the user doesn't match any of the cases, then the wildcard <code>_</code> action will take place.</p>
<p>Keep in mind that <code>match-case</code> is available only on Python 3.10 and later versions. So if you're using an older version, you may not have this statement.</p>
<h3 id="heading-lists-and-tuples-in-python">Lists and Tuples in Python</h3>
<p>Lists in Python are a sequence of values. You can modify lists at runtime. You can create a list as follows:</p>
<pre><code class="lang-python">vowels = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'u'</span>]

print(vowels)
</code></pre>
<p>Output of this program will be <code>['a', 'e', 'i', 'o', 'u']</code>. Like strings, each element in a Python list has an index and these indexes start from zero.</p>
<pre><code class="lang-python">vowels = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'u'</span>]

print(vowels[<span class="hljs-number">0</span>])
print(vowels[<span class="hljs-number">1</span>])
print(vowels[<span class="hljs-number">2</span>])
print(vowels[<span class="hljs-number">3</span>])
print(vowels[<span class="hljs-number">4</span>])
</code></pre>
<p>Like strings you can perform slicing on lists as well and the syntax for slicing a list is the same as a string.</p>
<p>Lists in Python have a bunch of useful methods. To add new items to a list there are the <code>append()</code>, <code>extend()</code>, and <code>insert()</code> methods.</p>
<p>The <code>append()</code> method appends a new item to the list and the <code>extend()</code> method adds multiple items:</p>
<pre><code class="lang-python">vowels = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'e'</span>]

vowels.append(<span class="hljs-string">'i'</span>)
vowels.extend([<span class="hljs-string">'o'</span>, <span class="hljs-string">'u'</span>])

print(vowels)
</code></pre>
<p>The <code>insert()</code> method, on the other hand, inserts an item at a given index in the list:</p>
<pre><code class="lang-python">vowels = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'u'</span>]

vowels.insert(<span class="hljs-number">1</span>, <span class="hljs-string">'e'</span>)

print(vowels)
</code></pre>
<p>The <code>pop()</code> method pops the last element off the list:</p>
<pre><code class="lang-python">vowels = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'u'</span>]

popped_item = vowels.pop()

print(popped_item)
print(vowels)
</code></pre>
<p>Output from this snippet of code will be:</p>
<pre><code class="lang-shell">u
['a', 'e', 'i', 'o']
</code></pre>
<p>The <code>remove()</code> method can remove a given element from the list:</p>
<pre><code class="lang-python">vowels = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'u'</span>]

vowels.remove(<span class="hljs-string">'e'</span>)

print(vowels)
</code></pre>
<p>This will delete the <code>e</code> from the list of vowels. </p>
<p>Finally there is the <code>clear()</code> method that removes all the elements from the list.</p>
<p>There is also the <code>sort()</code> method:</p>
<pre><code class="lang-python">vowels = [<span class="hljs-string">'u'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'i'</span>]

vowels.sort()

print(vowels)
</code></pre>
<p>The <code>sort()</code> method sorts the list in ascending order. This method sorts the list in place. This means it doesn't return a new list, and instead sorts the original list.</p>
<p>If you want to reverse the list instead, there is the <code>reverse()</code> method:</p>
<pre><code class="lang-python">vowels = [<span class="hljs-string">'u'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'i'</span>]

vowels.reverse()

print(vowels)
</code></pre>
<p>It's also an in place method like sort. It's just the reverse (no pun intended) of the sort method. You can learn more about lists from the <a target="_blank" href="https://docs.python.org/3/tutorial/datastructures.html">official documentation</a>.</p>
<p>There is also an immutable sequence type called a tuple in Python. Tuples are pretty similar to lists but you can not modify a tuple.</p>
<pre><code class="lang-python">vowels = (<span class="hljs-string">'a'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'u'</span>)

print(vowels)
</code></pre>
<p>The output of this code will be <code>('a', 'e', 'i', 'o', 'u')</code>. There are not many methods for the tuples. If you want to learn more about tuples, consult the <a target="_blank" href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences">official documentation</a>.</p>
<h3 id="heading-loops-in-python">Loops in Python</h3>
<p>You can use loops in Python to iterate over a sequence type like a list.</p>
<pre><code class="lang-python">vowels = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'u'</span>]

<span class="hljs-keyword">for</span> letter <span class="hljs-keyword">in</span> vowels:
    print(letter.upper())
</code></pre>
<p>There is also <code>while</code> loop but since the <code>for</code> loop is what you'll be mostly using, I won't spend time explaining <code>while</code> loops.</p>
<h3 id="heading-dictionaries-in-python">Dictionaries in Python</h3>
<p>Let's assume I've given you the line "the quick brown fox jumped over the lazy dog" and tell you to count the the number of occurrences for each letter. You can do this easily using a hashmap.</p>
<p>A hashmap is a collection of key-value pairs.</p>
<pre><code>{
    <span class="hljs-attr">key_1</span>: value_1,
    <span class="hljs-attr">key_2</span>: value_2,
    <span class="hljs-attr">key_3</span>: value_3,
    <span class="hljs-attr">key_4</span>: value_4,
    <span class="hljs-attr">key_5</span>: value_5,
}
</code></pre><p>To do the task I gave you earlier, you can write the following code:</p>
<pre><code class="lang-python">sentence = <span class="hljs-string">'the quick brown fox jumped over the lazy dog'</span>

record = {}

<span class="hljs-keyword">for</span> letter <span class="hljs-keyword">in</span> sentence:
    <span class="hljs-keyword">if</span> letter <span class="hljs-keyword">in</span> record:
        record[letter] += <span class="hljs-number">1</span>
    <span class="hljs-keyword">else</span>:
        record[letter] = <span class="hljs-number">1</span>

print(record)
</code></pre>
<p>Output for this code will be as follows:</p>
<pre><code class="lang-shell">{'t': 2, 'h': 2, 'e': 4, ' ': 8, 'q': 1, 'u': 2, 'i': 1, 'c': 1, 'k': 1, 'b': 1, 'r': 2, 'o': 4, 'w': 1, 'n': 1, 'f': 1, 'x': 1, 'j': 1, 'm': 1, 'p': 1, 'd': 2, 'v': 1, 'l': 1, 'a': 1, 'z': 1, 'y': 1, 'g': 1}
</code></pre>
<p>This is a dictionary. Each letter is a key and their occurrence number is the value. On the code snippet, you declare a dictionary in the second line. <a target="_blank" href="https://www.freecodecamp.org/news/author/estefaniacn/">Estefania Cassingena Navone</a> has written an article called <a target="_blank" href="https://www.freecodecamp.org/news/python-dictionaries-detailed-visual-introduction/">Python Dictionaries 101: A Detailed Visual Introduction</a> which you may consult to learn more about dictionaries.</p>
<h3 id="heading-functions-in-python">Functions in Python</h3>
<p>The final concept that I'll discuss is functions. Functions in programming are chunks of code that perform a certain task. </p>
<p>In Python, you can declare a function using the <code>def</code> keyword followed by the function signature:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-keyword">return</span> a + b

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sub</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-keyword">return</span> a - b

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">mul</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-keyword">return</span> a * b

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">div</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-keyword">return</span> a / b

a = float(input(<span class="hljs-string">'First: '</span>))
b = float(input(<span class="hljs-string">'Second: '</span>))
op = input(<span class="hljs-string">'Operation (sum/sub/mul/div): '</span>)

<span class="hljs-keyword">if</span> op == <span class="hljs-string">'sum'</span>:
    print(<span class="hljs-string">f'a + b = <span class="hljs-subst">{sum(a, b)}</span>'</span>)
<span class="hljs-keyword">elif</span> op == <span class="hljs-string">'sub'</span>:
    print(<span class="hljs-string">f'a - b = <span class="hljs-subst">{sub(a, b)}</span>'</span>)
<span class="hljs-keyword">elif</span> op == <span class="hljs-string">'mul'</span>:
    print(<span class="hljs-string">f'a * b = <span class="hljs-subst">{mul(a, b)}</span>'</span>)
<span class="hljs-keyword">elif</span> op == <span class="hljs-string">'div'</span>:
    print(<span class="hljs-string">f'a / b = <span class="hljs-subst">{div(a, b)}</span>'</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">'Invalid Operation!'</span>)
</code></pre>
<p>This is the same calculator program as before, but now the operations are written within separate functions. </p>
<p>To learn more about functions, you can read this article: <a target="_blank" href="https://www.freecodecamp.org/news/functions-in-python-a-beginners-guide/">Functions in Python – Explained with Code Examples</a> by <a target="_blank" href="https://www.freecodecamp.org/news/author/bala-priya/">Bala Priya C</a>.</p>
<p>There are a lot of other concepts that you need to learn if you want to be a great Python programmer. That's what the next section is about.</p>
<h2 id="heading-additional-python-learning-resources">Additional Python Learning Resources</h2>
<p>Now that you have a basic understanding of the Python programming language, I'll suggest some high quality learning resources to continue your learning journey.</p>
<h3 id="heading-learn-python-in-4-hours">Learn Python in 4 Hours</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/rfscVS0vtbw" 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>
<p>The first resource on the list is a video on the freeCodeCamp YouTube channel created by Girrafe Academy. </p>
<p>The instructor has created multiple courses on the channel and is known for making concise videos. </p>
<p>The video covers most of the important Python concepts within 4 hours. The instructor also makes simple projects along the way.</p>
<h3 id="heading-python-for-everybody">Python for Everybody</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/8DvywoWv6fI" 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>
<p>Another beginner friendly Python course in the freeCodeCamp YouTube channel is Python for Everybody. What makes this course special is that it not only targeted at Python beginners but at people who're trying to get started with programming in general. </p>
<p>The course is a little over 13 hours long and is taught by Charles R. Severance aka Dr. Chuck. He has authored some of the most amazing courses on the internet. </p>
<p>If you're patient enough to sit through a 13 hour course, Python for Everybody is one of the best Python courses online.</p>
<h3 id="heading-12-beginner-python-projects">12 Beginner Python Projects</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/8ext9G7xspg" 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>
<p>If you prefer a project-based approach, then this 3 hours course by Kylie Ying is highly recommended. </p>
<p>Kylie is a freeCodeCamp team member and knows what she's doing. In this course you'll learn to make 12 beginner friendly Python projects in increasing levels of complexity.</p>
<h3 id="heading-learn-python-by-building-5-games">Learn Python by Building 5 Games</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/XGf2GcyHPhc" 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>
<p>If you're into gaming and want to learn Python through building classic games, then this course should be a good fit for you. </p>
<p>The instructor for this course is Christian Thompson, an experienced Python programmer. If you're familiar with another programming language or you learn well by jumping into projects, dive right in.</p>
<h3 id="heading-intermediate-python">Intermediate Python</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/HGOBQPFzWKo" 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>
<p>If you've finished your first Python course and have learned all the fundamental concepts and now you're looking for the next logical step, then look no further.</p>
<p>Patrick Loeber has produced this 6 hour course on intermediate Python where you'll learn about a good number concepts usually not found in beginner Python courses.</p>
<h3 id="heading-object-oriented-programming-with-python">Object Oriented Programming with Python</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Ej_02ICOIgs" 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>
<p>If you're struggling to understand of object oriented programming in general, this course will teach you object oriented programming with Python in 2 hours. </p>
<p>The course includes tons of code examples and covers all the important concepts regarding object oriented programming with Python. I'd suggest this course right after you've finished your basic course.</p>
<h3 id="heading-python-for-data-science">Python for Data Science</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/LHBE6Q9XlzI" 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>
<p>This is a bit of a specialized course. If you're thinking of getting into data science and want to learn about all the necessary Python stuff necessary for data science then this course will help you greatly. </p>
<p>Don't think that this is a quick course. In its just over 12 hour runtime, this course will teach you Python programming concepts and a bunch of tools essential for data science in great detail.</p>
<h3 id="heading-data-structures-and-algorithms-in-python">Data Structures and Algorithms in Python</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/pkYVOmU3MgA" 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>
<p>Having an understanding of data structures and algorithms is essential to becoming an efficient software developer. </p>
<p>In this 12.5 hour course from Jovian, you'll learn about important data structures and algorithms with code examples in great detail. Regardless of what you plan to do with Python afterwards, I'd highly recommend this course.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I would like to thank you from the bottom of my heart for the time you've spent reading this article. </p>
<p>Although I've listed as many as good resources I could, the <a target="_blank" href="https://www.youtube.com/c/Freecodecamp/search?query=python">freeCodeCamp YouTube channel</a> is just filled with excellent Python learning resources.</p>
<p>I also have a personal blog where I write about random tech stuff, so if you're interested in something like that, checkout <a target="_blank" href="https://farhan.dev">https://farhan.dev</a>. If you have any questions or are confused about anything – or just want to get in touch – I'm available on <a target="_blank" href="https://twitter.com/frhnhsin">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Extern – C and C++ Extern Keyword Function Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ The extern keyword in C and C++ extends the visibility of variables and functions across multiple source files.  In the case of functions, the extern keyword is used implicitly. But with variables, you have to use the keyword explicitly. I believe a ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/extern-keyword-function-tutorial/</link>
                <guid isPermaLink="false">66b0ab323d157e92c589ab95</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Thu, 21 Apr 2022 00:08:58 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/Extern---C-and-C---Extern-Keyword-Function-Tutorial.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The <code>extern</code> keyword in C and C++ extends the visibility of variables and functions across multiple source files. </p>
<p>In the case of functions, the <code>extern</code> keyword is used implicitly. But with variables, you have to use the keyword explicitly.</p>
<p>I believe a simple code example can explain things better in some cases than a wall of text. So I'll quickly setup a simple C++ program for demonstration. </p>
<p>If you have GCC installed on your system you may follow along. Otherwise, I'll include outputs from each code snippet with them for you to read through.</p>
<h2 id="heading-extern-with-functions"><code>extern</code> with Functions</h2>
<p>In the example, I have two C++ files named <code>main.cpp</code> and <code>math.cpp</code> and a header file named <code>math.h</code>. Code for the <code>math.h</code> file is as follows:</p>
<pre><code class="lang-header">int sum(int a, int b);
</code></pre>
<p>As you can see, the header file contains the declaration for a simple function called <code>sum</code> that takes two integers as parameters. The code for the <code>math.cpp</code> file is as follows:</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">sum</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{
    <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>This file contains the definition for the previously declared <code>sum</code> function and it returns the sum of the given parameters as an integer.</p>
<p>Finally, the code for the <code>main.cpp</code> file is as follows:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"math.h"</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span> <span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; sum(<span class="hljs-number">10</span>, <span class="hljs-number">8</span>) &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
}
</code></pre>
<p>This file includes the <code>math.h</code> header file containing the declaration for the <code>sum</code> function. Then inside the <code>main</code> function, the <code>std::cout &lt;&lt; sum(10, 8) &lt;&lt; std::endl;</code> statement calls the <code>sum</code> functions by passing <code>10</code> and <code>8</code> as the two parameters and prints out whatever the returned value is.</p>
<p>Now if you try to compile this program you'll see it compiles without any problem and upon executing the resultant binary file, you'll see following output in the console:</p>
<pre><code><span class="hljs-number">18</span>
</code></pre><p>This works (even though the definition of the <code>sum</code> function is in a separate file than <code>main.cpp</code>) because all the functions in C/C++ are declared as <code>extern</code>. This means they can be invoked from any source file in the whole program. </p>
<p>You can declare the function as <code>extern int sum(int a, int b)</code> instead but this will only cause redundancy.</p>
<h2 id="heading-extern-with-variables"><code>extern</code> with Variables</h2>
<p>Although the <code>extern</code> keyword is applied implicitly to all the functions in a C/C++ program, the variables behave a bit differently. </p>
<p>Before I dive into the usage of <code>extern</code> with variables, I would like to clarify the difference between declaring a variable and defining it.</p>
<p>Declaring a variable simply declares the existence of the variable to the program. It tells the compiler that a variable of a certain type exists somewhere in the code. You declare a float variable as follows:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">float</span> pi;
</code></pre>
<p>At this point, the variable doesn't have any memory allocated to it. The compiler only knows that a <code>float</code> variable named <code>pi</code> exists somewhere in the code.</p>
<p>Defining the variable, on the other hand, means declaring the existence of the variable, as well as allocating the necessary memory for it. You define a variable as follows:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">float</span> pi = <span class="hljs-number">3.1416</span>;
</code></pre>
<p>You can declare a variable as many times as you want, but you can define a variable only once. This is because you can not allocate memory to the same variable multiple times.</p>
<p>Now, I'll modify the <code>math.h</code> header file created in the previous section to contain the declaration for the <code>pi</code> variable as follows:</p>
<pre><code class="lang-header">extern float pi;
int sum(int a, int b);
</code></pre>
<p>As you can see, the variable has been declared as an <code>extern</code> in the header file, which means this should be accessible anywhere in the program. Next, I'll update the <code>main.cpp</code> file as follows:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">"math.h"</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span> <span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; pi &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; sum(<span class="hljs-number">10</span>, <span class="hljs-number">8</span>) &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
}
</code></pre>
<p>I've added a new <code>std::cout</code> statement to print out the value of the <code>pi</code> variable. If you try to compile this program at this point, the compilation process will fail.</p>
<pre><code>Starting build...
C:\mingw64\bin\g++.exe -fdiagnostics-color=always -g C:\Users\shovi\repos\cpp-playground\extern\*.cpp -o C:\Users\shovi\repos\cpp-playground\extern\extern.exe
<span class="hljs-attr">c</span>:<span class="hljs-regexp">/mingw64/</span>bin/../lib/gcc/x86_64-w64-mingw32/<span class="hljs-number">11.2</span><span class="hljs-number">.0</span>/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\shovi\AppData\Local\Temp\ccFIWkmh.o:main.cpp:(.rdata$.refptr.pi[.refptr.pi]+<span class="hljs-number">0x0</span>): <span class="hljs-literal">undefined</span> reference to <span class="hljs-string">`pi'
collect2.exe: error: ld returned 1 exit status

Build finished with error(s).</span>
</code></pre><p>This happens because, declaring the variable has let the compiler know that this variable exists somewhere in the program – but in reality it doesn't. It has no memory allocation at all.</p>
<p>To get out of this problem, I'll define the <code>pi</code> variable inside the <code>math.cpp</code> file as follows:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">float</span> pi = <span class="hljs-number">3.1416</span>;

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">sum</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{
    <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>The compilation process finishes without any issues, and if I execute the resultant binary, I'll see the following output in my console:</p>
<pre><code><span class="hljs-number">3.1416</span>
<span class="hljs-number">18</span>
</code></pre><p>Since the <code>pi</code> variable has been declared as an <code>extern</code> and has been defined within the <code>math.cpp</code> file, the <code>main.cpp</code> file is able to access the value of <code>pi</code> without any problem at all. </p>
<p>You can define the variable anywhere in the program but I chose the <code>math.cpp</code> file for definition to prove the point that this <code>extern</code> variable indeed is available to all the other source files as well.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Even though it's not used that often, the <code>extern</code> keyword in C/C++ is undoubtedly one of the most important concept to understand. I hope you've understood how the keyword works at a basic level from this short article.</p>
<p>As you continue to use the keyword in your programs, you'll definitely come across problems and situations that are outside the scope of this article. Feel free to reach out to me in <a target="_blank" href="https://twitter.com/frhnhsin">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a> if you think I can be of help. Otherwise, <a target="_blank" href="https://stackoverflow.com/">Stack Overflow</a> is always there to help.</p>
<p>Also, if you're native Bengali speaker, checkout freeCodeCamp's <a target="_blank" href="https://www.freecodecamp.org/bengali/news/">Bengali Publication</a> and <a target="_blank" href="https://www.youtube.com/channel/UCYl5XjGuTM1gbXUuxH1e0jA">YouTube Channel</a>. Till the next one, stay safe and keep learning.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python IDE – Best IDEs and Editors for Python ]]>
                </title>
                <description>
                    <![CDATA[ Much of your experience as a developer will depend on what program you've chosen to write your code in. A good integrated development environment (IDE) or Code Editor can really boost your productivity. The problem with popular languages like Python ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-ide-best-ides-and-editors-for-python/</link>
                <guid isPermaLink="false">66b0ab472344be226f331c6c</guid>
                
                    <category>
                        <![CDATA[ editor ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Tue, 12 Apr 2022 19:28:47 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/Python-IDE---Best-IDEs-and-Editors-for-Python.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Much of your experience as a developer will depend on what program you've chosen to write your code in. A good integrated development environment (IDE) or Code Editor can really boost your productivity.</p>
<p>The problem with popular languages like Python is that every IDE or code editor under the sun seems to have good support for the language. While this can be great, choosing the best one becomes a bit tricky. </p>
<p>In this article I'll introduce you to three IDEs and code editors that can make your Python journey smoother.</p>
<p>But before I begin I want to clarify the fact that this is not an exhaustive list. Like I said, Python is one of the most popular programming languages so it's supported by a large number of code editors and IDEs. </p>
<p>I could've included as many of them as possible, but instead I chose to include the ones that I've used at some point in my life and don't mind going back to. Because I think this'll be more helpful.</p>
<p>Without any further ado, let's jump in!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-ide-vs-code-editor-whats-the-difference">IDE vs Code Editor – What's the difference?</a></li>
<li><a class="post-section-overview" href="#heading-pycharm">PyCharm</a></li>
<li><a class="post-section-overview" href="#heading-microsoft-visual-studio-code">Microsoft Visual Studio Code</a></li>
<li><a class="post-section-overview" href="#heading-sublime-text">Sublime Text</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-ide-vs-code-editor-whats-the-difference">IDE vs Code Editor – What's the Difference?</h2>
<p>Before you start reading about the IDEs and Code Editors I have in store for you, let's clarify the definitions of an IDE and a Code Editor.</p>
<p>As you may already know, source code files are just text files with certain extensions appended to them. Any text editor that has some special feature such as syntax highlighting, automatic code indentation, and so on to make editing code files easier is called a code editor. </p>
<p>Popular code editors include Visual Studio Code, Sublime Text, Atom, Notepad++ and more.</p>
<p>An IDE or Integrated Development Environment, on the other hand, is a much more complex suite of software that combines multiple tools such as a code editor, a file browser, a terminal emulator, a database explorer and more in a single package. </p>
<p>Popular IDEs include PyCharm, IntelliJ Idea, Microsoft Visual Studio, and others.</p>
<p>But thanks to modern highly extensible code editors such as Microsoft Visual Studio Code, the line between an IDE and a Code Editor has started to fade away.</p>
<p>Now that you have a better idea of what an editor is compared to a full-blown IDE, let's look at some of the best for Python coding.</p>
<h2 id="heading-pycharm">PyCharm</h2>
<p>The first one in our list is an IDE from JetBrains. <a target="_blank" href="https://www.jetbrains.com/pycharm/">PyCharm</a> is one of the most used Python IDEs out there (if not the most used).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/complexLook@2x.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>https://www.jetbrains.com/pycharm/</em></p>
<p>The IDE has two editions. The professional edition will cost you $8.90 every month and $89.00 every year if billed yearly. There is also the community edition which is completely free and is built on open-source software. In this article I'll discuss the community edition.</p>
<p>Both editions are available for Windows, macOS, and Linux. You can download the 30 day trial of the professional edition or the community edition from the official <a target="_blank" href="https://www.jetbrains.com/pycharm/download/">download page</a>.</p>
<p>The installation process is pretty straightforward regardless of the platform you're on. Once you've downloaded and installed PyCharm on your computer, you should be able to start the IDE. You can use the start menu shortcut on Windows, the Applications directory on macOS, or your application launcher on Linux.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-17.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can create a new Python project by clicking on the <em>New Project</em> button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-18.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the next step, choose where you'd like to store your project. You can either create a new virtual environment or use a previously configured interpreter. In this case, I'm creating a new environment.</p>
<p>If you check the <em>Create a main.py welcome script</em> option, a new Python file with some boilerplate code will be created inside your project. Once you're happy with all the choices, hit the <em>Create</em> button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-19.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is what the code editor looks like once the project has been created. On the left side you can browse all your source files, and you can hit the play button on the top right corner of the window to run the selected scripts in the dropdown.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/run-code-pycharm.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you can see, PyCharm comes with a terminal built in on the bottom of the window and you can see outputs from your program without ever leaving PyCharm.</p>
<p>The community edition is quite complete and you can do more or less everything you can do on the professional edition. The professional edition has better support for web frameworks like Django and some other bells and whistles.</p>
<p>If you're a student, you can get PyCharm Professional Edition and all other JetBrains stuff for free <a target="_blank" href="https://www.jetbrains.com/community/education/#students">by applying on their website</a>. You can also get a free license of all the JetBrains products if you're <a target="_blank" href="https://www.jetbrains.com/community/opensource/">an open-source maintainer</a>.</p>
<h2 id="heading-microsoft-visual-studio-code">Microsoft Visual Studio Code</h2>
<p>Next in the list of my favorites is Microsoft Visual Studio Code or VSCode for short. It's an open-source, electron-powered, cross-platform code editor from Microsoft with a ton of customization options and extensions.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-21.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>By installing the right set of extensions, you can turn Visual Studio Code into almost a fully-featured Python IDE. You can download VSCode for free from the <a target="_blank" href="https://code.visualstudio.com/#alt-downloads">official download site</a> for Windows, macOS, and Linux.</p>
<p>Once you've installed VSCode on your system, open the software and go to the extensions tab by hitting the <em>Ctrl + Shift + X</em> key combination.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-22.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Use the search bar to search for and install the following extensions:</p>
<ul>
<li><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=ms-python.python">Python</a> – provides features such as IntelliSense (Pylance), linting, debugging, code navigation, code formatting, refactoring, variable explorer, test explorer, and more!</li>
<li><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance">PyLance</a> – works alongside Python in Visual Studio Code to provide performant language support.</li>
<li><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=VisualStudioExptTeam.vscodeintellicode">Visual Studio IntelliCode</a> – provides AI-assisted development features for Python, TypeScript/JavaScript and Java developers in Visual Studio Code.</li>
</ul>
<p>Once you have these three installed, you're good to go. Create a directory anywhere on your machine and open that folder using VSCode. You can use the integrated terminal to run your code or execute any command in general.</p>
<p>You can set breakpoints by clicking on the left side of any line number. Then you can hit <em>F5</em> to start debugging or <em>Ctrl + F5</em> to run the program without debugging. VSCode has a lot more tricks up its sleeve that you'll find out as you keep using it.</p>
<h2 id="heading-sublime-text">Sublime Text</h2>
<p>Sublime Text is one of the OG code editors that has been used by developers for years. It's a very performant, powerful code editor with rich support for packages.</p>
<p>You can download Sublime Text from their <a target="_blank" href="https://www.sublimetext.com/download">official download page</a> for Windows, macOS, and Linux. Once you have it installed, start Sublime Text like any other software.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-23.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now click on <em>Tools &gt; Install Package Control...</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-24.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This'll install the Sublime Package Manager. Wait until a success message shows up.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-25.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now go to Command Palette using the <em>Ctrl + Shift + P</em> key combination and type <em>Install Package</em>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-26.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Select the first option and search for the <a target="_blank" href="https://packagecontrol.io/packages/Anaconda">Anaconda</a> package. This is the ultimate Python package that turns Sublime Text into a Python IDE with features like autocompletion, code linting, IDE features, autopep8 formating, McCabe complexity checker, Vagrant and Docker support, and more.</p>
<p>There are also more specific packages such as <a target="_blank" href="https://packagecontrol.io/packages/Djaneiro">Djaneiro</a> for Django support and <a target="_blank" href="https://packagecontrol.io/packages/requirementstxt">requirementstxt</a> for requirements.txt support on Sublime Text. Just look around the Package Control <a target="_blank" href="https://packagecontrol.io/browse">website</a> and you may find some pretty useful packages.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As I've already said, this is not an exhaustive list of all the popular Python IDEs and Code Editors. I've also used <a target="_blank" href="https://www.spyder-ide.org/">Spyder</a> at a point in my life but decided to leave it off since it's targeted at scientists and engineers. </p>
<p>I've also used <a target="_blank" href="https://docs.python.org/3/library/idle.html">IDLE</a> for a brief period as well but it didn't seem like a strong enough option when it comes to larger projects. </p>
<p>If you think I've left out any other good one, let me know via <a target="_blank" href="https://twitter.com/frhnhsin">Twitter</a> or <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>. Also, if you're native Bengali speaker, checkout freeCodeCamp's <a target="_blank" href="https://www.freecodecamp.org/bengali/news/">Bengali Publication</a> and <a target="_blank" href="https://www.youtube.com/channel/UCYl5XjGuTM1gbXUuxH1e0jA">YouTube Channel</a>. Till the next one, stay safe and keep learning.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Learn the C++ Programming Language ]]>
                </title>
                <description>
                    <![CDATA[ In the early days of computer programming, programmers had to write individual instructions in the Assembly language one by one.  Later on programming languages like FORTRAN and COBOL were created. The problem with these languages was that they were ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-learn-the-c-programming-language/</link>
                <guid isPermaLink="false">66b0ab3c2344be226f331c66</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Mon, 11 Apr 2022 17:10:10 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/03/How-to-Learn-the-C---Programming-Language.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In the early days of computer programming, programmers had to write individual instructions in the Assembly language one by one. </p>
<p>Later on programming languages like FORTRAN and COBOL were created. The problem with these languages was that they were targeted at a certain group of people – FORTRAN for engineers and scientists and COBOL for business people.</p>
<p>Then during the 60s a new language called Simula surfaced and introduced the concept of a class, which sort of let anyone make software for their special fields.</p>
<p>After that, during the 80s, Bjarne Stroustrup came up with the idea of combining the general abstraction of Simula with the low level functionalities of C, which at the time was the best language for the job. </p>
<p>Thus, "C with Classes" was born which later became known as the C++ programming language.</p>
<p>The C++ programming language is a statically typed, compiled, multi-paradigm, general purpose programming language notorious for it's steep learning curve. It has wide spread use in video game, desktop software, and embedded system development. </p>
<p>C++ is somewhat complex and extremely powerful – and to be honest, if you plan your learning roadmap properly, C++ is not as bad as many people may want you to believe.</p>
<p>In this article, I'll start by showing you the very basics of the C++ programming language. </p>
<p>If you've programmed before, this introduction should be pretty straightforward for you. But if you're learning C++ as your first programming language, you may find it quite challenging because of the sheer amount of concepts you'll have to understand.</p>
<p>Once I've finished with the introduction, I'll give you a list of high quality learning resources as well as recommendations on how to make the most out of them.</p>
<p>So without further ado, let's jump in.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-high-level-overview-of-c">High Level Overview of C++</a><ul>
<li><a class="post-section-overview" href="#heading-hello-world">Hello World</a></li>
<li><a class="post-section-overview" href="#heading-understanding-a-c-program">Understanding a C++ Program</a></li>
<li><a class="post-section-overview" href="#heading-common-data-types-and-arrays">Common Data Types and Arrays</a></li>
<li><a class="post-section-overview" href="#heading-flow-control">Flow Control</a></li>
<li><a class="post-section-overview" href="#heading-functions">Functions</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-c-learning-resources">C++ Learning Resources</a><ul>
<li><a class="post-section-overview" href="#heading-learn-c-in-31-hours">Learn C++ in 31 Hours</a></li>
<li><a class="post-section-overview" href="#heading-learn-c-in-4-hours">Learn C++ in 4 Hours</a></li>
<li><a class="post-section-overview" href="#heading-object-oriented-programming-oop-in-c">Object Oriented Programming (OOP) in C++</a></li>
<li><a class="post-section-overview" href="#heading-opengl-crash-course">OpenGL Crash Course</a></li>
<li><a class="post-section-overview" href="#heading-unreal-engine-in-5-hours">Unreal Engine in 5 Hours</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-high-level-overview-of-c">High Level Overview of C++</h2>
<p>Before I jump into the learning roadmap and resources section, I would like to introduce you to the C++ programming language itself. This way, you won't feel overwhelmed once you start diving into the below mentioned resources. </p>
<p>Keep in mind that this section assumes that you have experience of working with some other programming language such as Python or JavaScript.</p>
<h3 id="heading-hello-world">Hello World</h3>
<p>As I've already mentioned, C++ is a statically typed, compiled programming language and there are a number of compilers available out there. </p>
<p>The GCC or GNU Compiler Collection is one of the most popular compilers for C++ and my fellow freeCodeCamp author <a target="_blank" href="https://www.freecodecamp.org/news/author/fahimbinamin/">Md. Fahim Bin Amin</a> has written an excellent guide on <a target="_blank" href="https://www.freecodecamp.org/news/how-to-install-c-and-cpp-compiler-on-windows/">How to Install C and C++ Compilers on Windows</a>. </p>
<p>Depending on your Linux distribution, one of the following commands should install GCC for you:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Debian/Ubuntu</span>
sudo apt install build-essential

<span class="hljs-comment"># Fedora</span>
sudo dnf install make automake gcc gcc-c++

<span class="hljs-comment"># Arch Linux</span>
sudo pacman -S base-devel
</code></pre>
<p>On a mac, you can either install GCC using <a target="_blank" href="https://brew.sh/">Homebrew</a> or follow the guide written by another freeCodeCamp author <a target="_blank" href="https://www.freecodecamp.org/news/author/danielkehoe/">Daniel Kehoe</a> on <a target="_blank" href="https://www.freecodecamp.org/news/install-xcode-command-line-tools/">How to Install Xcode Command Line Tools on a Mac</a>.</p>
<p>Apart from GCC, there is also MSVC or Microsoft Visual C++ compiler on Windows. To install MSVC, head over to <a target="_blank" href="https://visualstudio.com/">https://visualstudio.com/</a>, download the latest installer, and install the "Desktop development with C++" workload:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/image-120.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once you've done that, you should be able to write and compile C++ programs on your computer. To do so, create a file <code>hello-world.cpp</code> anywhere in your computer and put the following code in it:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Hello World!"</span> &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Now if you're using GCC, open a terminal window in the same directory where the <code>hello-world.cpp</code> file exists and execute the following command:</p>
<pre><code>g++ -o hello-world hello-world.cpp
</code></pre><p>This command will compile the <code>hello-world.cpp</code> into the file indicated in the <code>-o</code> option. You should see a new binary file named <code>hello-world</code> in the same folder. Execute the file from the terminal as follows:</p>
<pre><code class="lang-bash">./hello-world

<span class="hljs-comment"># Hello World!</span>
</code></pre>
<p>If you're using MSVC, open up the start menu and search for "Developer PowerShell" and open the appropriate program according to your Visual Studio version:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/03/developer-powershell.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now, cd into the directory where you've saved your <code>hello-world.cpp</code> file and execute the following command:</p>
<pre><code class="lang-bash">cl -o hello-world hello-world.cpp
</code></pre>
<p>Like the <code>g++</code> command, this will compile your <code>hello-world.cpp</code> file into a <code>hello-world.exe</code> binary executable. Execute the file using the following command:</p>
<pre><code class="lang-bash">.\hello-world.exe

<span class="hljs-comment"># Hello World!</span>
</code></pre>
<h3 id="heading-understanding-a-c-program">Understanding a C++ Program</h3>
<p>Now that you've written your first C++ program, it's time to understand what you just did. Let's take a look at the source code once again:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Hello World!"</span> &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>The source file has four lines of code in total. The first line is <code>#include &lt;iostream&gt;</code> and it does exactly what it sounds like. It includes the content of the <code>iostream</code> header file in the <code>hello-world.cpp</code> file. </p>
<p>Header files contain declarations of things like the <code>std::cout</code> and <code>std::endl</code> objects. The <code>iostream</code> header file deals with input and output streams.</p>
<p>After the <code>#include</code> statement, the <code>int main(){}</code> lines declares and defines a new function. This <code>main()</code> function will be called by the OS when you execute your program and every executable C++ program must have a <code>main()</code> function.</p>
<p>Everything you write within the curly braces will be part of this function. In the above mentioned code, the <code>std::cout</code> object prints any string that comes after the <code>&lt;&lt;</code> sign. The <code>std::endl</code> object appends a newline character at the end of the line. You can chain multiple things to output in a single <code>std::cout</code> call as follows:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Hello World!"</span> &lt;&lt; <span class="hljs-string">" "</span> &lt;&lt; <span class="hljs-string">"C++ is awesome!"</span> &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>If you compile and run this program, you'll get the following output:</p>
<pre><code class="lang-bash">Hello World! C++ is awesome!
</code></pre>
<p>The word <code>int</code> in the function declaration simply means this function returns an integer. Returning <code>0</code> at the end of a program means it ran successfully. A non zero return value usually indicates some kind of failure, but that topic is out of the scope of this article.</p>
<h3 id="heading-common-data-types-and-arrays">Common Data Types and Arrays</h3>
<p>C++ has seven fundamental data types. They are as follows:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Data Type</td><td>Meaning</td></tr>
</thead>
<tbody>
<tr>
<td><code>int</code></td><td>Integer</td></tr>
<tr>
<td><code>float</code></td><td>Floating Point</td></tr>
<tr>
<td><code>double</code></td><td>Double Floating Point</td></tr>
<tr>
<td><code>char</code></td><td>Character</td></tr>
<tr>
<td><code>w_char</code></td><td>Wide Character</td></tr>
<tr>
<td><code>bool</code></td><td>Boolean</td></tr>
<tr>
<td><code>void</code></td><td>Empty</td></tr>
</tbody>
</table>
</div><p>There are modifiers such as <code>short</code>, <code>long</code>, <code>signed</code>, and <code>unsigned</code> but I won't touch upon them in this high level overview. </p>
<p>To declare a variable of a certain data type, you can do something like this:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> number = <span class="hljs-number">25</span>;

    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The number is "</span> &lt;&lt; number &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>If you compile and run this program, the output will be:</p>
<pre><code>The number is <span class="hljs-number">25</span>
</code></pre><p>There are also arrays which are capable of storing multiple values of the same type. So if you want to declare an array of type <code>int</code>, you can do so as follows:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> numbers[] = { <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">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The number is "</span> &lt;&lt; numbers[<span class="hljs-number">0</span>] &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>You can access any element from the array following the <code>array_name[element_index]</code> syntax. Array indexes are zero-based so to access the number one element, you'll have to write <code>numbers[0]</code>, and the output of the above code will be:</p>
<pre><code>The number is <span class="hljs-number">1</span>
</code></pre><p>You can also create strings using arrays of <code>char</code> type as follows:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">char</span> name[] = <span class="hljs-string">"Farhan"</span>;

    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"My name is "</span> &lt;&lt; name &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>The output of this program will be:</p>
<pre><code>My name is Farhan
</code></pre><p>There is also <code>std::string</code> but I won't touch upon that. You can <a target="_blank" href="https://www.freecodecamp.org/news/c-string-std-string-example-in-cpp/">read more about it here</a>.</p>
<h3 id="heading-flow-control">Flow Control</h3>
<p>In C++ there are the common ways of controlling the flow of your program such as if-else statements, switch statements, loops, breaks and so on. </p>
<p>In this section, I'll show you an example of if-else, a for loop, and a break statement. </p>
<p>Have a look at the following program:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> numbers[] = { <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-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span> };

    <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">10</span>; i++) {
        <span class="hljs-keyword">if</span> (numbers[i] == <span class="hljs-number">5</span>) {
            <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; numbers[i] &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

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

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>It's a simple program that loops over an array of integers and checks whether the current element if 5 or not. If it is, the program will print out the number and break out of the loop. This can also be done using a range-based for loop as follows:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">int</span> numbers[] = { <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-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span> };

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span> number : numbers) {
        <span class="hljs-keyword">if</span> (number == <span class="hljs-number">5</span>) {
            <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; number &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

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

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>The <code>auto</code> keyword will infer the type of the variable automatically. This syntax is again out of the scope of this article, but I just wanted to show you what you can do in C++.</p>
<h3 id="heading-functions">Functions</h3>
<p>Like any other programming language, C++ also has functions. You can create one as follows:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{
    <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The sum is "</span> &lt;&lt; add(<span class="hljs-number">8</span>, <span class="hljs-number">2</span>) &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>In this example, I've created a function named <code>add()</code> which returns an <code>int</code> and takes <code>int a</code> and <code>int b</code> as parameters. </p>
<p>When you call this function and pass two integers to it, the function will simply add the two numbers and return the sum. This is probably the simplest form of function in C++. In reality functions can get much more complex than this.</p>
<p>Now that you have a very brief idea of how the C++ programming language works, I'll introduce you to some very high quality learning resources on YouTube that you can use to learn C++.</p>
<h2 id="heading-c-learning-resources">C++ Learning Resources</h2>
<p>In this section I'll give you a list of free and awesome videos on C++. Let's begin with the first one.</p>
<h3 id="heading-learn-c-in-31-hours">Learn C++ in 31 Hours</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/8jLOx1hD3_o" 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>
<p>This is the latest C++ video on freeCodeCamp's YouTube channel. It's 31 hours long and touches upon every single important C++ concept. This is also the most up to date video on the list. </p>
<p>The instructor <strong>Daniel Gakwaya</strong> is an experienced software developer and knows what's he doing. If you're getting started with C++ in 2022, this is the video to follow.</p>
<p>But there are a few things to keep in mind when you're watching this. I've watched this video myself to brush up my rusty C++ skills and I can say from experience that you may feel overwhelmed by the time you've reached the middle of the video.</p>
<p>Don't worry, it's totally okay. What I suggest that you do is don't try to watch the entire video in one go. That way you won't remember anything.</p>
<p>Start from <strong>Chapter 1</strong> and watch the video until <strong>Chapter 7</strong>. Make sure to take breaks after each chapter and practice what you've learned. </p>
<p>Once you've reached Chapter 7, you should be able to solve any basic programming problem using C++. So find a programming problem solving platform that suits you and start solving problems using C++. </p>
<p>Once you feel confident about what you've already learned, come back to the video and resume watching.</p>
<p>Then I would suggest that you watch one chapter a day starting from Chapter 8. Because these are all intermediate to advanced topics and will take time to be properly understood. Don't rush, take it slow.</p>
<h3 id="heading-learn-c-in-4-hours">Learn C++ in 4 Hours</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/vLnPwxZdW4Y" 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>
<p>If you think that 31 hours is a bit too overwhelming for you, then I would suggest this one. It's one of the older videos on the channel and teaches most of the fundamental concepts of C++ pretty nicely. </p>
<p>The instructor <strong>Mike</strong> from <strong>Giraffe Academy</strong> has created multiple courses on the freeCodeCamp channel and is well known for making enjoyable long tutorials.</p>
<p>The instructor will build some simple projects such as a calculator and mad libs game during the video. Make sure to understand what he's doing and try to implement those projects by yourself. This way you'll learn way better than just copying what he's doing on the video.</p>
<h3 id="heading-object-oriented-programming-oop-in-c">Object Oriented Programming (OOP) in C++</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/wN0x9eZLix4" 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>
<p>This video is a bit different than the previous ones. Let's assume that you know C++ but you're not confident about your understanding of object oriented programming. In that case this video will help you immensely. It's a 1.5 hour long video completely dedicated to object oriented programming in C++. </p>
<p>The instructor <strong>Saldina Nurak</strong> aka <strong>CodeBeauty</strong> is a software developer and runs <a target="_blank" href="https://www.youtube.com/c/CodeBeauty/">an entire channel dedicated to C++</a>. Feel free to check out her content.</p>
<h3 id="heading-opengl-crash-course">OpenGL Crash Course</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/45MIykWJ-C4" 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>
<p>Assume that you have mastered C++ following one of the previous videos and now want to do something fun. Well, one of the most common things that you can do with C++ is working with graphics. </p>
<p>In this almost 2 hour long video course by <strong>Victor Gordan</strong> you'll not only learn about applying you C++ skills to render pretty graphics on screen, but also you'll get a good understanding of how computer graphics work in general.</p>
<p>The video requires understanding of OOP in C++ and some math skills. Even if you're not confident about your math, give the video a go. You may find it fun. </p>
<p>If you like this one and want to learn more, the same instructor has another video on the advanced parts of OpenGL</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/GJFHqK_-ARA" 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>
<p>In this one you'll learn a lot more advanced stuff about OpenGL and you'll need an understanding of the topics covered in the previous videos.</p>
<p>There is another instructor <strong>Etay Meiri</strong> who has created a really cool course on OpenGL on the freeCodeCamp YouTube channel.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/GZQkwx10p-8" 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>
<p>In this one, the instructor does an awesome job of teaching you how to implement skeletal animations using OpenGL. </p>
<p>But this video tackles some really advanced concepts so make sure that you have a good command of C++ and a mug of coffee nearby.</p>
<h3 id="heading-unreal-engine-in-5-hours">Unreal Engine in 5 Hours</h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/LsNW4FPHuZE" 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>
<p>If you think rendering graphics manually on screen is not your thing and you want to use your new C++ skills in another way, then this video will surely interest you.</p>
<p>In this 5 hour long video course from Awesome Tuts, you'll create three complete games from scratch using Unreal Engine and C++. Although the video uses Unreal Engine 4 and not 5, you should be able to carry your knowledge from this video to UE5 pretty effortlessly.</p>
<p>If you like this one and want more videos on UE and C++, there are two more from the same instructor.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/SOjZTmOMGcY" 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>
<p>In this one you'll learn to make an endless runner game like Subway Surfer or temple run using Unearl Engine 4 and C++.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/4HoJIgyclZ4" 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>
<p>If you're not into endless runners and want to create a first person shooter, the instructor also has a video on that.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I would like to thank you from the bottom of my heart for the time you've spent reading this article. I hope you've learned some valuable stuff from this article and always remember:</p>
<blockquote>
<p> “The only way to learn a new programming language is by writing programs in it.” -- Dennis Ritchie</p>
</blockquote>
<p>So keep applying what you're learning about C++, make whimsical projects, share them on GitHub, and you'll become a C++ wizard in no time. </p>
<p>I also have a personal blog where I write about random tech stuff, so if you're interested in something like that, checkout <a target="_blank" href="https://farhan.dev">https://farhan.dev</a>. If you have any questions or are confused about anything – or just want to get in touch – I'm available on <a target="_blank" href="https://twitter.com/frhnhsin">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Arch Linux Handbook – Learn Arch Linux for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ If you ask a group of developers what Linux is, most of them will probably say it's an open-source operating system. Those with more technical knowledge will probably call it a kernel. For me, though, Linux is not just an operating system or a kernel... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-install-arch-linux/</link>
                <guid isPermaLink="false">66b0ab397cd8dca6718a22b8</guid>
                
                    <category>
                        <![CDATA[ ArchLinux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Tue, 18 Jan 2022 15:15:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/Farhan-Arch-Linux-Mockup.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you ask a group of developers what Linux is, most of them will probably say it's an open-source operating system. Those with more technical knowledge will probably call it a kernel.</p>
<p>For me, though, Linux is not just an operating system or a kernel. For me, it's freedom. The freedom of putting together an operating system according to my needs, and that's where Arch Linux comes in.</p>
<p>According to their <a target="_blank" href="https://wiki.archlinux.org/title/Arch_Linux">wiki</a>,</p>
<blockquote>
<p>Arch Linux is an independently developed, x86-64 general-purpose GNU/Linux distribution that strives to provide the latest stable versions of most software by following a rolling-release model.   </p>
<p>The default installation is a minimal base system, configured by the user to only add what is purposely required.</p>
</blockquote>
<p>In other words, Arch Linux is a distribution optimized for x86-64 architecture targeted at experienced Linux users. It lets you have full responsibility and control over your system. </p>
<p>You'll get to choose what packages you want, the kernel (yes there are multiple), the boot-loader, the desktop environment, and so on.</p>
<p>Have you ever heard someone say,</p>
<blockquote>
<p>Oh – by the way, I use Arch Linux!</p>
</blockquote>
<p>This is because installing Arch Linux on a machine requires you to have proper knowledge of how different parts of a Linux distribution work. So running Arch Linux on your system is kind of a testament to your understanding of Linux.</p>
<p>Speaking from experience, installing Arch Linux is not very different from installing something like Fedora or Ubuntu. It's just that you have to go through the individual steps manually instead of having an installer do the things for you. But once you've gone through the process, you'll start to understand how the other distributions work in general.</p>
<p>In this article, I'll walk you through the entire process of installing and configuring Arch Linux on your machine. I'll also discuss some common tasks and troubleshooting tips near the end.</p>
<p>So come with me and I'll show you how deep the rabbit hole goes.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-some-assumptions-im-making">Some Assumptions I'm Making</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-bootable-arch-linux-usb-drive">How to Create a Bootable Arch Linux USB Drive</a></li>
<li><a class="post-section-overview" href="#heading-how-to-prepare-your-computer-for-installing-arch-linux">How to Prepare Your Computer for Installing Arch Linux</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-arch-linux">How To Install Arch Linux</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-set-the-console-keyboard-layout-and-font">How To Set the Console Keyboard Layout and Font</a></li>
<li><a class="post-section-overview" href="#heading-how-to-verify-the-boot-mode">How To Verify the Boot Mode</a></li>
<li><a class="post-section-overview" href="#heading-how-to-connect-to-the-internet">How To Connect to the Internet</a></li>
<li><a class="post-section-overview" href="#heading-how-to-update-the-system-clock">How To Update the System Clock</a></li>
<li><a class="post-section-overview" href="#heading-how-to-partition-the-disks">How To Partition the Disks</a></li>
<li><a class="post-section-overview" href="#heading-how-to-format-the-partitions">How To Format the Partitions</a></li>
<li><a class="post-section-overview" href="#heading-how-to-mount-the-file-systems">How To Mount the File Systems</a></li>
<li><a class="post-section-overview" href="#heading-how-to-configure-the-mirrors">How To Configure the Mirrors</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-arch-linux-base-system">How To Install Arch Linux Base System</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-configure-arch-linux">How To Configure Arch Linux</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-generate-the-fstab-file">How To Generate the Fstab File</a></li>
<li><a class="post-section-overview" href="#heading-how-to-login-to-the-newly-installed-system-using-arch-chroot">How To Login to The Newly Installed System Using Arch-Chroot</a></li>
<li><a class="post-section-overview" href="#heading-how-to-configure-the-time-zone">How To Configure the Time Zone</a></li>
<li><a class="post-section-overview" href="#heading-how-to-configure-the-localization">How To Configure the Localization</a></li>
<li><a class="post-section-overview" href="#heading-how-to-configure-the-network">How To Configure the Network</a></li>
<li><a class="post-section-overview" href="#heading-how-to-set-the-root-password">How To Set the Root Password</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-non-root-user">How To Create a Non-root User</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-microcode">How To Install Microcode</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-and-configure-a-boot-loader">How To Install and Configure a Boot Loader</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-install-xorg">How To Install Xorg</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-graphics-drivers">How To Install Graphics Drivers</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-a-desktop-environment">How To Install a Desktop Environment</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-install-gnome">How To Install GNOME</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-plasma">How To Install Plasma</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-finalize-the-installation">How To Finalize The Installation</a></li>
<li><a class="post-section-overview" href="#heading-how-to-switch-between-desktop-environments">How To Switch Between Desktop Environments</a></li>
<li><a class="post-section-overview" href="#heading-how-to-manage-packages-using-pacman">How To Manage Packages Using Pacman</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-install-packages-using-pacman">How To Install Packages Using Pacman</a></li>
<li><a class="post-section-overview" href="#heading-how-to-remove-packages-using-pacman">How To Remove Packages Using Pacman</a></li>
<li><a class="post-section-overview" href="#heading-how-to-upgrade-packages-using-pacman">How To Upgrade Packages Using Pacman</a></li>
<li><a class="post-section-overview" href="#heading-how-to-search-for-packages-using-pacman">How To Search for Packages Using Pacman</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-use-aur-in-arch-linux">How To Use AUR in Arch Linux</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-install-packages-using-a-helper">How To Install Packages Using a Helper</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-packages-manually">How To Install Packages Manually</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-troubleshoot-common-problems">How To Troubleshoot Common Problems</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-live-arch-iso-as-a-rescue-media">How To Use the Live Arch ISO as a Rescue Media</a></li>
<li><a class="post-section-overview" href="#heading-further-reading">Further Reading</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-some-assumptions-im-making">Some Assumptions I’m Making</h2>
<p>Before I jump into the core of the tutorial, I want to clarify a few things. To make this entire article approachable, I'm making the following assumptions about you and your system:</p>
<ul>
<li>You know about Arch Linux at a basic level<ul>
<li><a target="_blank" href="https://wiki.archlinux.org/title/Arch_Linux">Arch Linux</a></li>
<li><a target="_blank" href="https://wiki.archlinux.org/title/Frequently_asked_questions">Frequently asked questions</a></li>
<li><a target="_blank" href="https://wiki.archlinux.org/title/Arch_compared_to_other_distributions">Arch compared to other distributions</a></li>
</ul>
</li>
<li>Your computer is using UEFI and not BIOS</li>
<li>You have a USB drive large enough (4GB) to boot Linux from</li>
<li>You have some previous experience installing Linux (Ubuntu/Fedora)</li>
<li>You have enough space to install linux on your HDD or SSD</li>
</ul>
<p>That's pretty much it. If you have all of the above, you're good to go.</p>
<h2 id="heading-how-to-create-a-bootable-arch-linux-usb-drive">How to Create a Bootable Arch Linux USB Drive</h2>
<p>To download Arch Linux, head to <a target="_blank" href="https://archlinux.org/download/">https://archlinux.org/download/</a> and download the latest release (2022.01.01 as of this writing). The ISO should be around 870 megabytes in size.</p>
<p>Once downloaded, you'll need to put it in your USB. You can use the <a target="_blank" href="https://getfedora.org/en/workstation/download/">Fedora Media Writer</a> program to do that. Download and install the application on your system. Now connect your USB drive and open the application:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/image-48.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click on "Custom image" and use the file browser to pick the downloaded Arch Linux ISO file.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/image-49.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The application will now let you pick one of your connected USB drives. Be very careful in selecting the right one if you have multiple USB drives connected to your machine. Now hit the "Write to Disk" button and wait until the process is finished.</p>
<h2 id="heading-how-to-prepare-your-computer-for-installing-arch-linux">How to Prepare Your Computer for Installing Arch Linux</h2>
<p>In this step you'll have to make a few changes to your system, otherwise Arch Linux may fail to boot or run properly.</p>
<p>The first change that you'll have to make is disabling secure boot in your UEFI configuration. This feature helps prevent malware attacks during boot but it also prevents the Arch Linux installer from booting. </p>
<p>Detailed instructions on how you can disable this vary depending on your motherboard or laptop brand. You'll have to search the internet yourself to find the right way this time.</p>
<p>The second thing that you should disable is only relevant if you're installing Arch Linux alongside Windows. There is a Windows feature called fast startup that reduces the boot time of your computer by partially hibernating it.</p>
<p>This is generally a nice feature to have but it prevents any other operating system in a dual boot configuration from accessing the hard disk in the process.</p>
<p>To disable this feature, open the start menu and search for "Choose a power plan" as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/choose-a-power-plan.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Then on the next window, click on "Choose what the power buttons do" from the left sidebar:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/image-54.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Then on the next window you'll see a list of "Shutdown settings" and the "Turn on fast startup (recommended)" option should be shown as read only there.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/image-55.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click the "Change settings that are currently unavailable" at the top and you should then be able to change the settings.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/image-56.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Untick the "Turn on fast startup (recommended)" option and press the "Save changes" button at the bottom. From now on the boot process may take a few moments extra but it's all worth it.</p>
<p>In this article, I'll install Arch Linux as my default operating system. So I'll allocate my entire disk space to it. </p>
<p>If you're trying to install it alongside Windows, however, I have a dedicated <a target="_blank" href="https://www.freecodecamp.org/news/how-to-dual-boot-any-linux-distribution-with-windows/">article</a> on the topic. And in that article, there is a <a target="_blank" href="https://www.freecodecamp.org/news/how-to-dual-boot-any-linux-distribution-with-windows/#how-to-create-additional-partitions-for-installing-linux">section</a> that discusses the partitioning process in great detail.</p>
<h2 id="heading-how-to-install-arch-linux">How To Install Arch Linux</h2>
<p>Assuming that you have a bootable USB drive and your computer is configured properly, you'll have to boot from the USB drive. The process of booting from a USB drive differs from machine to machine.</p>
<p>On my machine, hitting the F12 key during boot takes me to the list of bootable devices. From there I can pick my bootable USB drive. You may already know the appropriate technique for your computer or you may have to research a bit.</p>
<p>Once you've managed to land on the list of connected bootable devices, select your USB drive to boot from and the following menu should show up:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_12_01_2022_18_39_29.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Choose the first one from the list and wait until the Arch installer finishes booting up. Once fully booted up, you'll see something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_12_01_2022_18_50_39.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>That's it. That's all you'll get. Unlike other operating systems that you maybe familiar with, the Arch installer doesn't have any graphical user interface to automate the installation.</p>
<p>It rather requires you to invest your time and effort and configure each part of the distribution piece by piece. It may sound daunting but, to be honest, if you understand what you're doing, installing Arch Linux is quite fun.</p>
<h3 id="heading-how-to-set-the-console-keyboard-layout-and-font">How To Set the Console Keyboard Layout and Font</h3>
<p>As I've already said, the Arch installer doesn't have a graphical user interface so there's going to be a lot of typing. Configuring your keyboard layout and a nice looking font can make the installation process a lot less frustrating.</p>
<p>By default, the console assumes that you have a standard US keyboard layout. This should be fine for most people but just in case if you happen to have a different one, you can change to that.</p>
<p>All the available keymaps are usually kept inside the <code>/usr/share/kbd/keymaps</code> directory in the form of <code>map.gz</code> files. You can see the list of them by using the <code>ls</code> command:</p>
<pre><code class="lang-bash">ls /usr/share/kbd/keymaps/**/*.map.gz
</code></pre>
<p>This will list out all the available key maps:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_15_58_28-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now for example, if you have the Mac-US keyboard layout, locate the corresponding <code>map.gz</code> file from this list which is the <code>mac-us.map.gz</code> one.</p>
<p>You can use the <code>loadkeys</code> command to load the desired keymap. To set <code>mac-us.map.gz</code> as default, execute the following command:</p>
<pre><code class="lang-bash">loadkeys mac-us
</code></pre>
<p>You can also change the console font if you don't like the default one. Just like the keymaps, the console fonts are kept inside the <code>/usr/share/kbd/consolefonts</code> which you can list out using the <code>ls</code> command:</p>
<pre><code class="lang-bash">ls /usr/share/kbd/consolefonts
</code></pre>
<p>This will list out all the available fonts:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_16_08_01.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can now use the <code>setfont</code> command for setting one of these. For example, if you want to set the <code>drdos8x16</code> as default, execute the following command:</p>
<pre><code class="lang-bash">setfont drdos8x16
</code></pre>
<p>Both the <code>loadkeys</code> and <code>setfont</code> commands are part of the <code>kbd</code> package containing essential Linux keyboard tools. They have great <a target="_blank" href="https://kbd-project.org/#documentation">documentation</a> so if you'd like to learn more, feel free to check it out.</p>
<h3 id="heading-how-to-verify-the-boot-mode">How To Verify the Boot Mode</h3>
<p>Now that you have your console configured, the next step is to make sure that you've booted in UEFI mode and not in BIOS mode.</p>
<p>To be honest, this step seems unnecessary to me since it literally says <code>x86_64 UEFI</code> in the live boot menu. But let's do it for the sake of the official Arch <a target="_blank" href="https://wiki.archlinux.org/title/installation_guide#Verify_the_boot_mode">installation guide</a>.</p>
<p>To verify the boot mode, execute the following command:</p>
<pre><code class="lang-bash">ls /sys/firmware/efi/efivars
</code></pre>
<p>If you're in UEFI mode then, it will list out a bunch of files on your screen:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_17_18_34.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In case of a BIOS boot, the <code>efi</code> directory won't even exist inside the <code>/sys/firmware</code> directory. If you're in UEFI mode, (which you should be if you've followed everything properly) continue to the next step.</p>
<h3 id="heading-how-to-connect-to-the-internet">How To Connect to the Internet</h3>
<p>Unlike a lot of other live distributions, the Arch live environment doesn't come with all necessary packages built into it. It contains a number of bare minimum packages that you can use to install the rest of the system. So, a working internet connection is a must.</p>
<p>If you're using a wired network then you should have a working internet connection from the get go. To test it out, ping any of the public addresses out there:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_17_40_04.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I'm making these screenshots using VirtualBox, so the internet connection works perfectly with the wired connection. But if you have a wireless connection, things can get a bit tricky.</p>
<p>The live environment comes with the <code>iwd</code> or <a target="_blank" href="https://wiki.archlinux.org/title/Iwd">iNet wireless daemon</a> package. You can use this package to connect to a nearby wireless network.</p>
<p>To begin with, execute the following command:</p>
<pre><code class="lang-bash">iwctl
</code></pre>
<p>This will start an interactive prompt as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_17_59_34.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now execute the following command to see the list of available wireless devices:</p>
<pre><code class="lang-bash">device list
</code></pre>
<p>This will spit out a list of available wireless devices. By wireless devices I mean any wireless adapter connected to your computer. Let's assume <code>wlan0</code> is the device name.</p>
<p>To scan for nearby wireless networks using the found device, execute the following command:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># station &lt;device&gt; scan</span>

station wlan0 scan
</code></pre>
<p>You may think that this command will print out a list of all the nearby networks, but that's not the case. To see the list of networks, execute the following command:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># station &lt;device&gt; get-networks</span>

station wlan0 get-networks
</code></pre>
<p>Now assuming the name of your home network is called <code>Skynet</code>, you can connect to it by executing the following command:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># station &lt;device&gt; connect &lt;SSID&gt;</span>

station wlan0 connect Skynet
</code></pre>
<p>The <code>iwctl</code> program will prompt you for the wi-fi password. Put it in carefully and, once connected to the network, exit the program by writing <code>exit</code> and hitting enter. Try pinging a public address once again and make sure that the internet is working fine.</p>
<h3 id="heading-how-to-update-the-system-clock">How To Update the System Clock</h3>
<p>In Linux, NTP or Network Time Protocol is used for synchronizing computer system clocks over a network. You can use the <code>timedatectl</code> command to enable NTP on your Arch live environment:</p>
<pre><code class="lang-bash">timedatectl set-ntp <span class="hljs-literal">true</span>
</code></pre>
<p>This command will start outputting some output and after a few seconds. If you do not see the command cursor show up again, try pressing Enter. I've faced this inconvenience a few times in the past.</p>
<h3 id="heading-how-to-partition-the-disks">How To Partition the Disks</h3>
<p>This is probably the most sensitive step of the entire installation process – because if you mess up your partitions, you lose your precious data. So my advice would be to not immediately follow along with this section. Instead, read the whole section first and then follow along.</p>
<p>To begin the partitioning process, you'll have to first know about the different disks connected to your computer. You can use <code>fdisk</code> which is a dialog-driven program for creation and manipulation of partition tables.</p>
<pre><code class="lang-bash">fdisk -l
</code></pre>
<p>This command will list the partition tables for all the available devices on your computer.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_19_53_34.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you can see, there are two devices connected to my computer (virtual machine actually). Depending on the number of devices you have, this list can be longer so ignore any device ending with <code>rom</code>, <code>loop</code>, or <code>airoot</code> when reviewing the list. You can not use those devices for the installation.</p>
<p>So that leaves us with the <code>/dev/sda</code> device. Keep in mind that this can be completely different on your machine. For example, if you have an NVME drive, you may see <code>/dev/nvme0n1</code> instead.</p>
<p>Once you've decided which device to use, it's a good idea to check if there are any existing partitions inside that device. To do so, you can use the following variation of the same <code>fdisk</code> command:</p>
<pre><code class="lang-bash">fdisk /dev/sda -l
</code></pre>
<p>Remember to replace <code>/dev/sda</code> with what you have. This command will list out all the partitions inside the given device.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_13_14.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Although there are no partitions in this device, in a real life situation you may have previously created partitions. Those partitions will show up as <code>/dev/sda1</code>, <code>/dev/sda2</code> or in the case of a NVME drive <code>/dev/nvme0n1p1</code>, <code>/dev/nvme0n1p2</code> and so on.</p>
<p>The <code>fdisk</code> program can do a lot more than just listing partitions. Consult the <a target="_blank" href="https://wiki.archlinux.org/title/Fdisk">corresponding ArchWiki page</a> to know about the tasks you can perform using this program.</p>
<p>There is another program <code>cfdisk</code> which is a <a target="_blank" href="https://en.wikipedia.org/wiki/Curses_(programming_library)">curses- (programming library)</a> based disk partition table manipulator for Linux. It's similar in functionality with <code>fdisk</code> but being curses-based means it has an interface which makes it easier to work with. </p>
<p>Execute the following command to start <code>cfdisk</code> on your preferred device:</p>
<pre><code class="lang-bash">cfdisk /dev/sda
</code></pre>
<p>Remember to replace <code>/dev/sda</code> with what you have. If the device has a previously created partition table, then <code>cfdisk</code> will directly show the list of partitions. Otherwise you'll get to choose a partition table type to begin with:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_22_55.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Choose <code>gpt</code> for your UEFI based system. Next, you'll land on the list of partitions and free space on the device:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_24_09.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can move vertically along the list of devices using your up/down arrow keys and move horizontally along the different actions using the left/right arrow keys.</p>
<p>To install Arch, or any other Linux distribution, you'll need three separate partitions. They are as follows:</p>
<ul>
<li>EFI system partition – for storing files required by the UEFI firmware.</li>
<li>ROOT – for installing the distribution itself.</li>
<li>SWAP – for serving as the overflow space for your RAM.</li>
</ul>
<p>Make sure the right partition/free space is highlighted in the list and select the <code>[ New ]</code> action.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_37_04.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Put the desired partition size. You can use M to denote megabytes, G for gigabytes, and T for terabytes.</p>
<p>For an EFI system partition, you should allocate at least 500MB. Once you've put your desire size, press Enter to finalize. The updated list of partitions may look as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_37_29.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The EFI system partition is a special type of partition. It has to be in a specific type and format. To change the default type, keep the newly created partition highlighted and select <code>[ Type ]</code> from the list of actions.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_39_24.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>From this long list of types, highlight <code>EFI System</code> and press Enter. The type of the partition in the list should update accordingly:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_40_37.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Next is the root partition. Highlight the remaining free space and select <code>[ New ]</code> once again. This time assign 10GB to this partition. The ideal size of the root partition depends on your necessities. Personally I allocate at least 100GB to the root partition of all my Linux installations.</p>
<p>You don't need to change the type of this partition. The default <code>Linux filesystem</code> will do.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_43_14.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Create one last partition with the remaining space and change its type to <code>Linux swap</code> from the menu:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_45_57.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The ideal size of a swap partition is a matter of debate. Personally I don't have swap partitions on my machines. The amount of physical RAM I have is more than enough. But if I ever feel the need for one later on, I use a <code>swapfile</code> instead. Anyways, the final state of your device should be as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_20_48_49.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you're happy with the set-up, highlight <code>[ Write ]</code> from the action list and hit Enter. The program will ask whether you want to persist these changes or not. You'll have to write <code>yes</code> and press enter if you agree. Once the partition table has been altered, select <code>[ Quit ]</code> to exit from the program.</p>
<p>One thing that I would like to mention for those trying to install Arch Linux alongside Windows is, in that case, the EFI system partition should already exist in your device. So don't touch that. Just create the other partitions and move on.</p>
<h3 id="heading-how-to-format-the-partitions">How To Format the Partitions</h3>
<p>Now that you've created the necessary partitions, you'll have to format them accordingly. You can use the <code>mkfs</code> and <code>mkswap</code> programs to do that. Before the formatting, take a final look at your partition list by executing the following command:</p>
<pre><code class="lang-bash">fdisk /dev/sda -l
</code></pre>
<p>This time you'll see the three newly created partitions with their details:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_21_02_23.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Take note of the device names, like <code>/dev/sda1</code>, <code>/dev/sda2</code>, <code>/dev/sda3</code> and so on. The EFI system partition has to be in FAT32 format. Execute the following command to format a partition in FAT32 format:</p>
<pre><code class="lang-bash">mkfs.fat -F32 /dev/sda1
</code></pre>
<p>The next one is the root partition. It can be in a number of formats, but I prefer using EXT4 for all of my Linux filesystems. Use the following command to format the partition in EXT4:</p>
<pre><code>mkfs.ext4 /dev/sda2
</code></pre><p>This operation may take a few moments to finish depending on your partition size. Finally, the swap partition. Use the following command to format that:</p>
<pre><code class="lang-bash">mkswap /dev/sda3
</code></pre>
<p>With that, you've finished the process of preparing your partitions for the installation.</p>
<h3 id="heading-how-to-mount-the-file-systems">How To Mount the File Systems</h3>
<p>Now that you've created and formatted your partitions, you're ready mount them. You can use the <code>mount</code> command with appropriate mount points to mount any partition:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># mount &lt;device&gt; &lt;mount point&gt;</span>

mount /dev/sda2 /mnt
</code></pre>
<p>I hope you remember that the <code>/dev/sda2</code> partition was created to be the root partition. The <code>/mnt</code> mount point in Linux is for mounting a storage device temporarily. As we only need to mount the partition for installing Arch Linux on it, the <code>/mnt</code> mount point is perfect.</p>
<p>In the case of a swap partition, you won't mount it like the other ones. You'll have to tell Linux to use this partition as swap explicitly. To do so, execute the following command:</p>
<pre><code class="lang-bash">swapon /dev/sda3
</code></pre>
<p>As you may have guessed, the <code>swapon</code> command tells the system to swap on this device. We'll work with the EFI system partition in a later section. For now, mounting these two partitions will suffice.</p>
<h3 id="heading-how-to-configure-the-mirrors">How To Configure the Mirrors</h3>
<p>There is one last step before you can install Arch Linux on your machine, and that is configuring the mirrors. Mirrors are servers located at different pointes around the world for serving the nearby population.</p>
<p>The installer comes with Reflector, a Python script written for retrieving the latest mirror list the <a target="_blank" href="https://archlinux.org/mirrors/status/">Arch Linux Mirror Status</a> page. To print out the latest mirror list, simply execute the following command:</p>
<pre><code class="lang-bash">reflector
</code></pre>
<p>If you have a slow internet connection, you may encounter an error message as follows:</p>
<pre><code class="lang-bash">failed to rate http(s) download (https://arch.jensgutermuth.de/community/os/x86_64/community.db): Download timed out after 5 second(s).
</code></pre>
<p>This happens when the default timeout (5 seconds) is lower than the actual time it's taking to download the information.</p>
<p>You can remedy to this problem by using the <code>--download-timeout</code> option:</p>
<pre><code class="lang-bash">reflector --download-timeout 60
</code></pre>
<p>Now reflector will wait for a whole minute before starting to scream. A long list of mirrors should show up on your screen:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_21_36_15-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Going through the entire list to find nearby mirrors would be a pain. That's why reflector can do that for you.</p>
<p>Reflector can generate a list of mirrors based on a plethora of given constraints. For example, I want a list of mirrors that were synchronized within the last 12 hours and that are located either in India or Singapore (these two are closest to my location), and sort the mirrors by download speed.</p>
<p>Turns out, reflector can do that:</p>
<pre><code class="lang-bash">reflector --download-timeout 60 --country India,Singapore --age 12 --protocol https --sort rate
</code></pre>
<p>The found servers will be listed like before:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_21_45_25.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Printing out a mirror list like this is not enough. You'll have to persist the list in the <code>/etc/pacman.d/mirrorlist</code> location. Pacman, the default package manager for Arch Linux, uses this file to learn about the mirrors.</p>
<p>Before overwriting the default mirror list, make a copy of it:</p>
<pre><code class="lang-bash">cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak
</code></pre>
<p>Now execute the reflector command with the <code>--save</code> option as follows:</p>
<pre><code class="lang-bash">reflector --download-timeout 60 --country India,Singapore --age 12 --protocol https --sort rate --save /etc/pacman.d/mirrorlist
</code></pre>
<p>This command will generate the mirror list and overwrite the default one. Now you're ready to install the base Arch Linux system.</p>
<h3 id="heading-how-to-install-arch-linux-base-system">How To Install Arch Linux Base System</h3>
<p>Before installing the base system, it's a good idea to update the package cache according to the new mirror list. To do so, execute the following command:</p>
<pre><code class="lang-bash">pacman -Sy
</code></pre>
<p>The <code>pacman</code> program to Arch Linux is what <code>apt</code> is to Ubuntu or <code>dnf</code> is to Fedora. The <code>-S</code> option means sync which is equivalent to <code>install</code> in <code>apt</code> or <code>dnf</code> package managers.</p>
<p>Once the update process is finished, you can use the <code>pacstrap</code> script to install the Arch Linux system. Execute the following command to start the installation process:</p>
<pre><code class="lang-bash">pacstrap /mnt base base-devel linux linux-firmware sudo nano ntfs-3g networkmanager
</code></pre>
<p>The <code>pacstrap</code> script can install packages to a specified new root directory. As you may remember, the root partition was mounted on the <code>/mnt</code> mount point, so that's what you'll use with this script. Then you'll pass the package names you want to install:</p>
<ul>
<li><code>base</code> – Minimal package set to define a basic Arch Linux installation.</li>
<li><code>base-devel</code> – Group of packages required for building software from source.</li>
<li><code>linux</code> – The kernel itself.</li>
<li><code>linux-firmware</code> – Drivers for common hardware.</li>
<li><code>sudo</code> – You want to run commands as root right?</li>
<li><code>nano</code> – A pico editor clone with some enhancements.</li>
<li><code>ntfs-3g</code> – NTFS filesystem driver and utilities required for working with NTFS drives.</li>
<li><code>networkmanager</code> – Provides detection and configuration for systems to automatically connect to networks.</li>
</ul>
<p>I would like to clarify that this list of seven packages is not something mandatory. To have a functional Arch Linux installation, you just need the <code>base</code>, <code>linux</code>, and <code>linux-firmware</code> packages. But considering you'll need the other ones anyway, why not catch 'em all in one go.</p>
<p>Depending on your internet connection, the installation process may take a while. Sit back and relax until <code>pacstrap</code> does its thing. Once it's done, you'll see something as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_22_57_54.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Congratulations, you've successfully installed Arch Linux on your computer. All that is left to do now is configuring the system.</p>
<h2 id="heading-how-to-configure-arch-linux">How To Configure Arch Linux</h2>
<p>Installing Arch Linux wasn't that hard right? In fact in my opinion, installing it is way more straightforward than configuring it. There is a lot to do here. So let's get started.</p>
<h3 id="heading-how-to-generate-the-fstab-file">How To Generate the Fstab File</h3>
<p>According to the <a target="_blank" href="https://wiki.archlinux.org/title/Fstab">ArchWiki</a>,</p>
<blockquote>
<p>The <code>fstab</code> file can be used to define how disk partitions, various other block devices, or remote file systems should be mounted into the file system.</p>
</blockquote>
<p>In other distributions like Ubuntu or Fedora this gets generated automatically during the installation. On Arch however, you'll have to do it manually. To do so, execute the following command:</p>
<pre><code class="lang-bash">genfstab -U /mnt &gt;&gt; /mnt/etc/fstab
</code></pre>
<p>The <code>genfstab</code> program can detect all the current mounts below a given mount point and print them in fstab-compatible format to standard output. So <code>genfstab -U /mnt</code> will output all current mounts under the <code>/mnt</code> mount point. We can save that output to the <code>/mnt/etc/fstab</code> file using the <code>&gt;&gt;</code> operator.</p>
<h3 id="heading-how-to-login-to-the-newly-installed-system-using-arch-chroot">How To Login to The Newly Installed System Using Arch-Chroot</h3>
<p>Right now you're logged into the live environment and and not into your newly installed system. </p>
<p>To continue configuring your newly installed system, you'll have to first log into it. To do so, execute the following command:</p>
<pre><code class="lang-bash">arch-chroot /mnt
</code></pre>
<p>The <code>arch-chroot</code> bash script is part of the <code>arch-install-scripts</code> package and lets you change to the newly installed system's <code>root</code> user without any reboot. How cool is that!</p>
<h3 id="heading-how-to-configure-the-time-zone">How To Configure the Time Zone</h3>
<p>Once you've switched root, the first thing to configure is the time zone. To see a list of all the available zones, execute the following command:</p>
<pre><code class="lang-bash">ls /usr/share/zoneinfo
</code></pre>
<p>All the major zones should be in the directory.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_23_45_19.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I live in Dhaka, Bangladesh which resides inside the Asia zone. If I list out the content of Asia, I should see Dhaka there:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_23_45_44.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To set Asia/Dhaka as my default time zone, I'll have to make a symbolic link of the file at the <code>/etc/localtime</code> location:</p>
<pre><code class="lang-bash">ln -sf /usr/share/zoneinfo/Asia/Dhaka /etc/localtime
</code></pre>
<p>The <code>ln</code> command is used for creating symbolic links. The <code>-sf</code> options indicate soft and force, respectively.</p>
<h3 id="heading-how-to-configure-the-localization">How To Configure the Localization</h3>
<p>Now you'll have to configure your languages. Arch Linux has an easy way to set that up as well. </p>
<p>First, you'll have to edit the <code>etc/locale.gen</code> file according to your localization. Open the file in the nano text editor:</p>
<pre><code class="lang-bash">nano /etc/locale.gen
</code></pre>
<p>You'll see a long list of languages:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_23_46_29.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You'll have to uncomment the languages that you want to enable. I usually only need English and Bengali. So I'll locate the <code>en_US.UTF-8 UTF-8</code>, <code>bn_BD UTF-8</code>, and <code>bn_IN UTF-8</code> languages. Save the file by pressing Ctrl + O and exit nano by pressing the Ctrl + X key combination.</p>
<p>Now you'll have to execute the following command:</p>
<pre><code class="lang-bash">locale-gen
</code></pre>
<p>The <code>locale-gen</code> command will read your <code>/etc/locale.gen</code> file and generate the locales accordingly.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_13_01_2022_23_57_55.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now that you've enabled multiple languages, you'll have to tell Arch Linux which one to use by default. To do so, open the <code>/etc/locale.conf</code> file and add the following line to it:</p>
<pre><code class="lang-conf">LANG=en_US.UTF-8
</code></pre>
<p>That's all you gotta do to configure your locale. You can always go back to the <code>/etc/locale.gen</code> file and add or remove languages from it. Just remember to run <code>locale-gen</code> whenever you do that.</p>
<p>Apart from the locales, if you've made any changes to your console keymaps in the first step of installation, you may want to persist them now. To do so, open the <code>/etc/vconsole.conf</code> file and add your preferred keymaps there.</p>
<p>For example, if you changed the default keymaps to <code>mac-us</code> in the first step, then you may want to add the following line to the <code>vconsole.conf</code> file:</p>
<pre><code class="lang-bash">KEYMAP=mac-us
</code></pre>
<p>Now every time you use the virtual console, it'll have the correct keymap and you will not have to configure it every time.</p>
<h3 id="heading-how-to-configure-the-network">How To Configure the Network</h3>
<p>Configuring a network manually in any Linux distribution can be tricky. That's why I advised you to install the <code>networkmanager</code> package during the system installation. If you did as I said, you're good to go. Otherwise, use <code>pacman</code> to install the package now:</p>
<pre><code class="lang-bash">pacman -S networkmanager
</code></pre>
<p>Pacman is a package manager. You'll learn more about it later. Let's set the host name for your computer now. A host name is a unique name created to identify a machine on a network, written in the <code>/etc/hostname</code> file.</p>
<p>Open the file with nano and write your host name in it. You can use anything to identify your machine. I usually use my device brand or model as my hostname and as I'm on a legion laptop, I'll simply write the following:</p>
<pre><code>legion
</code></pre><p>Local host name resolution is provided by <code>nss-myhostname</code> (an NSS module provided by systemd) without having to edit <code>/etc/hosts</code> file. It is enabled by default.</p>
<p>But some software may still read the <code>/etc/hosts</code> file directly. Open the file in nano and add the following lines to it:</p>
<pre><code><span class="hljs-number">127.0</span><span class="hljs-number">.0</span><span class="hljs-number">.1</span>        localhost
::<span class="hljs-number">1</span>              localhost
<span class="hljs-number">127.0</span><span class="hljs-number">.1</span><span class="hljs-number">.1</span>        legion
</code></pre><p>Make sure to replace <code>legion</code> with your host name. Now you may install the aforementioned package:</p>
<pre><code class="lang-bash">pacman -S networkmanager
</code></pre>
<p>Enable the <code>NetworkManager</code> service by executing the following command:</p>
<pre><code class="lang-bash">systemctl <span class="hljs-built_in">enable</span> NetworkManager
</code></pre>
<p>Make sure to write <code>NetworkManager</code> and not <code>networkmanager</code> as the service name. If the command succeeds, network manager will start automatically on boot from now on and do its thing.</p>
<h3 id="heading-how-to-set-the-root-password">How To Set the Root Password</h3>
<p>You may want to set a password for the root user because why not? To do so, execute the following command:</p>
<pre><code class="lang-bash">passwd
</code></pre>
<p>The <code>passwd</code> command lets you change the password for a user. By default it affects the current user's password which is the <code>root</code> right now.</p>
<p>It'll ask for a new password and confirmation password. Input them carefully and make sure you don't forget the password.</p>
<h3 id="heading-how-to-create-a-non-root-user">How To Create a Non-root User</h3>
<p>Using your Linux system as the root user for long is not a good idea. So creating a non-root user is important. To create a new user, execute the following command:</p>
<pre><code class="lang-bash">useradd -m -G wheel farhan
</code></pre>
<p>The <code>useradd</code> command lets you create a new user. Make sure to replace my name with the one you want to use. The <code>-m</code> option indicates that you also want it to create the corresponding home directory. The <code>-G</code> option will add the new user to the <code>wheel</code> group which is the administration user group in Arch Linux.</p>
<p>Now you can use the <code>passwd</code> command once again to set the password for the newly created user:</p>
<pre><code class="lang-bash">passwd farhan
</code></pre>
<p>The program will prompt you for a new password and a password confirmation. Again, don't forget to replace my name with the one you've used.</p>
<p>Finally, you'll have to enable <code>sudo</code> privilege for this new user. To do so, open the <code>/etc/sudoers</code> file using nano. Once open, locate the following line and uncomment it:</p>
<pre><code># %wheel ALL=(ALL) ALL
</code></pre><p>This file essentially means that all users in the <code>wheel</code> group can use <code>sudo</code> by providing their password. Save the file by hitting Ctrl + O and exit nano by hitting Ctrl + X. Now the new user will be able to use <code>sudo</code> when necessary.</p>
<h3 id="heading-how-to-install-microcode">How To Install Microcode</h3>
<p>According to <a target="_blank" href="https://www.pcmag.com/encyclopedia/term/microcode">PCMag</a>,</p>
<blockquote>
<p>A set of elementary instructions in a complex instruction set computer (CISC). The microcode resides in a separate high-speed memory and functions as a translation layer between the machine instructions and the circuit level of the computer. Microcode enables the computer designer to create machine instructions without having to design electronic circuits.</p>
</blockquote>
<p>Processor manufacturers such as Intel and AMD often release stability and security updates to the processor. These updates are crucial for the system's stability. </p>
<p>In Arch Linux, microcode updates are available through official packages that every user should install on their systems.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># for amd processors</span>
pacman -S amd-ucode

<span class="hljs-comment"># for intel processors</span>
pacman -S intel-ucode
</code></pre>
<p>Just installing these packages is not enough though. You'll have to make sure that your bootloader is loading them. You'll learn about it in the next section.</p>
<h3 id="heading-how-to-install-and-configure-a-boot-loader">How To Install and Configure a Boot Loader</h3>
<p>According to <a target="_blank" href="https://en.wikipedia.org/wiki/Bootloader">Wikipedia</a>,</p>
<blockquote>
<p>A bootloader, also spelled as boot loader or called boot manager and bootstrap loader, is a computer program that is responsible for booting a computer.</p>
</blockquote>
<p>The internals of bootloader is out of scope of this article so I'll just go on with the installation process. If you've used any other Linux distribution in the past you may have encountered the GRUB menu.</p>
<p>GRUB is one of the most popular bootloaders out there. Although there are a number of options available, I'll demonstrate the installation of GRUB because it is what most people will likely use.</p>
<p>To install GRUB, you'll have to first install two packages.</p>
<pre><code class="lang-bash">pacman -S grub efibootmgr
</code></pre>
<p>If you're installing alongside other operating systems, you'll also need the <code>os-prober</code> package:</p>
<pre><code class="lang-bash">pacman -S os-prober
</code></pre>
<p>This program will search for already installed operating systems on your system and will make them a part of the GRUB configuration file. </p>
<p>Now, you'll have to mount the EFI system partition you created a few sections ago. To do so, you'll have to first create an <code>efi</code> directory:</p>
<pre><code class="lang-bash">mkdir /boot/efi
</code></pre>
<p>According to <a target="_blank" href="https://en.wikipedia.org/wiki//boot/">Wikipedia</a>,</p>
<blockquote>
<p>In Linux, and other Unix-like operating systems, the <code>/boot/</code> directory holds files used in booting the operating system.</p>
</blockquote>
<p>This directory is present in all Unix-like operating systems. The above mentioned command creates a directory called <code>efi</code> inside the <code>/boot</code> directory. After creating the directory, you'll have to mount your EFI system partition in that directory.</p>
<pre><code class="lang-bash">mount /dev/sda1 /boot/efi
</code></pre>
<p>I hope you remember that we formatted the <code>/dev/sda1</code> device as the EFI system partition during the partitioning phase. Make sure to use the correct one for your device. </p>
<p>Now, we'll use the <code>grub-install</code> command to install GRUB in the newly mounted EFI system partition:</p>
<pre><code class="lang-bash">grub-install --target=x86_64-efi --bootloader-id=grub
</code></pre>
<p>You can more or less use this command verbatim. You can change the <code>--bootloader-id</code> to something more expressive like <code>arch</code> or something else. If the installation finishes without any errors, you'll then have to generate the GRUB configuration file.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_18_34_01.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you're installing alongside other operating systems, you'll have to enable <code>os-prober</code> before generating the configuration file. To do so, open the <code>/etc/default/grub</code> file in nano text editor. Locate the following line and uncomment it:</p>
<pre><code>#GRUB_DISABLE_OS_PROBER=<span class="hljs-literal">false</span>
</code></pre><p>This should be the last line in the aforementioned file so just scroll to the bottom and uncomment it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_18_31_41.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now execute the following command to generate the configuration file:</p>
<pre><code class="lang-bash">grub-mkconfig -o /boot/grub/grub.cfg
</code></pre>
<p>The <code>grub-mkconfig</code> command generates the GRUB configuration file and saves it to a given target location. In this case <code>/boot/grub/grub.cfg</code> is the target location.</p>
<p>The command will also take into account the microcode you installed earlier and any other existing operating system on your machine.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_18_35_45.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Congratulations, you now have a working Arch Linux installation. At this point, you can exit the Arch-Chroot environment, unmount the partition, and reboot. But I would suggest you to stay a bit longer and set-up the graphical user interface as well.</p>
<h2 id="heading-how-to-install-xorg">How To Install Xorg</h2>
<p>To run programs with graphical user interfaces on your system, you'll have to install an X Window System implementation. The most common one is Xorg. </p>
<p>To install Xorg, execute the following command:</p>
<pre><code class="lang-bash">pacman -S xorg-server
</code></pre>
<p>Wait until the installation is done and then move on to installing the necessary graphics drivers.</p>
<h2 id="heading-how-to-install-graphics-drivers">How To Install Graphics Drivers</h2>
<p>Installing graphics drivers on Arch Linux is very straightforward. You just install the packages required by your graphics processing unit and call it a day.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># for nvidia graphics processing unit</span>
pacman -S nvidia nvidia-utils

<span class="hljs-comment"># for amd discreet and integrated graphics processing unit</span>
pacman -S xf86-video-amdgpu

<span class="hljs-comment"># for intel integrated graphics processing unit</span>
pacman -S xf86-video-intel
</code></pre>
<p>If you need further assistance, feel free to check the <a target="_blank" href="https://wiki.archlinux.org/title/Xorg">ArchWiki</a> page.</p>
<h2 id="heading-how-to-install-a-desktop-environment">How To Install a Desktop Environment</h2>
<p>Now that you've installed Xorg and the necessary graphics drivers, you're ready to install a desktop environment like GNOME, Plasma, or XFCE. </p>
<p>Arch Linux supports a long list of desktop environments but I've only tried out GNOME and Plasma. I'll demonstrate how you can install either of these two.</p>
<h3 id="heading-how-to-install-gnome">How To Install GNOME</h3>
<p>To install GNOME, you'll have to install the <code>gnome</code> package. To do so, execute the following command:</p>
<pre><code class="lang-bash">pacman -S gnome
</code></pre>
<p>During the installation, you'll be offered multiple choices for <code>pipwire-session-manager</code> and <code>emoji-font</code> packages. Accept the defaults by hitting Enter in both prompts. The installation may take some time to finish.</p>
<p>The <code>gnome</code> package comes with GDM or Gnome Display Manager. You can enable the service by executing the following command:</p>
<pre><code class="lang-bash">systemctl <span class="hljs-built_in">enable</span> gdm
</code></pre>
<p>That's all you need to do to get GNOME up and running on your Arch system.</p>
<h3 id="heading-how-to-install-plasma">How To Install Plasma</h3>
<p>The KDE Plasma installation is not that different from GNOME. You'll need to install Plasma related packages instead of GNOME.</p>
<pre><code class="lang-bash">pacman -S plasma plasma-wayland-session
</code></pre>
<p>If you have an NVIDIA graphics card, then avoid installing the <code>plasma-wayland-session</code> and use plain old X11. I own two devices with NVIDIA GPUs and both of them have shown instability when using Wayland.</p>
<p>During the installation, you'll get multiple choices for <code>ttf-font</code>, <code>pipwire-session-manager</code>, and <code>phonon-qt5-backend</code> packages. Make sure to pick <code>noto-fonts</code> as your <code>ttf-font</code> and accept the defaults for the other two.</p>
<p>Like <code>gdm</code> in GNOME, Plasma comes with <code>sddm</code> as the default display manager. Execute the following command to enable the service:</p>
<pre><code class="lang-bash">systemctl <span class="hljs-built_in">enable</span> sddm
</code></pre>
<p>And that's all you need to do to get Plasma up and running on your Arch Linux system.</p>
<h2 id="heading-how-to-finalize-the-installation">How To Finalize The Installation</h2>
<p>Now that you've installed Arch Linux and gone through all necessary configuration steps, you can reboot to your newly installed system. To do so, first come out of the Arch-Chroot environment:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">exit</span>
</code></pre>
<p>Next, unmount the root partition to make sure there are no pending operations:</p>
<pre><code class="lang-bash">umount -R /mnt
</code></pre>
<p>Now reboot the machine:</p>
<pre><code class="lang-bash">reboot
</code></pre>
<p>Wait until you see the GRUB menu.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_20_10_25.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Choose Arch Linux from the list and wait until the system finishes booting up.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_20_11_15.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Log in with your user credentials and voilà!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_20_15_41.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Your shiny new Arch Linux system is ready to do wonders.</p>
<h2 id="heading-how-to-switch-between-desktop-environments">How To Switch Between Desktop Environments</h2>
<p>Unlike other distributions coupled tightly with their default desktop environment, Arch is flexible. You can switch to another desktop environment whenever you feel like it. </p>
<p>To do so, first logout of your current session.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_20_11_15.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you can see, I'm currently using Plasma. Now switch to TTY2 press Ctrl + Alt + F2 key combination. You'll see a console login prompt:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_20_18_54.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Login with the root credentials and disable the <code>sddm</code> display manager.</p>
<pre><code class="lang-bash">systemctl <span class="hljs-built_in">disable</span> sddm
</code></pre>
<p>Then uninstall the Plasma related packages you installed earlier:</p>
<pre><code class="lang-bash">sudo pacman -Rns plasma plasma-wayland-session
</code></pre>
<p>Once the packages have been uninstalled, install the packages needed for GNOME:</p>
<pre><code class="lang-bash">pacman -S gnome
</code></pre>
<p>Then perform the installation according to the section you read earlier. After the <code>gnome</code> package has been installed, enable the <code>gdm</code> display manager:</p>
<pre><code class="lang-bash">systemctl <span class="hljs-built_in">enable</span> gdm
</code></pre>
<p>Restart the computer.</p>
<pre><code class="lang-bash">reboot
</code></pre>
<p>Wait until the Arch Linux system finishes booting.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_20_24_11.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Lo and behold, the gorgeous Gnome Display Manager. Login with your credentials.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_19_53_31.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can switch between the desktop environments as much as you want to, but I would suggest on settling down with one of them. Also, I wouldn't recommend having multiples of them installed at the same time.</p>
<h2 id="heading-how-to-manage-packages-using-pacman">How To Manage Packages Using Pacman</h2>
<p>You've already installed a number of packages using pacman. It's equivalent to package managers like apt in Ubuntu and dnf in Fedora.</p>
<p>In this section, I'll introduce you to some of the common pacman commands that you may need on a daily basis.</p>
<h3 id="heading-how-to-install-packages-using-pacman">How To Install Packages Using Pacman</h3>
<p>To install a package using pacman, you can use the following command syntax:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># sudo pacman -S &lt;package name&gt;</span>

sudo pacman -S rust
</code></pre>
<p>You can install multiple packages as follows:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># sudo pacman -S &lt;package name&gt; &lt;package name&gt;</span>

sudo pacman -S rust golang
</code></pre>
<p>You can also specify the repository you want to install the package from like this:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># sudo pacman -S &lt;package repository&gt;/&lt;package name&gt;</span>

sudo pacman -S extra/rust
</code></pre>
<p>In this command, the <code>-S</code> option means synchronize which is equivalent to install in the case of apt or dnf package managers.</p>
<h3 id="heading-how-to-remove-packages-using-pacman">How To Remove Packages Using Pacman</h3>
<p>To remove a package using pacman you can use the following syntax:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># sudo pacman -R &lt;package name&gt;</span>

sudo pacman -R rust
</code></pre>
<p>This will remove the package but will leave the dependencies. You can remove the package with dependencies if they're not required by any other package by executing the following command:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># sudo pacman -Rs &lt;package name&gt;</span>

sudo pacman -Rs rust
</code></pre>
<p>Pacman often saves important configuration files when removing certain applications. You can override this behavior by using the following syntax:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># sudo pacman -Rn &lt;package name&gt;</span>

sudo pacman -Rn rust
</code></pre>
<p>I usually use <code>sudo pacman -Rns</code> whenever I want to uninstall something. One last thing that I want to show is how to remove orphan packages.</p>
<p>In Ubuntu the <code>sudo apt autoremove</code> command uninstalls any unnecessary package. The equivalent command in Arch is:</p>
<pre><code class="lang-bash">sudo pacman -Qdtq | pacman -Rs -
</code></pre>
<p>This will cleanup any leftover package from previously installed packages.</p>
<h3 id="heading-how-to-upgrade-packages-using-pacman">How To Upgrade Packages Using Pacman</h3>
<p>To upgrade all the packages in your system, you can use the following syntax:</p>
<pre><code class="lang-bash">sudo pacman -Syu
</code></pre>
<p>In this command, the <code>S</code> option synchronizes the packages, <code>y</code> refreshes the local package cache, and <code>u</code> updates the system. This is like the ultimate upgrade command and I run it at least once everyday.</p>
<h3 id="heading-how-to-search-for-packages-using-pacman">How To Search for Packages Using Pacman</h3>
<p>To search for a package in the database, you can use the following syntax:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># sudo pacman -Ss &lt;package name&gt;</span>

sudo pacman -Ss rust
</code></pre>
<p>This will print out all the packages found in the database with that search term and will also indicate if any of those are already installed.</p>
<p>If you would like to check if a package is already installed or not, you can use the following command:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># sudo pacman -Qs &lt;package name&gt;</span>

sudo pacman -Qs rust
</code></pre>
<p>This is useful when you want to uninstall a package but do not know its exact name.</p>
<h2 id="heading-how-to-use-aur-in-arch-linux">How To Use AUR in Arch Linux</h2>
<p>According to <a target="_blank" href="https://itsfoss.com/aur-arch-linux/">It's FOSS</a>,</p>
<blockquote>
<p>AUR stands for Arch User Repository. It is a community-driven repository for Arch-based Linux distributions users. It contains package descriptions named PKGBUILDs that allow you to compile a package from source with makepkg and then install it via pacman (package manager in Arch Linux).</p>
</blockquote>
<p>AUR is one of the most attractive features of Arch Linux. It's due to AUR that Arch Linux has a package count almost equal to Debian. You've already used <code>pacman</code> to install various packages. Sadly, you can not use that to install packages from AUR.</p>
<p>You'll have to install one of the AUR helpers instead. Arch Linux doesn't support any of these helpers and advises you to learn how to build packages manually. I'll explain both techniques here. If you understand how a helper works, you'll be able to do it manually as well.</p>
<h3 id="heading-how-to-install-packages-using-a-helper">How To Install Packages Using a Helper</h3>
<p>Among the available and currently maintained AUR helpers, I like the <code>yay</code> or yet another yogurt package. It's written in Go and is quite solid. </p>
<p>You can not install <code>yay</code> like other packages. You'll have to get the source code and compile the program. You'll need <code>git</code> and the <code>base-devel</code> package to do so. Assuming you've already installed <code>base-devel</code> during Arch Linux installation:</p>
<pre><code class="lang-bash">pacman -S git
</code></pre>
<p>Clone the yay repository from GitHub and <code>cd</code> into it:</p>
<pre><code class="lang-bash">git <span class="hljs-built_in">clone</span> https://aur.archlinux.org/yay.git &amp;&amp; <span class="hljs-built_in">cd</span> yay
</code></pre>
<p>To build and install yay from source, execute the following command:</p>
<pre><code class="lang-bash">makepkg -si
</code></pre>
<p>The makepkg script automates the build process of packages. The <code>-si</code> options stand for sync dependencies and install. The first option will install required dependencies (Golang in this case) and the later option will install the built package.</p>
<p>After the build process finishes, makepkg will ask for installation confirmation and your password. Input your password carefully and let the installation finish.</p>
<p>Check if yay has been installed properly or not:</p>
<pre><code class="lang-bash">yay --version

<span class="hljs-comment"># yay v11.1.0 - libalpm v13.0.1</span>
</code></pre>
<p>Now let's install something using yay. One of the common packages you may want to install is the <a target="_blank" href="https://aur.archlinux.org/packages/visual-studio-code-bin/">visual-studio-code-bin</a> package. To do so, execute the following command:</p>
<pre><code class="lang-bash">yay -S visual-studio-code-bin
</code></pre>
<p>Unlike pacman, you shouldn't run yay with sudo. Yay will look for the given package and will ask whether you would like to see the diff or not:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_21_07_26.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>All the repositories over at AUR comes with a PKGBUILD file which contains the instructions for building this package. Yay has this nice feature where it shows you what has changed in the PKGBUILD file since the last time.</p>
<p>For now, I'll pick <code>N</code> for none and hit enter. Yay will now look for the dependencies and ask for your password to install them.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_21_19_58.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Confirm the installation and provide your password. Yay will then install the dependencies and start building the package. Once built, yay will install the package and prompt for your password where necessary.</p>
<p>After the installation finishes, search for Visual Studio Code in the application launcher:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_14_01_2022_21_28_42.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Congratulations on installing your first package from AUR. Yay commands are almost identical to pacman, so if you can do something with pacman, you should be able to do that with yay as well.</p>
<p>In fact, yay can also install packages from official Arch Linux repositories like pacman. But I would suggest you to use yay only for installing packages from AUR when necessary and pacman for everything else.</p>
<h3 id="heading-how-to-install-packages-manually">How To Install Packages Manually</h3>
<p>Like I said in the previous section, the ArchWiki suggests avoiding any AUR helper and installing packages from AUR manually. I'll now show you how to do it. </p>
<p>Make sure you have <code>git</code> and <code>base-devel</code> packages installed. If not, use <code>pacman</code> to install them.</p>
<p>For the demonstration, let's install Spotify this time. First visit the AUR page for the spotify package - <a target="_blank" href="https://aur.archlinux.org/packages/spotify/">https://aur.archlinux.org/packages/spotify/</a> and copy the "Git Clone URL" from there.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/image-68.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The page even lists all the dependencies you'll need. Clone the repository to your machine:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_16_01_2022_21_16_43.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Every AUR repository comes with a PKGBUILD file containing the instructions for building the package. Whenever you're installing a package from AUR, it's a great idea to checkout the PKGBUILD file using something like the <code>cat</code> command:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_16_01_2022_21_22_37.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Make sure there's nothing harmful in the file. Once you're satisfied, use <code>makepkg</code> to install any dependencies, build the package, and install it. Ideally there shouldn't be any issues but sometimes, things can take an unexpected turn.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_16_01_2022_21_34_29.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In these cases, go back to the corresponding AUR page and check the user comments. Like in this case, I found the following pinned comment:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/image-69.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Turns out the package requires you to add the Spotify for Linux gpg key to the user kyechain. This command downloads the gpg key using <code>curl</code> and pipes it as the input of the <code>gpg --import</code> command:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_16_01_2022_21_37_50.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Try executing <code>makepkg -si</code> once again and everything should work fine this time:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/01/VirtualBox_archlinux-2022.01.01-x86_64_16_01_2022_21_39_33.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>See, told ya! Manually installing packages often involves such troubleshooting but help is almost always around the comment corner. Let's enjoy some music now.</p>
<h2 id="heading-how-to-troubleshoot-common-problems">How To Troubleshoot Common Problems</h2>
<p>Look, I've been using Arch as my primary on all my devices for some years now but I still run into issues. Fortunately there are some great places to look for help when you're stuck:</p>
<ul>
<li><a target="_blank" href="https://wiki.archlinux.org/">ArchWiki</a></li>
<li><a target="_blank" href="https://bbs.archlinux.org/">Arch Linux Forum</a></li>
<li><a target="_blank" href="https://www.reddit.com/r/archlinux/">r/archlinux</a></li>
</ul>
<p>For the most part, the wiki should have the information you're looking for. In fact, if you're on a laptop and having difficulty getting something to work, there is an entire wiki <a target="_blank" href="https://wiki.archlinux.org/title/Category:Laptops">category</a> dedicated to different laptops. So look around the wiki.</p>
<p>If the wiki fails to solve your problem, then ask other fellow users at the forum as well as the subreddit. But whenever you're doing that, make sure to do your research first and include as much description as you can in the post. It's really annoying if other users have to keep asking you for more information and it'll also lower the chance that you'll get an answer.</p>
<h2 id="heading-how-to-use-the-live-arch-iso-as-a-rescue-media">How To Use the Live Arch ISO as a Rescue Media</h2>
<p>Whatever people may say, Arch Linux is very stable as long as you know what you're doing. If you go about installing every funky package you come across in the AUR or keep switching different kernels without knowing what they're for, your system may fail to boot.</p>
<p>In those cases, you can use your live USB drive as a rescue media. To do so, reconnect the bootable USB to your computer and boot into the live environment. Once there, configure the time, keymaps, and fonts if you want to.</p>
<p>Then use <code>fdisk</code> to list out all your partitions and locate the one holding your Arch Linux installation. In my case it's the <code>/dev/sda2</code> partition. Mount the partition like you did before:</p>
<pre><code class="lang-bash">mount /dev/sda2 /mnt
</code></pre>
<p>Now use Arch-Chroot to log in as the root user.</p>
<pre><code class="lang-bash">arch-chroot /mnt
</code></pre>
<p>Now uninstall the bad package you installed or go back to a kernel version that used to work in the past and so on. Once done, exit the Arch-Chroot environment, unmount the partition, and reboot:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">exit</span>
umount -R /mnt
reboot
</code></pre>
<p>If the computer boots fine then congratulations. Otherwise try the wiki, forum, or the subreddit. If nothing works, you may have to do a fresh install.</p>
<h2 id="heading-further-reading">Further Reading</h2>
<p>If you've come this far then you've done a lot of reading already – but that's not all. This entire handbook was written by combining information from the wiki, forum, and subreddit. I'm listing out some wiki pages that I think you should read.</p>
<ul>
<li><a target="_blank" href="https://wiki.archlinux.org/title/Installation_guide">Installation guide</a></li>
<li><a target="_blank" href="https://wiki.archlinux.org/title/Network_configuration">Network configuration</a></li>
<li><a target="_blank" href="https://wiki.archlinux.org/title/General_recommendations">General recommendation</a></li>
<li><a target="_blank" href="https://wiki.archlinux.org/title/Desktop_environment">Desktop environment</a></li>
<li><a target="_blank" href="https://wiki.archlinux.org/title/pacman">pacman</a></li>
<li><a target="_blank" href="https://wiki.archlinux.org/title/Arch_Build_System">Arch Build System</a></li>
<li><a target="_blank" href="https://wiki.archlinux.org/title/makepkg">makepkg</a></li>
<li><a target="_blank" href="https://wiki.archlinux.org/title/List_of_applications">List of applications</a></li>
</ul>
<p>Couldn't think of any more at the moment but I'll keep this list updated.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I would like to thank you from the bottom of my heart for the time you've spent on reading this article. I hope you've enjoyed your time and have learned a lot about not only Arch but Linux in general</p>
<p>Apart from this one, I've written full-length handbooks on other complicated topics available for free on <a target="_blank" href="https://www.freecodecamp.org/news/author/farhanhasin/">freeCodeCamp</a>.</p>
<p>These handbooks are part of my mission to simplify hard to understand technologies for everyone. Each of these handbooks takes a lot of time and effort to write.</p>
<p>If you've enjoyed my writing and want to keep me motivated, consider leaving starts on <a target="_blank" href="https://github.com/fhsinchy/">GitHub</a> and endorse me for relevant skills on <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>.</p>
<p>I'm always open to suggestions and discussions on <a target="_blank" href="https://twitter.com/frhnhsin">Twitter</a> or <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>. Hit me with direct messages.</p>
<p>In the end, consider sharing the resources with others, because</p>
<blockquote>
<p>In open source, we feel strongly that to really do something well, you have to get a lot of people involved. — Linus Torvalds</p>
</blockquote>
<p>Till the next one, stay safe and keep learning.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Dual Boot Any Linux Distribution With Windows – and Get Rid of It When You Need To ]]>
                </title>
                <description>
                    <![CDATA[ Gone are the days when Linux and Windows were like two opposing forces. Microsoft has embraced the open-source community quite cordially in recent years, and as a result we have things like Windows Subsystem for Linux baked right into our Windows ins... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-dual-boot-any-linux-distribution-with-windows/</link>
                <guid isPermaLink="false">66b0ab376a48f420e310e613</guid>
                
                    <category>
                        <![CDATA[ Linux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ubuntu ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Windows ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Thu, 23 Dec 2021 16:32:46 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/How-to-Dual-Boot-Any-Linux-Distribution-With-Windows.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Gone are the days when Linux and Windows were like two opposing forces. Microsoft has embraced the open-source community quite cordially in recent years, and as a result we have things like <a target="_blank" href="https://docs.microsoft.com/en-us/windows/wsl/">Windows Subsystem for Linux</a> baked right into our Windows installations.</p>
<p>That doesn't mean that we no longer need a full blown Linux installation. In fact, machines with both Windows and Linux running side by side are quite common.</p>
<p>But do you know what's more common than machines running both operating systems? Machine owners who have tried to dual boot their machines and ended up losing a lot of data in the process.</p>
<p>So if you're one of the victims or one of those who are trying to avoid possible disasters in their upcoming dual booting adventure, this article is for you. Here you'll learn about:</p>
<ul>
<li>How to install any Linux distribution alongside Windows</li>
<li>How to get rid of Linux without messing up Windows if necessary</li>
<li>Common problems, misconceptions, and their solutions, and</li>
<li>Some generally geeky stuff to impress you peers</li>
</ul>
<p>Without any further ado, let's grab a mug of coffee or tea or at least water and jump right into the process.</p>
<h2 id="heading-some-assumptions-im-making">Some Assumptions I’m Making</h2>
<p>Before I jump into the core of the tutorial, I want to clarify a few things. To make this entire article approachable, I'm making following assumptions about your system:</p>
<ul>
<li>Your computer is using UEFI and not BIOS</li>
<li>You already have Windows installed on your machine</li>
<li>You have a USB drive large enough (4GB) to boot Linux from</li>
<li>You have enough space (25GB) to install Linux on your HDD or SSD</li>
</ul>
<p>That's pretty much it. If you have all of the above ready, you're good to go.</p>
<h2 id="heading-how-to-create-a-bootable-linux-usb-drive">How to Create a Bootable Linux USB Drive</h2>
<p>There are multiple tools that can help you to create a bootable Linux USB drive. Among all these tools, my favorites are:</p>
<ul>
<li><a target="_blank" href="https://www.balena.io/etcher/">balenaEtcher</a></li>
<li><a target="_blank" href="https://getfedora.org/en/workstation/download/">Fedora Media Writer</a></li>
</ul>
<p>Both of these tools are open-source, free to use, and available on pretty much all major platforms. For this article, I'll go with Fedora Media Writer simply because there are not a lot of tutorials talking about it and because I use it personally.</p>
<p>Like the name suggests, Fedora Media Writer is a tool created by Red Hat for making bootable Linux USBs. Once you've downloaded the program, install it on your system and fire it up.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/fedora-media-writer.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is how it looks. As you can see, you've got the option to download the latest Fedora ISOs as well as an option to pick a custom image file from your drives.</p>
<p>Unless you're planning on installing Fedora (spoiler! it's my favorite) on your machine, you'll have to go ahead and download your desired ISO file. </p>
<p>In this article, I'll use <a target="_blank" href="https://ubuntu.com/">Ubuntu</a> because it's more popular among newcomers. But the things you'll learn here can be applied to any other Linux distribution.</p>
<p>Go ahead and download the ISO for Ubuntu from their <a target="_blank" href="https://ubuntu.com/download/desktop">download</a> page. Ubuntu 20.04 LTS (the latest long term release at the time of writing) is around 2.67GB in size. Once you've finished downloading the file, go back to Fedora Media Writer, click on "Custom Image", and select the ISO file you've just downloaded.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/fmw-ready-to-write.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The "Write to Disk" button is grayed out because there are no USB drives attached to the computer. Connect your USB drive and the button should turn bright red.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/fmw-ready-to-write-with-usb-drive.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Recheck that the correct USB drive is selected in the dropdown and hit the "Write to Disk" button. Depending on your machine's transfer rate, this process may take a few minutes. Once it's done, disconnect the USB drive and set it aside. You'll need it soon.</p>
<h2 id="heading-how-to-prepare-your-computer-for-installing-linux">How to Prepare Your Computer for Installing Linux</h2>
<p>Again, it's not uncommon to find people who have failed to boot from a Linux USB drive. This can happen if you haven't configured your computer properly. </p>
<p>To do so, go to your Control Panel. Not the new Settings application, but the OG Control Panel.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/control-panel-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Make sure Control Panel is either on "Small icons" or "Large icons" mode and not on the "Category mode". Now go to "Power Options" and from the left side-bar, click on "Choose what the power buttons do".</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/turn-off-fast-startup.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Click on the Change settings that are currently unavailable link and uncheck the "Turn on fast startup (recommended)" option and hit "Save changes". </p>
<p>According to Walter Glenn's <a target="_blank" href="https://www.howtogeek.com/243901/the-pros-and-cons-of-windows-10s-fast-startup-mode/">article</a>,</p>
<blockquote>
<p>Fast Startup combines elements of a cold shutdown and the hibernate feature. When you shut down your computer with Fast Startup enabled, Windows closes all applications and logs off all users, just as in a normal cold shutdown.   </p>
<p>At this point, Windows is in a state very similar to when it’s freshly booted up: No users have logged in and started programs, but the Windows kernel is loaded and the system session is running.   </p>
<p>Windows then alerts device drivers that support it to prepare for hibernation, saves the current system state to the hibernation file, and turns off the computer.  </p>
<p>When you start the computer again, Windows does not have to reload the kernel, drivers, and system state individually. Instead, it just refreshes your RAM with the loaded image from the hibernation file and delivers you to the login screen. This technique can shave considerable time off your start up.</p>
</blockquote>
<p>I know this sounds like a nice to have feature, but the problem is, if you keep fast startup enabled in a dual boot system, Linux will be unable to use any of the drives shared between the two operating systems because they're hibernated and held by Windows.</p>
<p>Next, boot into your motherboard's UEFI configuration screen. Depending on your motherboard or laptop brand, the key can change but in most cases pressing the "Del" key should get you in.</p>
<p>Once you're there, you'll have to change one setting in particular:</p>
<ul>
<li><strong>Turn off secure boot</strong> – this is one of the features of UEFI that helps prevent attacks and malware during boot. Disabling it is not strictly necessary but depending on the distribution you've chosen you may or may not face issues during installation. Disable it to be safe.</li>
</ul>
<p>Save the updated settings and boot back to Windows. Now it's time to prepare some disk space for Linux to fit into.</p>
<h2 id="heading-how-to-create-additional-partitions-for-installing-linux">How to Create Additional Partitions for Installing Linux</h2>
<p>Now it's time to make some room for the new OS. Based on the state of your HDD or SSD, it can either be very straightforward or quite tricky. </p>
<p>Let me explain what we're going to do. There is a utility built into Windows called "Disk Management" that's useful when you want to mess around with your partitions.</p>
<p>You can use this to squeeze out some space out of your existing partitions. To do so, open Disk Management by searching for it in the start menu.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/disk-management-in-start-menu.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Keep in mind that it may pop up as "Create and format hard disk partitions" instead of Disk Management. Fire it up and have a good look at its user interface:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/disk-management.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This screenshot is from one of my machines that doesn't have Linux installed. I'll use this device as the guinea pig for this article. It has a 512GB NVME SSD and 8GB of RAM. </p>
<p>The user interface is divided into two parts. The top one is a list of all your partitions and the bottom part has all the physical disks connected to your computer listed vertically.</p>
<p>The below screenshot is from my desktop workstation that has a 250GB NVME SSD and a 1TB HDD. I have both Windows and Linux installed on the second disk. So if you have multiple disks on your machine as well, I would suggest you install the OS on the disk that contains the EFI partition. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/disk-management-desktop.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you look at the beginning of Disk 1, that 550MB FAT32 partition is the EFI. On your machine, it may be much smaller.</p>
<p>Let's get back to our guinea pig device. As you can see from the screenshot, the Windows (C:) partition is almost 250GB. I'll cut off 108GB from this partition.</p>
<ul>
<li>100GB for root</li>
<li>8GB for swap</li>
</ul>
<p>In Linux, the root directory contains all other directories and files on the system. When your RAM gets full, Linux moves the inactive pages from memory to the swap space. Having a swap space is not mandatory but it's good to have.</p>
<p>There is no hard and fast rule for determining the swap space. The recommended size for swap when you have a 4GB-8GB RAM is 2 times that size, and for 8GB-16GB is 1.5 times that size. Considering I don't do any memory intensive tasks on this laptop, I will break the rule here.</p>
<p>To cut off some space from your desired partition, right click on it from the bottom part and click on "Shrink". Once you do that, Disk Management will start calculating the amount available for shrinking.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/querying-for-available-space.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You may think that the entire free space of a partition should be shrinkable, but that's not true. Sometimes there are unmovable files scattered around your partition that may prevent you from using the full free space. In those cases, use a tool like <a target="_blank" href="https://www.ccleaner.com/defraggler">Defraggler</a> to optimize your drive.</p>
<p>After Disk Management has finished querying the partition, you'll see the following window:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/shrink-window.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you can see, I have 160311MB of space available to shrink. Dividing the value by 1024 will give you the size in gigabytes which in my case is around 156GB.</p>
<p>But I want to shrink my partition by 108GB. Multiplying this value by 1024 gives the value in megabytes of 110592MB.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/calculate-shrink-amount.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once you have your desired size calculated, hit the "Shrink" button. The shrinking process doesn't take that long. Once the process is done the bottom part of the user interface will update.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/disk-management-after-shrink.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you can see, I now have 108GB of unallocated space. To be honest, this is enough for proceeding to the next step. But to make your life easier, I would suggest that you create two RAW partitions before going forward.</p>
<p>To do so, right click on the unallocated space and click on the "New Simple Volume" option. A new wizard window will show up. Press the "Next" button and on the next step, the wizard will ask about the new partition's size:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/partition-creation-size.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I want to create the 100GB root partition. Multiplying that value by 1024 gives the value in megabytes which is 102400MB. Once you have the size calculated, hit "Next".</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/partition-creation-drive-letter.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the next step, the wizard will ask you about the drive letter. Choose "Do not assign a drive letter or drive path" and hit "Next".</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/partition-creation-format.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In this step, select the "Do not format this volume" option and hit "Next". Finally hit finish on the last step. Follow the same process for creating your swap partition.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/disk-management-after-creating-partitions.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I now have a 100GB RAW partition for the Linux root and a 8GB RAW partition for swap. Close the disk management tool and grab another mug of coffee or tea or at least water because we're going deeper into the rabbit hole.</p>
<h2 id="heading-how-to-install-linux-alongside-windows">How to Install Linux Alongside Windows</h2>
<p>Okay everyone, it's getting real now. We're going to do it. But first, you'll have to figure out which key to use to get into your boot menu.</p>
<p>On the device I'm using, pressing the F2 button takes me to the UEFI configuration screen. From there, pressing F8 takes me to the boot menu. So make sure you've done the research for your device.</p>
<p>Some tutorials may instruct you to change the boot order from your UEFI configuration screen, but I don't recommend doing that. The SSD or HDD that contains your bootloader should always be on the top.</p>
<p>Now connect the bootable USB device that you set aside on the first section and reboot your computer into the boot menu. From the boot menu, select the bootable USB drive and hit enter.</p>
<p>The GNU GRUB menu will appear. Pick the first one that says "Ubuntu". Wait until the file integrity check finishes or you can just skip it by hitting "Ctrl + C" on your keyboard.</p>
<p>You'll hear a beautiful chime and with that, the majestic Ubuntu installer will show up:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/ubuntu-installer-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Before you hit the "Continue" button, I would suggest that you get connected to the internet. If you're using an ethernet cable then you should be connected already. But if you're using wireless, then check the top right corner of your screen for the Wifi icon:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/wifi.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once you're connected, hit the "Continue" button on the installer:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/keyboard-layout.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Pick the correct keyboard layout for yourself and hit "Continue".</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/updates-and-other-software.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The "Normal installation" will give you a bunch of useful software and games from the get go, whereas the "Minimal installation" will give you the essentials only.</p>
<p>Keep the "Download updates while installing Ubuntu" option checked. This will download updated package files from the internet during installation.</p>
<p>The third option needs some explanation. Assume that you're using an NVIDIA GPU. When Ubuntu detects that GPU, Ubuntu will load the open-source drivers for NVIDIA GPUs known as "nouveau". </p>
<p>If you check the "Install third-party software for graphics and Wi-Fi hardware and additional media formats" option, NVIDIA will attempt to install proprietary drivers provided by NVIDIA itself. It'll also install codecs for proprietary media formats such as MPEG. </p>
<p>This device I'm using has an AMD GPU and uses the open-source "amdgpu" driver. I'll leave this unchecked considering I can install the codecs as necessary by myself. Do what you prefer and hit the "Continue" button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/installation-type.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Okay this step needs attention. The Ubuntu installer is smart enough to detect whether you have other OSes installed on your machine or not. If yes, the installer will offer you the option to install Ubuntu alongside them. Don't pick that option. I repeat, <strong>don't pick that option</strong>.</p>
<p>Choose "Something else" and hit the "Continue" button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/partition-map.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This part can be a bit tricky. This is why I instructed you to create the partition from Windows instead of leaving the space unallocated. If you had left it unallocated, figuring out which part of the disk you should use would have become much more difficult.</p>
<p>At the top you can see a multi-colored line along with legends for which color represents which partition. Find out the two partitions you created from Windows.</p>
<p>In my machine, "nvme0n1p4" and "nvme0n1p5" are the ones. Now from the list, find the one you created for the root (nvme0n1p4 in my case) and double click on it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/edit-partition.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Choose "Ext4 journaling file system" from the "Use as" dropdown and "/" as the "Mount point" dropdown. According to the <a target="_blank" href="http://www.linfo.org/mount_point.html">The Linux Information Project</a>:</p>
<blockquote>
<p>A mount point is a directory (typically an empty one) in the currently accessible <a target="_blank" href="http://www.linfo.org/filesystem.html">filesystem</a> on which an additional filesystem is mounted (i.e., logically attached).</p>
</blockquote>
<p>Hit the "OK" button. Next double click on the partition you created for the swap space:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/swap-partition.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Choose "swap area" from the "Use as" dropdown menu and hit the "OK" button. There is one more partition to configure. That is the EFI partition. Scroll through the list and find the FAT32 partition.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/efi-partition.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>On my machine, the "nvme0n1p1" is the EFI partition. Double click on it:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/use-as-efi.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Make sure "EFI System Partition" is selected from the "Use as" dropdown menu. This is the partition that'll contain your bootloader. Make sure you're not formatting this partition. Hit the "OK" button.</p>
<p>Also, the default mount point for the EFI partition is "/boot/efi". Some distributions like Fedora will require you to write this mount point manually. So make sure you're putting the correct mount point.</p>
<p>Recheck the partition configuration once again and if everything looks fine, hit the "Install Now" button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/where-are-you.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The installer will ask you about your time zone. I live in Dhaka, Bangladesh so that's what I've chosen. Hit the "Continue" button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/who-are-you-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Fill out all the information as you see fit and hit the "Continue" button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/welcome-to-ubuntu.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The installation process shouldn't take long. Back when I was a kid, I loved looking at this slideshow.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/restart-now.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once the installation is done you can either continue testing or restart. If you choose to restart, Ubuntu will instruct you to disconnect the USB drive and hit Enter.</p>
<p>The machine will reboot and the GRUB menu will show up again. Take a look at the list, and you'll see both Ubuntu and Windows Boot Manager on the menu. Boot into Ubuntu because you have one last thing to do.</p>
<h2 id="heading-how-to-sync-the-time-between-windows-and-linux">How to Sync the Time Between Windows and Linux</h2>
<p>This is one of the common problems that people with a dual boot system face. When you boot into Windows and then boot into Linux, you'll find Linux's clock all messed up. The same thing will happen if you first boot into Linux and then boot into Windows.</p>
<p>Let me explain why this happens. Your computer (or rather every computer in the world) has two clocks. One is the system clock that lives within the OS, and the other is the hardware clock that lives in your motherboard and keeps track of time even when your computer is not running.</p>
<p>The problem is that Windows assumes that your hardware clock is running in your local time and Linux assumes that your hardware clock is running in UTC time and applies an offset according to your location.</p>
<p>The easiest way to fix this issue is to make your Linux distribution use local time like Windows does. To do so, execute the following command in the Linux terminal:</p>
<pre><code class="lang-bash">timedatectl set-local-rtc 1 --adjust-system-clock
</code></pre>
<p>Now restart your computer into Windows, sync the system clock and go back to Linux. The time should not be messed up now.</p>
<h2 id="heading-how-to-remove-linux-from-a-dual-boot-system">How to Remove Linux From a Dual Boot System</h2>
<p>Say for some reason you didn't like your time with Linux and want to get rid of it. This would be sad, but life is hard, ain't it?</p>
<p>Removing Linux from a dual boot system is a two step process:</p>
<ol>
<li>Getting rid of the GRUB bootloader</li>
<li>Getting rid of the Linux partitions</li>
</ol>
<p>To get rid of the GRUB bootloader you'll have to remove the corresponding files from the EFI partition. The problem is that the partition is hidden by default. </p>
<p>To make if accessible you'll have to use the <code>diskpart</code> program. It's a disk management utility like the Disk Management tool but it's a command line interface.</p>
<p>Boot into Windows. From the start menu, open Command Prompt as an administrator. To do so, just search for "cmd" in your start menu and when the Command Prompt shows up, press the "Ctrl + Shift + Enter" key combination.</p>
<p>Now write <code>diskpart</code> in the command prompt window and hit enter to start the program.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/diskpart.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Next, write <code>list disk</code> and hit enter to get a list of all the connected disks:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/list-disk.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This device has only one physical disk but you may have multiple. Write <code>sel disk &lt;disk number&gt;</code> to select the desired disk.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/sel-disk-0.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Then write <code>list vol</code> and press enter to list out all the partitions in this disk.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/list-vol.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Judging by the size and format, I can say that Volume 4 is the EFI partition. Keep in mind this can be much smaller on your system but it will be always a FAT32 partition. Write <code>sel vol &lt;volume number&gt;</code> to select the desired volume.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/sel-vol-4.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Finally write <code>assign letter x</code> and hit enter to assign the letter <code>x</code> to this partition.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/assign-letter-x.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Exit <code>diskpart</code> by writing <code>exit</code> and hitting enter:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/exit.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now the partition has become accessible. From the same command prompt window, go inside the EFI partition by writing <code>x:</code> and hitting enter.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/x.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To get a list of all the folders in there, write <code>dir</code> and hit enter.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/dir.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now write <code>cd EFI</code> to go inside that EFI folder and write <code>dir</code> once again to list out the contents.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/cd-efi.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You'll have to get rid of that <code>ubuntu</code> folder. To do so, write <code>rmdir /s ubuntu</code> and hit enter. Command prompt will ask you whether you're sure or not. Write <code>Y</code> and hit enter to confirm. Then use <code>dir</code> one last time to make sure it's gone.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/rmdir-dir.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>That's it. Next, open Disk Management once again like you did before and from the bottom part, right click on the Linux oriented partitions and choose "Delete Volume" from the list.</p>
<p>After deleting the partitions, you can either create a new one using the unallocated space or extend the partition on the left of it to dissolve the unallocated space.</p>
<p>Finally reboot your computer and check whether the Ubuntu has gone away from your machine or not.</p>
<h2 id="heading-what-about-other-linux-distributions">What About Other Linux Distributions?</h2>
<p>The techniques learned in this article is relevant for any Linux distributions out there.</p>
<p>So, whenever you're dual booting a system, make sure that</p>
<ul>
<li>Secure Boot is disabled</li>
<li>Fast Startup is disabled</li>
</ul>
<p>And during the installation</p>
<ul>
<li>Do not choose any guided/automatic installation type</li>
<li>Make sure to not format the EFI/ESP partition</li>
<li>Make sure to mount your partitions properly</li>
</ul>
<p>As long as you're sticking to these few rules, you should be good to go. </p>
<p>Just keep in mind that there are some rare cases when a distribution may not use GRUB as a bootloader.</p>
<p>Take the very popular "<a target="_blank" href="https://pop.system76.com/">Pop!_OS</a>" for example. It uses "systemd-boot" as its default bootloader. As a result you'll have to keep pressing the Space button (or maybe any button on the keyboard) during startup, otherwise the boot menu won't show up and you'll boot into Pop!_OS directly.</p>
<p>Another thing that I've seen: some motherboards such as my MSI B450 Tomahawk Max, chooses the Windows Boot Manager by default even though I have a working Linux installation. If you see something like this, go into your UEFI configuration screen and look for relevant options.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I would like to thank you from the bottom of my heart for the time you've spent reading this article. </p>
<p>I also have a personal blog where I write about random tech stuff, so if you're interested in something like that, checkout <a target="_blank" href="https://farhan.dev">https://farhan.dev</a>. If you have any questions or are confused about anything – or just want to get in touch – I'm available on <a target="_blank" href="https://twitter.com/frhnhsin">Twitter</a> and <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The NGINX Handbook – Learn NGINX for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ A young Russian developer named Igor Sysoev was frustrated by older web servers' inability to handle more than 10 thousand concurrent requests. This is a problem referred to as the C10k problem. As an answer to this, he started working on a new web s... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-nginx-handbook/</link>
                <guid isPermaLink="false">66b0ab588d675d0da5f1ab85</guid>
                
                    <category>
                        <![CDATA[ nginx ]]>
                    </category>
                
                    <category>
                        <![CDATA[ servers ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Farhan Hasin Chowdhury ]]>
                </dc:creator>
                <pubDate>Mon, 26 Apr 2021 23:56:38 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/NGINX-Handbook-Mockup.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A young Russian developer named <a target="_blank" href="https://en.wikipedia.org/wiki/Igor_Sysoev">Igor Sysoev</a> was frustrated by older web servers' inability to handle more than 10 thousand concurrent requests. This is a problem referred to as the <a target="_blank" href="https://en.wikipedia.org/wiki/C10k_problem">C10k problem</a>. As an answer to this, he started working on a new web server back in 2002.</p>
<p><a target="_blank" href="https://nginx.org/">NGINX</a> was first released to the public in 2004 under the terms of the <a target="_blank" href="https://en.wikipedia.org/wiki/2-clause_BSD">2-clause BSD</a> license. According to the <a target="_blank" href="https://news.netcraft.com/archives/2021/03/29/march-2021-web-server-survey.html">March 2021 Web Server Survey</a>, NGINX holds 35.3% of the market with a total of 419.6 million sites.</p>
<p>Thanks to tools like <a target="_blank" href="https://www.digitalocean.com/community/tools/nginx">NGINXConfig</a> by <a target="_blank" href="https://digitalocean.com/">DigitalOcean</a> and an abundance of pre-written configuration files on the internet, people tend to do a lot of copy-pasting instead of trying to understand when it comes to configuring NGINX.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/177962736_1410222585999736_5618677227291897851_n.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Trust me, it's not that hard...</em></p>
<p>I'm not saying that copying code is bad, but copying code without understanding is a big "no no". </p>
<p>Also NGINX is the kind of software that should be configured exactly according to the requirements of the application to be served and available resources on the host. </p>
<p>That's why instead of copying blindly, you should understand and then fine tune what you're copying – and that's where this handbook comes in.</p>
<p>After going through the entire book, you should be able to:</p>
<ul>
<li>Understand configuration files generated by popular tools as well as those found in various documentation.</li>
<li>Configure NGINX as a web server, a reverse proxy server, and a load balancer from scratch.</li>
<li>Optimize NGINX to get maximum performance out of your server.</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li>Familiarity with the Linux terminal and common Unix programs such as <code>ls</code>, <code>cat</code>, <code>ps</code>, <code>grep</code>, <code>find</code>, <code>nproc</code>, <code>ulimit</code> and <code>nano</code>.</li>
<li>A computer powerful enough to run a virtual machine or a $5 virtual private server.</li>
<li>Understanding of web applications and a programming language such as JavaScript or PHP.</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-introduction-to-nginx">Introduction to NGINX</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-nginx">How to Install NGINX</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-provision-a-local-virtual-machine">How to Provision a Local Virtual Machine</a></li>
<li><a class="post-section-overview" href="#heading-how-to-provision-a-virtual-private-server">How to Provision a Virtual Private Server</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-nginx-on-a-provisioned-server-or-virtual-machine-2">How to Install NGINX on a Provisioned Server or Virtual Machine</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-introduction-to-nginxs-configuration-files">Introduction to NGINX's Configuration Files</a></li>
<li><a class="post-section-overview" href="#heading-how-to-configure-a-basic-web-server">How to Configure a Basic Web Server</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-write-your-first-configuration-file">How to Write Your First Configuration File</a></li>
<li><a class="post-section-overview" href="#heading-how-to-validate-and-reload-configuration-files">How to Validate and Reload Configuration Files</a></li>
<li><a class="post-section-overview" href="#heading-how-to-understand-directives-and-contexts-in-nginx">How to Understand Directives and Contexts in NGINX</a></li>
<li><a class="post-section-overview" href="#heading-how-to-serve-static-content-using-nginx">How to Serve Static Content Using NGINX</a></li>
<li><a class="post-section-overview" href="#heading-static-file-type-handling-in-nginx">Static File Type Handling in NGINX</a></li>
<li><a class="post-section-overview" href="#heading-how-to-include-partial-config-files">How to Include Partial Config Files</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-dynamic-routing-in-nginx">Dynamic Routing in NGINX</a><ul>
<li><a class="post-section-overview" href="#heading-location-matches">Location Matches</a></li>
<li><a class="post-section-overview" href="#heading-variables-in-nginx">Variables in NGINX</a></li>
<li><a class="post-section-overview" href="#heading-redirects-and-rewrites">Redirects and Rewrites</a></li>
<li><a class="post-section-overview" href="#heading-how-to-try-for-multiple-files">How to Try for Multiple Files</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-logging-in-nginx">Logging in NGINX</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-nginx-as-a-reverse-proxy">How to Use NGINX as a Reverse Proxy</a><ul>
<li><a class="post-section-overview" href="#heading-nodejs-with-nginx">Node.js With NGINX</a></li>
<li><a class="post-section-overview" href="#heading-php-with-nginx">PHP With NGINX</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-use-nginx-as-a-load-balancer">How to Use NGINX as a Load Balancer</a></li>
<li><a class="post-section-overview" href="#heading-how-to-optimize-nginx-for-maximum-performance">How To Optimize NGINX for Maximum Performance</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-configure-worker-processes-and-worker-connections">How to Configure Worker Processes and Worker Connections</a></li>
<li><a class="post-section-overview" href="#heading-how-to-cache-static-content">How to Cache Static Content</a></li>
<li><a class="post-section-overview" href="#heading-how-to-compress-responses">How to Compress Responses</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-understand-the-main-configuration-file-1">How to Understand the Main Configuration File</a></li>
<li><a class="post-section-overview" href="#heading-how-to-configure-ssl-and-http2">How To Configure SSL and HTTP/2</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-configure-ssl">How To Configure SSL</a></li>
<li><a class="post-section-overview" href="#heading-how-to-enable-http2">How to Enable HTTP/2</a></li>
<li><a class="post-section-overview" href="#heading-how-to-enable-server-push">How to Enable Server Push</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-project-code">Project Code</h2>
<p>You can find the code for the example projects in the following repository:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/fhsinchy/nginx-handbook-projects">https://github.com/fhsinchy/nginx-handbook-projects</a></div>
<h2 id="heading-introduction-to-nginx">Introduction to NGINX</h2>
<p><a target="_blank" href="https://nginx.org/">NGINX</a> is a high performance web server developed to facilitate the increasing needs of the modern web. It focuses on high performance, high concurrency, and low resource usage. Although it's mostly known as a web server, NGINX at its core is a <a target="_blank" href="https://en.wikipedia.org/wiki/Reverse_proxy">reverse proxy</a> server.</p>
<p>NGINX is not the only web server on the market, though. One of its biggest competitors is <a target="_blank" href="https://httpd.apache.org/">Apache HTTP Server (httpd)</a>, first released back on 1995. In spite of the fact that Apache HTTP Server is more flexible, server admins often prefer NGINX for two main reasons:</p>
<ul>
<li>It can handle a higher number of concurrent requests.</li>
<li>It has faster static content delivery with low resource usage.</li>
</ul>
<p>I won't go further into the whole Apache vs NGINX debate. But if you wish to learn more about the differences between them in detail, this excellent <a target="_blank" href="https://www.digitalocean.com/community/tutorials/apache-vs-nginx-practical-considerations">article</a> from <a target="_blank" href="https://www.digitalocean.com/community/users/jellingwood">Justin Ellingwood</a> may help.</p>
<p>In fact, to explain NGINX's request handling technique, I would like to quote two paragraphs from Justin's article here:</p>
<blockquote>
<p>Nginx came onto the scene after Apache, with more awareness of the concurrency problems that would face sites at scale. Leveraging this knowledge, Nginx was designed from the ground up to use an asynchronous, non-blocking, event-driven connection handling algorithm.  </p>
<p>Nginx spawns worker processes, each of which can handle thousands of connections. The worker processes accomplish this by implementing a fast looping mechanism that continuously checks for and processes events. Decoupling actual work from connections allows each worker to concern itself with a connection only when a new event has been triggered.</p>
</blockquote>
<p>If that seems a bit complicated to understand, don't worry. Having a basic understanding of the inner workings will suffice for now.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/wQszK2rvq-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>NGINX is faster in static content delivery while staying relatively lighter on resources because it doesn't embed a dynamic programming language processor. When a request for static content comes, NGINX simply responds with the file without running any additional processes.</p>
<p>That doesn't mean that NGINX can't handle requests that require a dynamic programming language processor. In such cases, NGINX simply delegates the tasks to separate processes such as <a target="_blank" href="https://www.php.net/manual/en/install.fpm.php">PHP-FPM</a>, <a target="_blank" href="https://nodejs.org/">Node.js</a> or <a target="_blank" href="https://python.org/">Python</a>. Then, once that process finishes its work, NGINX reverse proxies the response back to the client.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/_nT7rcdjG.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>NGINX is also a lot easier to configure thanks to a configuration file syntax inspired from various scripting languages that results in compact, easily maintainable configuration files.</p>
<h2 id="heading-how-to-install-nginx">How to Install NGINX</h2>
<p>Installing NGINX on a <a target="_blank" href="https://en.wikipedia.org/wiki/Linux">Linux</a>-based system is pretty straightforward. You can either use a virtual private server running <a target="_blank" href="https://ubuntu.com/">Ubuntu</a> as your playground, or you can provision a virtual machine on your local system using Vagrant.</p>
<p>For the most part, provisioning a local virtual machine will suffice and that's the way I'll be using in this article.</p>
<h3 id="heading-how-to-provision-a-local-virtual-machine">How to Provision a Local Virtual Machine</h3>
<p>For those who doesn't know, <a target="_blank" href="https://vagrantup.com/">Vagrant</a> is an open-source tool by <a target="_blank" href="https://www.hashicorp.com/">Hashicorp</a> that allows you to provision virtual machines using simple configuration files.</p>
<p>For this approach to work, you'll need <a target="_blank" href="https://www.virtualbox.org/wiki/Downloads/">VirtualBox</a> and <a target="_blank" href="https://www.vagrantup.com/downloads/">Vagrant</a>, so go ahead and install them first. If you need a little warm up on the topic, this <a target="_blank" href="https://learn.hashicorp.com/collections/vagrant/getting-started/">tutorial</a> may help.</p>
<p>Create a working directory somewhere in your system with a sensible name. Mine is <code>~/vagrant/nginx-handbook</code> directory.</p>
<p>Inside the working directory create a file named <code>Vagrantfile</code> and put following content in there:</p>
<pre><code class="lang-vagrantfile">Vagrant.configure("2") do |config|

    config.vm.hostname = "nginx-handbook-box"

    config.vm.box = "ubuntu/focal64"

    config.vm.define "nginx-handbook-box"

    config.vm.network "private_network", ip: "192.168.20.20"

    config.vm.provider "virtualbox" do |vb|
      vb.cpus = 1
      vb.memory = "1024"
      vb.name = "nginx-handbook"
    end

  end
</code></pre>
<p>This <code>Vagrantfile</code> is the configuration file I talked about earlier. It contains information like name of the virtual machine, number of CPUs, size of RAM, the IP address, and more.</p>
<p>To start a virtual machine using this configuration, open your terminal inside the working directory and execute the following command:</p>
<pre><code class="lang-shell">vagrant up

# Bringing machine 'nginx-handbook-box' up with 'virtualbox' provider...
# ==&gt; nginx-handbook-box: Importing base box 'ubuntu/focal64'...
# ==&gt; nginx-handbook-box: Matching MAC address for NAT networking...
# ==&gt; nginx-handbook-box: Checking if box 'ubuntu/focal64' version '20210415.0.0' is up to date...
# ==&gt; nginx-handbook-box: Setting the name of the VM: nginx-handbook
# ==&gt; nginx-handbook-box: Clearing any previously set network interfaces...
# ==&gt; nginx-handbook-box: Preparing network interfaces based on configuration...
#     nginx-handbook-box: Adapter 1: nat
#     nginx-handbook-box: Adapter 2: hostonly
# ==&gt; nginx-handbook-box: Forwarding ports...
#     nginx-handbook-box: 22 (guest) =&gt; 2222 (host) (adapter 1)
# ==&gt; nginx-handbook-box: Running 'pre-boot' VM customizations...
# ==&gt; nginx-handbook-box: Booting VM...
# ==&gt; nginx-handbook-box: Waiting for machine to boot. This may take a few minutes...
#     nginx-handbook-box: SSH address: 127.0.0.1:2222
#     nginx-handbook-box: SSH username: vagrant
#     nginx-handbook-box: SSH auth method: private key
#     nginx-handbook-box: Warning: Remote connection disconnect. Retrying...
#     nginx-handbook-box: Warning: Connection reset. Retrying...
#     nginx-handbook-box: 
#     nginx-handbook-box: Vagrant insecure key detected. Vagrant will automatically replace
#     nginx-handbook-box: this with a newly generated keypair for better security.
#     nginx-handbook-box: 
#     nginx-handbook-box: Inserting generated public key within guest...
#     nginx-handbook-box: Removing insecure key from the guest if it's present...
#     nginx-handbook-box: Key inserted! Disconnecting and reconnecting using new SSH key...
# ==&gt; nginx-handbook-box: Machine booted and ready!
# ==&gt; nginx-handbook-box: Checking for guest additions in VM...
# ==&gt; nginx-handbook-box: Setting hostname...
# ==&gt; nginx-handbook-box: Configuring and enabling network interfaces...
# ==&gt; nginx-handbook-box: Mounting shared folders...
#     nginx-handbook-box: /vagrant =&gt; /home/fhsinchy/vagrant/nginx-handbook

vagrant status

# Current machine states:

# nginx-handbook-box           running (virtualbox)
</code></pre>
<p>The output of the <code>vagrant up</code> command may differ on your system, but as long as <code>vagrant status</code> says the machine is running, you're good to go. </p>
<p>Given that the virtual machine is now running, you should be able to SSH into it. To do so, execute the following command:</p>
<pre><code class="lang-shell">vagrant ssh nginx-handbook-box

# Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-72-generic x86_64)
# vagrant@nginx-handbook-box:~$
</code></pre>
<p>If everything's done correctly you should be logged into your virtual machine, which will be evident by the <code>vagrant@nginx-handbook-box</code> line on your terminal. </p>
<p>This virtual machine will be accessible on <strong>http://192.168.20.20</strong> on your local machine. You can even assign a custom domain like <strong>http://nginx-handbook.test</strong> to the virtual machine by adding an entry to your <strong>hosts</strong> file:</p>
<pre><code class="lang-shell"># on mac and linux terminal
sudo nano /etc/hosts

# on windows command prompt as administrator
notepad c:\windows\system32\drivers\etc\hosts
</code></pre>
<p>Now append the following line at the end of the file:</p>
<pre><code><span class="hljs-number">192.168</span><span class="hljs-number">.20</span><span class="hljs-number">.20</span>   nginx-handbook.test
</code></pre><p>Now you should be able to access the virtual machine on <strong>http://nginx-handbook.test</strong> URI in your browser.</p>
<p>You can stop or destroy the virtual machine by executing the following commands inside the working directory:</p>
<pre><code class="lang-shell"># to stop the virtual machine
vagrant halt

# to destroy the virtual machine
vagrant destroy
</code></pre>
<p>If you want to learn about more Vagrant commands, this <a target="_blank" href="https://gist.github.com/wpscholar/a49594e2e2b918f4d0c4">cheat sheet</a> may come in handy.</p>
<p>Now that you have a functioning Ubuntu virtual machine on your system, all that is left to do is <a class="post-section-overview" href="#heading-how-to-install-nginx-on-a-provisioned-server-or-virtual-machine-2">install NGINX</a>.</p>
<h3 id="heading-how-to-provision-a-virtual-private-server">How to Provision a Virtual Private Server</h3>
<p>For this demonstration, I'll use <a target="_blank" href="https://vultr.com/">Vultr</a> as my provider but you may use <a target="_blank" href="https://digitalocean.com/">DigitalOcean</a> or whatever provider you like.</p>
<p>Assuming you already have an account with your provider, log into the account and deploy a new server:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/ZUAu_Tpxx-2.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>On DigitalOcean, it's usually called a droplet. On the next screen, choose a location close to you. I live in Bangladesh which is why I've chosen Singapore:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/zH08EnmGq.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>On the next step, you'll have to choose the operating system and server size. Choose Ubuntu 20.04 and the smallest possible server size:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/G8mEC13pp.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Although production servers tend to be much bigger and more powerful than this, a tiny server will be more than enough for this article.</p>
<p>Finally, for the last step, put something fitting like <strong>nginx-hadnbook-demo-server</strong> as the server host and label. You can even leave them empty if you want. </p>
<p>Once you're happy with your choices, go ahead and press the <strong>Deploy Now</strong> button.</p>
<p>The deployment process may take some time to finish, but once it's done, you'll see the newly created server on your dashboard:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/server-list.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Also pay attention to the <strong>Status –</strong> it should say <strong>Running</strong> and not <strong>Preparing</strong> or <strong>Stopped</strong>. To connect to the server, you'll need a username and password.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/server-overview.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Go into the overview page for your server and there you should see the server's IP address, username, and password:</p>
<p>The generic command for logging into a server using SSH is as follows:</p>
<pre><code class="lang-shell">ssh &lt;username&gt;@&lt;ip address&gt;
</code></pre>
<p>So in the case of my server, it'll be:</p>
<pre><code class="lang-shell">ssh root@45.77.251.108

# Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
# Warning: Permanently added '45.77.251.108' (ECDSA) to the list of known hosts.

# root@45.77.251.108's password: 
# Welcome to Ubuntu 20.04.2 LTS (GNU/Linux 5.4.0-65-generic x86_64)

# root@localhost:~#
</code></pre>
<p>You'll be asked if you want to continue connecting to this server or not. Answer with <code>yes</code> and then you'll be asked for the password. Copy the password from the server overview page and paste that into your terminal. </p>
<p>If you do everything correctly you should be logged into your server – you'll see the <code>root@localhost</code> line on your terminal. Here <code>localhost</code> is the server host name, and may differ in your case.</p>
<p>You can access this server directly by its IP address. Or if you own any custom domain, you can use that also. </p>
<p>Throughout the article you'll see me adding test domains to my operating system's <code>hosts</code> file. In case of a real server, you'll have to configure those servers using your DNS provider.</p>
<p>Remember that you'll be charged as long as this server is being used. Although the charge should be very small, I'm warning you anyways. You can destroy the server anytime you want by hitting the trash icon on the server overview page:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/image-90.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you own a custom domain name, you may assign a sub-domain to this server. Now that you're inside the server, all that is left to is <a class="post-section-overview" href="#heading-how-to-install-nginx-on-a-provisioned-server-or-virtual-machine-2">install NGINX</a>.</p>
<h3 id="heading-how-to-install-nginx-on-a-provisioned-server-or-virtual-machine">How to Install NGINX on a Provisioned Server or Virtual Machine</h3>
<p>Assuming you're logged into your server or virtual machine, the first thing you should do is performing an update. Execute the following command to do so:</p>
<pre><code class="lang-shell">sudo apt update &amp;&amp; sudo apt upgrade -y
</code></pre>
<p>After the update, install NGINX by executing the following command:</p>
<pre><code class="lang-shell">sudo apt install nginx -y
</code></pre>
<p>Once the installation is done, NGINX should be automatically registered as a <code>systemd</code> service and should be running. To check, execute the following command:</p>
<pre><code class="lang-shell">sudo systemctl status nginx

# ● nginx.service - A high performance web server and a reverse proxy server
#      Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
#      Active: active (running)
</code></pre>
<p>If the status says <code>running</code>, then you're good to go. Otherwise you may start the service by executing this command:</p>
<pre><code class="lang-shell">sudo systemctl start nginx
</code></pre>
<p>Finally for a visual verification that everything is working properly, visit your server/virtual machine with your favorite browser and you should see NGINX's default welcome page:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/image-89.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>NGINX is usually installed on the <code>/etc/nginx</code> directory and the majority of our work in the upcoming sections will be done in here.</p>
<p>Congratulations! Bow you have NGINX up and running on your server/virtual machine. Now it's time to jump head first into NGINX.</p>
<h2 id="heading-introduction-to-nginxs-configuration-files">Introduction to NGINX's Configuration Files</h2>
<p>As a web server, NGINX's job is to serve static or dynamic contents to the clients. But how that content are going to be served is usually controlled by configuration files.</p>
<p>NGINX's configuration files end with the <code>.conf</code> extension and usually live inside the <code>/etc/nginx/</code> directory. Let's begin by <code>cd</code>ing into this directory and getting a list of all the files:</p>
<pre><code class="lang-shell">cd /etc/nginx

ls -lh

# drwxr-xr-x 2 root root 4.0K Apr 21  2020 conf.d
# -rw-r--r-- 1 root root 1.1K Feb  4  2019 fastcgi.conf
# -rw-r--r-- 1 root root 1007 Feb  4  2019 fastcgi_params
# -rw-r--r-- 1 root root 2.8K Feb  4  2019 koi-utf
# -rw-r--r-- 1 root root 2.2K Feb  4  2019 koi-win
# -rw-r--r-- 1 root root 3.9K Feb  4  2019 mime.types
# drwxr-xr-x 2 root root 4.0K Apr 21  2020 modules-available
# drwxr-xr-x 2 root root 4.0K Apr 17 14:42 modules-enabled
# -rw-r--r-- 1 root root 1.5K Feb  4  2019 nginx.conf
# -rw-r--r-- 1 root root  180 Feb  4  2019 proxy_params
# -rw-r--r-- 1 root root  636 Feb  4  2019 scgi_params
# drwxr-xr-x 2 root root 4.0K Apr 17 14:42 sites-available
# drwxr-xr-x 2 root root 4.0K Apr 17 14:42 sites-enabled
# drwxr-xr-x 2 root root 4.0K Apr 17 14:42 snippets
# -rw-r--r-- 1 root root  664 Feb  4  2019 uwsgi_params
# -rw-r--r-- 1 root root 3.0K Feb  4  2019 win-utf
</code></pre>
<p>Among these files, there should be one named <strong>nginx.conf</strong>. This is the the main configuration file for NGINX. You can have a look at the content of this file using the <code>cat</code> program:</p>
<pre><code class="lang-shell">cat nginx.conf

# user www-data;
# worker_processes auto;
# pid /run/nginx.pid;
# include /etc/nginx/modules-enabled/*.conf;

# events {
#     worker_connections 768;
#     # multi_accept on;
# }

# http {

#     ##
#     # Basic Settings
#     ##

#     sendfile on;
#     tcp_nopush on;
#     tcp_nodelay on;
#     keepalive_timeout 65;
#     types_hash_max_size 2048;
#     # server_tokens off;

#     # server_names_hash_bucket_size 64;
#     # server_name_in_redirect off;

#     include /etc/nginx/mime.types;
#     default_type application/octet-stream;

#     ##
#     # SSL Settings
#     ##

#     ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
#     ssl_prefer_server_ciphers on;

#     ##
#     # Logging Settings
#     ##

#     access_log /var/log/nginx/access.log;
#     error_log /var/log/nginx/error.log;

#     ##
#     # Gzip Settings
#     ##

#     gzip on;

#     # gzip_vary on;
#     # gzip_proxied any;
#     # gzip_comp_level 6;
#     # gzip_buffers 16 8k;
#     # gzip_http_version 1.1;
#     # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

#     ##
#     # Virtual Host Configs
#     ##

#     include /etc/nginx/conf.d/*.conf;
#     include /etc/nginx/sites-enabled/*;
# }


# #mail {
# #    # See sample authentication script at:
# #    # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
# # 
# #    # auth_http localhost/auth.php;
# #    # pop3_capabilities "TOP" "USER";
# #    # imap_capabilities "IMAP4rev1" "UIDPLUS";
# # 
# #    server {
# #        listen     localhost:110;
# #        protocol   pop3;
# #        proxy      on;
# #    }
# # 
# #    server {
# #        listen     localhost:143;
# #        protocol   imap;
# #        proxy      on;
# #    }
# #}
</code></pre>
<p>Whoa! That's a lot of stuff. Trying to understand this file at its current state will be a nightmare. So let's rename the file and create a new empty one:</p>
<pre><code class="lang-shell"># renames the file
sudo mv nginx.conf nginx.conf.backup

# creates a new file
sudo touch nginx.conf
</code></pre>
<p>I <strong>highly discourage</strong> you from editing the original <code>nginx.conf</code> file unless you absolutely know what you're doing. For learning purposes, you may rename it, but <a class="post-section-overview" href="#heading-how-to-understand-the-main-configuration-file-1">later on</a>, I'll show you how you should go about configuring a server in a real life scenario.</p>
<h2 id="heading-how-to-configure-a-basic-web-server">How to Configure a Basic Web Server</h2>
<p>In this section of the book, you'll finally get your hands dirty by configuring a basic static web server from the ground up. The goal of this section is to introduce you to the syntax and fundamental concepts of NGINX configuration files.</p>
<h3 id="heading-how-to-write-your-first-configuration-file">How to Write Your First Configuration File</h3>
<p>Start by opening the newly created <code>nginx.conf</code> file using the <a target="_blank" href="https://www.nano-editor.org/">nano</a> text editor:</p>
<pre><code class="lang-shell">sudo nano /etc/nginx/nginx.conf
</code></pre>
<p>Throughout the book, I'll be using nano as my text editor. You may use something more modern if you want to, but in a real life scenario, you're most likely to work using <a target="_blank" href="https://www.nano-editor.org/">nano</a> or <a target="_blank" href="https://www.vim.org/">vim</a> on servers instead of anything else. So use this book as an opportunity to sharpen your nano skills. Also the official <a target="_blank" href="https://www.nano-editor.org/dist/latest/cheatsheet.html">cheat sheet</a> is there for you to consult whenever you need.</p>
<p>After opening the file, update its content to look like this:</p>
<pre><code class="lang-conf">events {

}

http {

    server {

        listen 80;
        server_name nginx-handbook.test;

        return 200 "Bonjour, mon ami!\n";
    }

}
</code></pre>
<p>If you have experience building REST APIs then you may guess from the <code>return 200 "Bonjour, mon ami!\n";</code> line that the server has been configured to respond with a status code of 200 and the message "Bonjour, mon ami!".</p>
<p>Don't worry if you don't understand anything more than that at the moment. I'll explain this file line by line, but first let's see this configuration in action.</p>
<h3 id="heading-how-to-validate-and-reload-configuration-files">How to Validate and Reload Configuration Files</h3>
<p>After writing a new configuration file or updating an old one, the first thing to do is check the file for any syntax mistakes. The <code>nginx</code> binary includes an option <code>-t</code> to do just that.</p>
<pre><code class="lang-shell">sudo nginx -t

# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful
</code></pre>
<p>If you have any syntax errors, this command will let you know about them, including the line number. </p>
<p>Although the configuration file is fine, NGINX will not use it. The way NGINX works is it reads the configuration file once and keeps working based on that.</p>
<p>If you update the configuration file, then you'll have to instruct NGINX explicitly to reload the configuration file. There are two ways to do that.</p>
<ul>
<li>You can restart the NGINX service by executing the <code>sudo systemctl restart nginx</code> command.</li>
<li>You can dispatch a <code>reload</code> signal to NGINX by executing the <code>sudo nginx -s reload</code> command.</li>
</ul>
<p>The <code>-s</code> option is used for dispatching various signals to NGINX. The available signals are <code>stop</code>, <code>quit</code>, <code>reload</code> and <code>reopen</code>. Among the two ways I just mentioned, I prefer the second one simply because it's less typing.</p>
<p>Once you've reloaded the configuration file by executing the <code>nginx -s reload</code> command, you can see it in action by sending a simple get request to the server:</p>
<pre><code class="lang-shell">curl -i http://nginx-handbook.test

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Wed, 21 Apr 2021 10:03:33 GMT
# Content-Type: text/plain
# Content-Length: 18
# Connection: keep-alive

# Bonjour, mon ami!
</code></pre>
<p>The server is responding with a status code of 200 and the expected message. Congratulations on getting this far! Now it's time for some explanation.</p>
<h3 id="heading-how-to-understand-directives-and-contexts-in-nginx">How to Understand Directives and Contexts in NGINX</h3>
<p>The few lines of code you've written here, although seemingly simple, introduce two of the most important terminologies of NGINX configuration files. They are <strong>directives</strong> and <strong>contexts</strong>.</p>
<p>Technically, everything inside a NGINX configuration file is a <strong>directive</strong>. Directives are of two types:</p>
<ul>
<li>Simple Directives</li>
<li>Block Directives</li>
</ul>
<p>A simple directive consists of the directive name and the space delimited parameters, like <code>listen</code>, <code>return</code> and others. Simple directives are terminated by semicolons.</p>
<p>Block directives are similar to simple directives, except that instead of ending with semicolons, they end with a pair of curly braces <code>{ }</code> enclosing additional instructions. </p>
<p>A block directive capable of containing other directives inside it is called a context, that is <code>events</code>, <code>http</code> and so on. There are four core contexts in NGINX:</p>
<ul>
<li><code>events { }</code> – The <code>events</code> context is used for setting global configuration regarding how NGINX is going to handle requests on a general level. There can be only one <code>events</code> context in a valid configuration file.</li>
<li><code>http { }</code> – Evident by the name, <code>http</code> context is used for defining configuration regarding how the server is going to handle HTTP and HTTPS requests, specifically. There can be only one <code>http</code> context in a valid configuration file.</li>
<li><code>server { }</code> – The <code>server</code> context is nested inside the <code>http</code> context and used for configuring specific virtual servers within a single host. There can be multiple <code>server</code> contexts in a valid configuration file nested inside the <code>http</code> context. Each <code>server</code> context is considered a virtual host.</li>
<li><code>main</code> – The <code>main</code> context is the configuration file itself. Anything written outside of the three previously mentioned contexts is on the <code>main</code> context.</li>
</ul>
<p>You can treat contexts in NGINX like scopes in other programming languages. There is also a sense of inheritance among them. You can find an <a target="_blank" href="https://nginx.org/en/docs/dirindex.html">alphabetical index of directives</a> on the official NGINX docs.</p>
<p>I've already mentioned that there can be multiple <code>server</code> contexts within a configuration file. But when a request reaches the server, how does NGINX know which one of those contexts should handle the request?</p>
<p>The <code>listen</code> directive is one of the ways to identify the correct <code>server</code> context within a configuration. Consider the following scenario:</p>
<pre><code>http {
    server {
        listen <span class="hljs-number">80</span>;
        server_name nginx-handbook.test;

        <span class="hljs-keyword">return</span> <span class="hljs-number">200</span> <span class="hljs-string">"hello from port 80!\n"</span>;
    }


    server {
        listen <span class="hljs-number">8080</span>;
        server_name nginx-handbook.test;

        <span class="hljs-keyword">return</span> <span class="hljs-number">200</span> <span class="hljs-string">"hello from port 8080!\n"</span>;
    }
}
</code></pre><p>Now if you send a request to http://nginx-handbook.test:80 then you'll receive "hello from port 80!" as a response. And if you send a request to http://nginx-handbook.test:8080, you'll receive "hello from port 8080!" as a response:</p>
<pre><code>curl nginx-handbook.test:<span class="hljs-number">80</span>

# hello <span class="hljs-keyword">from</span> port <span class="hljs-number">80</span>!

curl nginx-handbook.test:<span class="hljs-number">8080</span>

# hello <span class="hljs-keyword">from</span> port <span class="hljs-number">8080</span>!
</code></pre><p>These two server blocks are like two people holding telephone receivers, waiting to respond when a request reaches one of their numbers. Their numbers are indicated by the <code>listen</code> directives.</p>
<p>Apart from the <code>listen</code> directive, there is also the <code>server_name</code> directive. Consider the following scenario of an imaginary library management application:</p>
<pre><code>http {
    server {
        listen <span class="hljs-number">80</span>;
        server_name library.test;

        <span class="hljs-keyword">return</span> <span class="hljs-number">200</span> <span class="hljs-string">"your local library!\n"</span>;
    }


    server {
        listen <span class="hljs-number">80</span>;
        server_name librarian.library.test;

        <span class="hljs-keyword">return</span> <span class="hljs-number">200</span> <span class="hljs-string">"welcome dear librarian!\n"</span>;
    }
}
</code></pre><p>This is a basic example of the idea of virtual hosts. You're running two separate applications under different server names in the same server.</p>
<p>If you send a request to http://library.test then you'll get "your local library!" as a response. If you send a request to http://librarian.library.test, you'll get "welcome dear librarian!" as a response.</p>
<pre><code class="lang-shell">curl http://library.test

# your local library!

curl http://librarian.library.test

# welcome dear librarian!
</code></pre>
<p>To make this demo work on your system, you'll have to update your <code>hosts</code> file to include these two domain names as well:</p>
<pre><code class="lang-hosts">192.168.20.20   library.test
192.168.20.20   librarian.library.test
</code></pre>
<p>Finally, the <code>return</code> directive is responsible for returning a valid response to the user. This directive takes two parameters: the status code and the string message to be returned.</p>
<h3 id="heading-how-to-serve-static-content-using-nginx">How to Serve Static Content Using NGINX</h3>
<p>Now that you have a good understanding of how to write a basic configuration file for NGINX, let's upgrade the configuration to serve static files instead of plain text responses.</p>
<p>In order to serve static content, you first have to store them somewhere on your server. If you list the files and directory on the root of your server using <code>ls</code>, you'll find a directory called <code>/srv</code> in there:</p>
<pre><code class="lang-shell">ls -lh /

# lrwxrwxrwx   1 root    root       7 Apr 16 02:10 bin -&gt; usr/bin
# drwxr-xr-x   3 root    root    4.0K Apr 16 02:13 boot
# drwxr-xr-x  16 root    root    3.8K Apr 21 09:23 dev
# drwxr-xr-x  92 root    root    4.0K Apr 21 09:24 etc
# drwxr-xr-x   4 root    root    4.0K Apr 21 08:04 home
# lrwxrwxrwx   1 root    root       7 Apr 16 02:10 lib -&gt; usr/lib
# lrwxrwxrwx   1 root    root       9 Apr 16 02:10 lib32 -&gt; usr/lib32
# lrwxrwxrwx   1 root    root       9 Apr 16 02:10 lib64 -&gt; usr/lib64
# lrwxrwxrwx   1 root    root      10 Apr 16 02:10 libx32 -&gt; usr/libx32
# drwx------   2 root    root     16K Apr 16 02:15 lost+found
# drwxr-xr-x   2 root    root    4.0K Apr 16 02:10 media
# drwxr-xr-x   2 root    root    4.0K Apr 16 02:10 mnt
# drwxr-xr-x   2 root    root    4.0K Apr 16 02:10 opt
# dr-xr-xr-x 152 root    root       0 Apr 21 09:23 proc
# drwx------   5 root    root    4.0K Apr 21 09:59 root
# drwxr-xr-x  26 root    root     820 Apr 21 09:47 run
# lrwxrwxrwx   1 root    root       8 Apr 16 02:10 sbin -&gt; usr/sbin
# drwxr-xr-x   6 root    root    4.0K Apr 16 02:14 snap
# drwxr-xr-x   2 root    root    4.0K Apr 16 02:10 srv
# dr-xr-xr-x  13 root    root       0 Apr 21 09:23 sys
# drwxrwxrwt  11 root    root    4.0K Apr 21 09:24 tmp
# drwxr-xr-x  15 root    root    4.0K Apr 16 02:12 usr
# drwxr-xr-x   1 vagrant vagrant   38 Apr 21 09:23 vagrant
# drwxr-xr-x  14 root    root    4.0K Apr 21 08:34 var
</code></pre>
<p>This <code>/srv</code> directory is meant to contain site-specific data which is served by this system. Now <code>cd</code> into this directory and clone the code repository that comes with this book:</p>
<pre><code>cd /srv

sudo git clone https:<span class="hljs-comment">//github.com/fhsinchy/nginx-handbook-projects.git</span>
</code></pre><p>Inside the <code>nginx-handbook-projects</code> directory there should a directory called <code>static-demo</code> containing four files in total:</p>
<pre><code class="lang-shell">ls -lh /srv/nginx-handbook-projects/static-demo

# -rw-r--r-- 1 root root 960 Apr 21 11:27 about.html
# -rw-r--r-- 1 root root 960 Apr 21 11:27 index.html
# -rw-r--r-- 1 root root 46K Apr 21 11:27 mini.min.css
# -rw-r--r-- 1 root root 19K Apr 21 11:27 the-nginx-handbook.jpg
</code></pre>
<p>Now that you have the static content to be served, update your configuration as follows:</p>
<pre><code class="lang-conf">events {

}

http {

    server {

        listen 80;
        server_name nginx-handbook.test;

        root /srv/nginx-handbook-projects/static-demo;
    }

}
</code></pre>
<p>The code is almost the same, except the <code>return</code> directive has now been replaced by a <code>root</code> directive. This directive is used for declaring the root directory for a site. </p>
<p>By writing <code>root /srv/nginx-handbook-projects/static-demo</code> you're telling NGINX to look for files to serve inside the <code>/srv/nginx-handbook-projects/static-demo</code> directory if any request comes to this server. Since NGINX is a web server, it is smart enough to serve the <code>index.html</code> file by default.</p>
<p>Let's see if this works or not. Test and reload the updated configuration file and visit the server. You should be greeted with a somewhat broken HTML site:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/image-91.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Although NGINX has served the index.html file correctly, judging by the look of the three navigation links, it seems like the CSS code is not working.</p>
<p>You may think that there is something wrong in the CSS file. But in reality, the problem is in the configuration file.</p>
<h3 id="heading-static-file-type-handling-in-nginx">Static File Type Handling in NGINX</h3>
<p>To debug the issue you're facing right now, send a request for the CSS file to the server:</p>
<pre><code class="lang-shell">curl -I http://nginx-handbook/mini.min.css

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Wed, 21 Apr 2021 12:17:16 GMT
# Content-Type: text/plain
# Content-Length: 46887
# Last-Modified: Wed, 21 Apr 2021 11:27:06 GMT
# Connection: keep-alive
# ETag: "60800c0a-b727"
# Accept-Ranges: bytes
</code></pre>
<p>Pay attention to the <strong>Content-Type</strong> and see how it says <strong>text/plain</strong> and not <strong>text/css</strong>. This means that NGINX is serving this file as plain text instead of as a stylesheet.</p>
<p>Although NGINX is smart enough to find the <code>index.html</code> file by default, it's pretty dumb when it comes to interpreting file types. To solve this problem update your configuration once again:</p>
<pre><code class="lang-conf">events {

}

http {

    types {
        text/html html;
        text/css css;
    }

    server {

        listen 80;
        server_name nginx-handbook.test;

        root /srv/nginx-handbook-projects/static-demo;
    }
}
</code></pre>
<p>The only change we've made to the code is a new <code>types</code> context nested inside the <code>http</code> block. As you may have already guessed from the name, this context is used for configuring file types.</p>
<p>By writing <code>text/html html</code> in this context you're telling NGINX to parse any file as <code>text/html</code> that ends with the <code>html</code> extension.</p>
<p>You may think that configuring the CSS file type should suffice as the HTML is being parsed just fine – but no. </p>
<p>If you introduce a <code>types</code> context in the configuration, NGINX becomes even dumber and only parses the files configured by you. So if you only define the <code>text/css css</code> in this context then NGINX will start parsing the HTML file as plain text.</p>
<p>Validate and reload the newly updated config file and visit the server once again. Send a request for the CSS file once again, and this time the file should be parsed as a <strong>text/css</strong> file:</p>
<pre><code class="lang-shell">curl -I http://nginx-handbook.test/mini.min.css

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Wed, 21 Apr 2021 12:29:35 GMT
# Content-Type: text/css
# Content-Length: 46887
# Last-Modified: Wed, 21 Apr 2021 11:27:06 GMT
# Connection: keep-alive
# ETag: "60800c0a-b727"
# Accept-Ranges: bytes
</code></pre>
<p>Visit the server for a visual verification, and the site should look better this time:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/image-92.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you've updated and reloaded the configuration file correctly and you're still seeing the old site, perform a hard refresh.</p>
<h3 id="heading-how-to-include-partial-config-files">How to Include Partial Config Files</h3>
<p>Mapping file types within the <code>types</code> context may work for small projects, but for bigger projects it can be cumbersome and error-prone.</p>
<p>NGINX provides a solution for this problem. If you list the files inside the <code>/etc/nginx</code> directory once again, you'll see a file named <code>mime.types</code>.</p>
<pre><code class="lang-shell">ls -lh /etc/nginx

# drwxr-xr-x 2 root root 4.0K Apr 21  2020 conf.d
# -rw-r--r-- 1 root root 1.1K Feb  4  2019 fastcgi.conf
# -rw-r--r-- 1 root root 1007 Feb  4  2019 fastcgi_params
# -rw-r--r-- 1 root root 2.8K Feb  4  2019 koi-utf
# -rw-r--r-- 1 root root 2.2K Feb  4  2019 koi-win
# -rw-r--r-- 1 root root 3.9K Feb  4  2019 mime.types
# drwxr-xr-x 2 root root 4.0K Apr 21  2020 modules-available
# drwxr-xr-x 2 root root 4.0K Apr 17 14:42 modules-enabled
# -rw-r--r-- 1 root root 1.5K Feb  4  2019 nginx.conf
# -rw-r--r-- 1 root root  180 Feb  4  2019 proxy_params
# -rw-r--r-- 1 root root  636 Feb  4  2019 scgi_params
# drwxr-xr-x 2 root root 4.0K Apr 17 14:42 sites-available
# drwxr-xr-x 2 root root 4.0K Apr 17 14:42 sites-enabled
# drwxr-xr-x 2 root root 4.0K Apr 17 14:42 snippets
# -rw-r--r-- 1 root root  664 Feb  4  2019 uwsgi_params
# -rw-r--r-- 1 root root 3.0K Feb  4  2019 win-utf
</code></pre>
<p>Let's have a look at the content of this file:</p>
<pre><code class="lang-shell">cat /etc/mime.types

# types {
#     text/html                             html htm shtml;
#     text/css                              css;
#     text/xml                              xml;
#     image/gif                             gif;
#     image/jpeg                            jpeg jpg;
#     application/javascript                js;
#     application/atom+xml                  atom;
#     application/rss+xml                   rss;

#     text/mathml                           mml;
#     text/plain                            txt;
#     text/vnd.sun.j2me.app-descriptor      jad;
#     text/vnd.wap.wml                      wml;
#     text/x-component                      htc;

#     image/png                             png;
#     image/tiff                            tif tiff;
#     image/vnd.wap.wbmp                    wbmp;
#     image/x-icon                          ico;
#     image/x-jng                           jng;
#     image/x-ms-bmp                        bmp;
#     image/svg+xml                         svg svgz;
#     image/webp                            webp;

#     application/font-woff                 woff;
#     application/java-archive              jar war ear;
#     application/json                      json;
#     application/mac-binhex40              hqx;
#     application/msword                    doc;
#     application/pdf                       pdf;
#     application/postscript                ps eps ai;
#     application/rtf                       rtf;
#     application/vnd.apple.mpegurl         m3u8;
#     application/vnd.ms-excel              xls;
#     application/vnd.ms-fontobject         eot;
#     application/vnd.ms-powerpoint         ppt;
#     application/vnd.wap.wmlc              wmlc;
#     application/vnd.google-earth.kml+xml  kml;
#     application/vnd.google-earth.kmz      kmz;
#     application/x-7z-compressed           7z;
#     application/x-cocoa                   cco;
#     application/x-java-archive-diff       jardiff;
#     application/x-java-jnlp-file          jnlp;
#     application/x-makeself                run;
#     application/x-perl                    pl pm;
#     application/x-pilot                   prc pdb;
#     application/x-rar-compressed          rar;
#     application/x-redhat-package-manager  rpm;
#     application/x-sea                     sea;
#     application/x-shockwave-flash         swf;
#     application/x-stuffit                 sit;
#     application/x-tcl                     tcl tk;
#     application/x-x509-ca-cert            der pem crt;
#     application/x-xpinstall               xpi;
#     application/xhtml+xml                 xhtml;
#     application/xspf+xml                  xspf;
#     application/zip                       zip;

#     application/octet-stream              bin exe dll;
#     application/octet-stream              deb;
#     application/octet-stream              dmg;
#     application/octet-stream              iso img;
#     application/octet-stream              msi msp msm;

#     application/vnd.openxmlformats-officedocument.wordprocessingml.document    docx;
#     application/vnd.openxmlformats-officedocument.spreadsheetml.sheet          xlsx;
#     application/vnd.openxmlformats-officedocument.presentationml.presentation  pptx;

#     audio/midi                            mid midi kar;
#     audio/mpeg                            mp3;
#     audio/ogg                             ogg;
#     audio/x-m4a                           m4a;
#     audio/x-realaudio                     ra;

#     video/3gpp                            3gpp 3gp;
#     video/mp2t                            ts;
#     video/mp4                             mp4;
#     video/mpeg                            mpeg mpg;
#     video/quicktime                       mov;
#     video/webm                            webm;
#     video/x-flv                           flv;
#     video/x-m4v                           m4v;
#     video/x-mng                           mng;
#     video/x-ms-asf                        asx asf;
#     video/x-ms-wmv                        wmv;
#     video/x-msvideo                       avi;
# }
</code></pre>
<p>The file contains a long list of file types and their extensions. To use this file inside your configuration file, update your configuration to look as follows:</p>
<pre><code class="lang-conf">events {

}

http {

    include /etc/nginx/mime.types;

    server {

        listen 80;
        server_name nginx-handbook.test;

        root /srv/nginx-handbook-projects/static-demo;
    }

}
</code></pre>
<p>The old <code>types</code> context has now been replaced with a new <code>include</code> directive. Like the name suggests, this directive allows you to include content from other configuration files.</p>
<p>Validate and reload the configuration file and send a request for the <code>mini.min.css</code> file once again:</p>
<pre><code class="lang-shell">curl -I http://nginx-handbook.test/mini.min.css

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Wed, 21 Apr 2021 12:29:35 GMT
# Content-Type: text/css
# Content-Length: 46887
# Last-Modified: Wed, 21 Apr 2021 11:27:06 GMT
# Connection: keep-alive
# ETag: "60800c0a-b727"
# Accept-Ranges: bytes
</code></pre>
<p>In the section below on how to understand the main configuration file, I'll demonstrate how <code>include</code> can be used to modularize your virtual server configurations.</p>
<h2 id="heading-dynamic-routing-in-nginx">Dynamic Routing in NGINX</h2>
<p>The configuration you wrote in the previous section was a very simple static content server configuration. All it did was match a file from the site root corresponding to the URI the client visits and respond back.</p>
<p>So if the client requests files existing on the root such as <code>index.html</code>, <code>about.html</code> or <code>mini.min.css</code> NGINX will return the file. But if you visit a route such as http://nginx-handbook.test/nothing, it'll respond with the default 404 page:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/image-93.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In this section of the book, you'll learn about the <code>location</code> context, variables, redirects, rewrites and the <code>try_files</code> directive. There will be no new projects in this section but the concepts you learn here will be necessary in the upcoming sections.</p>
<p>Also the configuration will change very frequently in this section, so do not forget to validate and reload the configuration file after every update.</p>
<h3 id="heading-location-matches">Location Matches</h3>
<p>The first concept we'll discuss in this section is the <code>location</code> context. Update the configuration as follows:</p>
<pre><code class="lang-conf">events {

}

http {

    server {

        listen 80;
        server_name nginx-handbook.test;

        location /agatha {
            return 200 "Miss Marple.\nHercule Poirot.\n";
        }
    }
}
</code></pre>
<p>We've replaced the <code>root</code> directive with a new <code>location</code> context. This context is usually nested inside <code>server</code> blocks. There can be multiple <code>location</code> contexts within a <code>server</code> context.</p>
<p>If you send a request to http://nginx-handbook.test/agatha, you'll get a 200 response code and list of characters created by <a target="_blank" href="https://en.wikipedia.org/wiki/Agatha_Christie">Agatha Christie</a>.</p>
<pre><code class="lang-shell">curl -i http://nginx-handbook.test/agatha

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Wed, 21 Apr 2021 15:59:07 GMT
# Content-Type: text/plain
# Content-Length: 29
# Connection: keep-alive

# Miss Marple.
# Hercule Poirot.
</code></pre>
<p>Now if you send a request to http://nginx-handbook.test/agatha-christie, you'll get the same response:</p>
<pre><code class="lang-shell">curl -i http://nginx-handbook.test/agatha-christie

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Wed, 21 Apr 2021 15:59:07 GMT
# Content-Type: text/plain
# Content-Length: 29
# Connection: keep-alive

# Miss Marple.
# Hercule Poirot.
</code></pre>
<p>This happens because, by writing <code>location /agatha</code>, you're telling NGINX to match any URI starting with "agatha".  This kind of match is called a <strong>prefix match</strong>.</p>
<p>To perform an <strong>exact match</strong>, you'll have to update the code as follows:</p>
<pre><code class="lang-conf">events {

}

http {

    server {

        listen 80;
        server_name nginx-handbook.test;

        location = /agatha {
            return 200 "Miss Marple.\nHercule Poirot.\n";
        }
    }

}
</code></pre>
<p>Adding an <code>=</code> sign before the location URI will instruct NGINX to respond only if the URL matches exactly. Now if you send a request to anything but <code>/agatha</code>, you'll get a 404 response.</p>
<pre><code class="lang-shell">curl -I http://nginx-handbook.test/agatha-christie

# HTTP/1.1 404 Not Found
# Server: nginx/1.18.0 (Ubuntu)
# Date: Wed, 21 Apr 2021 16:14:29 GMT
# Content-Type: text/html
# Content-Length: 162
# Connection: keep-alive

curl -I http://nginx-handbook.test/agatha

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Wed, 21 Apr 2021 16:15:04 GMT
# Content-Type: text/plain
# Content-Length: 29
# Connection: keep-alive
</code></pre>
<p>Another kind of match in NGINX is the <strong>regex match</strong>. Using this match you can check location URLs against complex regular expressions.</p>
<pre><code class="lang-conf">events {

}

http {

    server {

        listen 80;
        server_name nginx-handbook.test;

        location ~ /agatha[0-9] {
            return 200 "Miss Marple.\nHercule Poirot.\n";
        }
    }

}
</code></pre>
<p>By replacing the previously used <code>=</code> sign with a <code>~</code> sign, you're telling NGINX to perform a regular expression match. Setting the location to <code>~ /agatha[0-9]</code> means NIGINX will only respond if there is a number after the word "agatha":</p>
<pre><code class="lang-shell">curl -I http://nginx-handbook.test/agatha

# HTTP/1.1 404 Not Found
# Server: nginx/1.18.0 (Ubuntu)
# Date: Wed, 21 Apr 2021 16:14:29 GMT
# Content-Type: text/html
# Content-Length: 162
# Connection: keep-alive

curl -I http://nginx-handbook.test/agatha8

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Wed, 21 Apr 2021 16:15:04 GMT
# Content-Type: text/plain
# Content-Length: 29
# Connection: keep-alive
</code></pre>
<p>A regex match is by default case sensitive, which means that if you capitalize any of the letters, the location won't work:</p>
<pre><code class="lang-shell">curl -I http://nginx-handbook.test/Agatha8

# HTTP/1.1 404 Not Found
# Server: nginx/1.18.0 (Ubuntu)
# Date: Wed, 21 Apr 2021 16:14:29 GMT
# Content-Type: text/html
# Content-Length: 162
# Connection: keep-alive
</code></pre>
<p>To turn this into case insensitive, you'll have to add a <code>*</code> after the <code>~</code> sign.</p>
<pre><code class="lang-conf">events {

}

http {

    server {

        listen 80;
        server_name nginx-handbook.test;

        location ~* /agatha[0-9] {
            return 200 "Miss Marple.\nHercule Poirot.\n";
        }
    }

}
</code></pre>
<p>That will tell NGINX to let go of type sensitivity and match the location anyways.</p>
<pre><code class="lang-shell">curl -I http://nginx-handbook.test/agatha8

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Wed, 21 Apr 2021 16:15:04 GMT
# Content-Type: text/plain
# Content-Length: 29
# Connection: keep-alive

curl -I http://nginx-handbook.test/Agatha8

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Wed, 21 Apr 2021 16:15:04 GMT
# Content-Type: text/plain
# Content-Length: 29
# Connection: keep-alive
</code></pre>
<p>NGINX assigns priority values to these matches, and a regex match has more priority than a prefix match.</p>
<pre><code class="lang-conf">events {

}

http {

    server {

        listen 80;
        server_name nginx-handbook.test;

        location /Agatha8 {
            return 200 "prefix matched.\n";
        }

        location ~* /agatha[0-9] {
            return 200 "regex matched.\n";
        }
    }

}
</code></pre>
<p>Now if you send a request to http://nginx-handbook.test/Agatha8, you'll get the following response:</p>
<pre><code class="lang-shell">curl -i http://nginx-handbook.test/Agatha8

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Thu, 22 Apr 2021 08:08:18 GMT
# Content-Type: text/plain
# Content-Length: 15
# Connection: keep-alive

# regex matched.
</code></pre>
<p>But this priority can be changed a little. The final type of match in NGINX is a <strong>preferential prefix match</strong>. To turn a prefix match into a preferential one, you need to include the <code>^~</code> modifier before the location URI:</p>
<pre><code class="lang-conf">events {

}

http {

    server {

        listen 80;
        server_name nginx-handbook.test;

        location ^~ /Agatha8 {
            return 200 "prefix matched.\n";
        }

        location ~* /agatha[0-9] {
            return 200 "regex matched.\n";
        }
    }

}
</code></pre>
<p>Now if you send a request to http://nginx-handbook.test/Agatha8, you'll get the following response:</p>
<pre><code class="lang-shell">curl -i http://nginx-handbook.test/Agatha8

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Thu, 22 Apr 2021 08:13:24 GMT
# Content-Type: text/plain
# Content-Length: 16
# Connection: keep-alive

# prefix matched.
</code></pre>
<p>This time, the prefix match wins. So the list of all the matches in descending order of priority is as follows:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Match</td><td>Modifier</td></tr>
</thead>
<tbody>
<tr>
<td>Exact</td><td><code>=</code></td></tr>
<tr>
<td>Preferential Prefix</td><td><code>^~</code></td></tr>
<tr>
<td>REGEX</td><td><code>~</code> or <code>~*</code></td></tr>
<tr>
<td>Prefix</td><td><code>None</code></td></tr>
</tbody>
</table>
</div><h3 id="heading-variables-in-nginx">Variables in NGINX</h3>
<p>Variables in NGINX are similar to variables in other programming languages. The <code>set</code> directive can be used to declare new variables anywhere within the configuration file:</p>
<pre><code class="lang-conf">set $&lt;variable_name&gt; &lt;variable_value&gt;;

# set name "Farhan"
# set age 25
# set is_working true
</code></pre>
<p>Variables can be of three types</p>
<ul>
<li>String</li>
<li>Integer</li>
<li>Boolean</li>
</ul>
<p>Apart from the variables you declare, there are embedded variables within NGINX modules. An <a target="_blank" href="https://nginx.org/en/docs/varindex.html">alphabetical index of variables</a> is available in the official documentation.</p>
<p>To see some of the variables in action, update the configuration as follows:</p>
<pre><code class="lang-conf">events {

}

http {

    server {

        listen 80;
        server_name nginx-handbook.test;

        return 200 "Host - $host\nURI - $uri\nArgs - $args\n";
    }

}
</code></pre>
<p>Now upon sending a request to the server, you should get a response as follows:</p>
<pre><code class="lang-shell"># curl http://nginx-handbook.test/user?name=Farhan

# Host - nginx-handbook.test
# URI - /user
# Args - name=Farhan
</code></pre>
<p>As you can see, the <code>$host</code> and <code>$uri</code> variables hold the root address and the requested URI relative to the root, respectively. The <code>$args</code> variable, as you can see, contains all the query strings. </p>
<p>Instead of printing the literal string form of the query strings, you can access the individual values using the <code>$arg</code> variable.</p>
<pre><code class="lang-conf">events {

}

http {

    server {

        listen 80;
        server_name nginx-handbook.test;

        set $name $arg_name; # $arg_&lt;query string name&gt;

        return 200 "Name - $name\n";
    }

}
</code></pre>
<p>Now the response from the server should look like as follows:</p>
<pre><code class="lang-shell">curl http://nginx-handbook.test?name=Farhan

# Name - Farhan
</code></pre>
<p>The variables I demonstrated here are embedded in the <a target="_blank" href="https://nginx.org/en/docs/http/ngx_http_core_module.html">ngx_http_core_module</a>. For a variable to be accessible in the configuration, NGINX has to be built with the module embedding the variable. Building NGINX from source and usage of dynamic modules is slightly out of scope for this article. But I'll surely write about that in my blog.</p>
<h3 id="heading-redirects-and-rewrites">Redirects and Rewrites</h3>
<p>A redirect in NGINX is same as redirects in any other platform. To demonstrate how redirects work, update your configuration to look like this:</p>
<pre><code class="lang-conf">events {

}

http {

    include /etc/nginx/mime.types;

    server {

        listen 80;
        server_name nginx-handbook.test;

        root /srv/nginx-handbook-projects/static-demo;

        location = /index_page {
                return 307 /index.html;
        }

        location = /about_page {
                return 307 /about.html;
        }
    }
}
</code></pre>
<p>Now if you send a request to http://nginx-handbook.test/about_page, you'll be redirected to http://nginx-handbook.test/about.html:</p>
<pre><code class="lang-shell">curl -I http://nginx-handbook.test/about_page

# HTTP/1.1 307 Temporary Redirect
# Server: nginx/1.18.0 (Ubuntu)
# Date: Thu, 22 Apr 2021 18:02:04 GMT
# Content-Type: text/html
# Content-Length: 180
# Location: http://nginx-handbook.test/about.html
# Connection: keep-alive
</code></pre>
<p>As you can see, the server responded with a status code of 307 and the location indicates http://nginx-handbook.test/about.html. If you visit http://nginx-handbook.test/about_page from a browser, you'll see that the URL will automatically change to http://nginx-handbook.test/about.html.</p>
<p>A <code>rewrite</code> directive, however, works a little differently. It changes the URI internally, without letting the user know. To see it in action, update your configuration as follows:</p>
<pre><code class="lang-conf">events {

}

http {

    include /etc/nginx/mime.types;

    server {

        listen 80;
        server_name nginx-handbook.test;

        root /srv/nginx-handbook-projects/static-demo;

        rewrite /index_page /index.html;

        rewrite /about_page /about.html;
    }
}
</code></pre>
<p>Now if you send a request to http://nginx-handbook/about_page URI, you'll get a 200 response code and the HTML code for about.html file in response:</p>
<pre><code class="lang-shell">curl -i http://nginx-handbook.test/about_page

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Thu, 22 Apr 2021 18:09:31 GMT
# Content-Type: text/html
# Content-Length: 960
# Last-Modified: Wed, 21 Apr 2021 11:27:06 GMT
# Connection: keep-alive
# ETag: "60800c0a-3c0"
# Accept-Ranges: bytes

# &lt;!DOCTYPE html&gt;
# &lt;html lang="en"&gt;
# &lt;head&gt;
#     &lt;meta charset="UTF-8"&gt;
#     &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt;
#     &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
#     &lt;title&gt;NGINX Handbook Static Demo&lt;/title&gt;
#     &lt;link rel="stylesheet" href="mini.min.css"&gt;
#     &lt;style&gt;
#         .container {
#             max-width: 1024px;
#             margin-left: auto;
#             margin-right: auto;
#         }
# 
#         h1 {
#             text-align: center;
#         }
#     &lt;/style&gt;
# &lt;/head&gt;
# &lt;body class="container"&gt;
#     &lt;header&gt;
#         &lt;a class="button" href="index.html"&gt;Index&lt;/a&gt;
#         &lt;a class="button" href="about.html"&gt;About&lt;/a&gt;
#         &lt;a class="button" href="nothing"&gt;Nothing&lt;/a&gt;
#     &lt;/header&gt;
#     &lt;div class="card fluid"&gt;
#         &lt;img src="./the-nginx-handbook.jpg" alt="The NGINX Handbook Cover Image"&gt;
#     &lt;/div&gt;
#     &lt;div class="card fluid"&gt;
#         &lt;h1&gt;this is the &lt;strong&gt;about.html&lt;/strong&gt; file&lt;/h1&gt;
#     &lt;/div&gt;
# &lt;/body&gt;
# &lt;/html&gt;
</code></pre>
<p>And if you visit the URI using a browser, you'll see the about.html page while the URL remains unchanged:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/rewrite.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Apart from the way the URI change is handled, there is another difference between a redirect and rewrite. When a rewrite happens, the <code>server</code> context gets re-evaluated by NGINX. So, a rewrite is a more expensive operation than a redirect.</p>
<h3 id="heading-how-to-try-for-multiple-files">How to Try for Multiple Files</h3>
<p>The final concept I'll be showing in this section is the <code>try_files</code> directive. Instead of responding with a single file, the <code>try_files</code> directive lets you check for the existence of multiple files.</p>
<pre><code class="lang-conf">events {

}

http {

    include /etc/nginx/mime.types;

    server {

        listen 80;
        server_name nginx-handbook.test;

        root /srv/nginx-handbook-projects/static-demo;

        try_files /the-nginx-handbook.jpg /not_found;

        location /not_found {
                return 404 "sadly, you've hit a brick wall buddy!\n";
        }
    }
}
</code></pre>
<p>As you can see, a new <code>try_files</code> directive has been added. By writing <code>try_files /the-nginx-handbook.jpg /not_found;</code> you're instructing NGINX to look for a file named the-nginx-handbook.jpg on the root whenever a request is received. If it doesn't exist, go to the <code>/not_found</code> location. </p>
<p>So now if you visit the server, you'll see the image:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/image-94.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>But if you update the configuration to try for a non-existent file such as blackhole.jpg, you'll get a 404 response with the message "sadly, you've hit a brick wall buddy!".</p>
<p>Now the problem with writing a <code>try_files</code> directive this way is that no matter what URL you visit, as long as a request is received by the server and the the-nginx-handbook.jpg file is found on the disk, NGINX will send that back.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/try-files.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And that's why <code>try_files</code> is often used with the <code>$uri</code> NGINX variable. </p>
<pre><code class="lang-conf">events {

}

http {

    include /etc/nginx/mime.types;

    server {

        listen 80;
        server_name nginx-handbook.test;

        root /srv/nginx-handbook-projects/static-demo;

        try_files $uri /not_found;

        location /not_found {
                return 404 "sadly, you've hit a brick wall buddy!\n";
        }
    }
}
</code></pre>
<p>By writing <code>try_files $uri /not_found;</code> you're instructing NGINX to try for the URI requested by the client first. If it doesn't find that one, then try the next one.</p>
<p>So now if you visit http://nginx-handbook.test/index.html you should get the old index.html page. The same goes for the about.html page:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/image-95.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>But if you request a file that doesn't exist, you'll get the response from the <code>/not_found</code> location:</p>
<pre><code class="lang-shell">curl -i http://nginx-handbook.test/nothing

# HTTP/1.1 404 Not Found
# Server: nginx/1.18.0 (Ubuntu)
# Date: Thu, 22 Apr 2021 20:01:57 GMT
# Content-Type: text/plain
# Content-Length: 38
# Connection: keep-alive

# sadly, you've hit a brick wall buddy!
</code></pre>
<p>One thing that you may have already noticed is that if you visit the server root http://nginx-handbook.test, you get the 404 response.</p>
<p>This is because when you're hitting the server root, the <code>$uri</code> variable doesn't correspond to any existing file so NGINX serves you the fallback location. If you want to fix this issue, update your configuration as follows:</p>
<pre><code class="lang-conf">events {

}

http {

    include /etc/nginx/mime.types;

    server {

        listen 80;
        server_name nginx-handbook.test;

        root /srv/nginx-handbook-projects/static-demo;

        try_files $uri $uri/ /not_found;

        location /not_found {
                return 404 "sadly, you've hit a brick wall buddy!\n";
        }
    }
}
</code></pre>
<p>By writing <code>try_files $uri $uri/ /not_found;</code> you're instructing NGINX to try for the requested URI first. If that doesn't work then try for the requested URI as a directory, and whenever NGINX ends up into a directory it automatically starts looking for an index.html file.</p>
<p>Now if you visit the server, you should get the index.html file just right:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/image-95.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The <code>try_files</code> is the kind of directive that can be used in a number of variations. In the upcoming sections, you'll encounter a few other variations but I would suggest that you do some research on the internet regarding the different usage of this directive by yourself.</p>
<h2 id="heading-logging-in-nginx">Logging in NGINX</h2>
<p>By default, NGINX's log files are located inside <code>/var/log/nginx</code>. If you list the content of this directory, you may see something as follows:</p>
<pre><code class="lang-shell">ls -lh /var/log/nginx/

# -rw-r----- 1 www-data adm     0 Apr 25 07:34 access.log
# -rw-r----- 1 www-data adm     0 Apr 25 07:34 error.log
</code></pre>
<p>Let's begin by emptying the two files.</p>
<pre><code class="lang-shell"># delete the old files
sudo rm /var/log/nginx/access.log /var/log/nginx/error.log

# create new files
sudo touch /var/log/nginx/access.log /var/log/nginx/error.log

# reopen the log files
sudo nginx -s reopen
</code></pre>
<p>If you do not dispatch a <code>reopen</code> signal to NGINX, it'll keep writing logs to the previously open streams and the new files will remain empty.</p>
<p>Now to make an entry in the access log, send a request to the server.</p>
<pre><code>curl -I http:<span class="hljs-comment">//nginx-handbook.test</span>

# HTTP/<span class="hljs-number">1.1</span> <span class="hljs-number">200</span> OK
# Server: nginx/<span class="hljs-number">1.18</span><span class="hljs-number">.0</span> (Ubuntu)
# <span class="hljs-built_in">Date</span>: Sun, <span class="hljs-number">25</span> Apr <span class="hljs-number">2021</span> <span class="hljs-number">08</span>:<span class="hljs-number">35</span>:<span class="hljs-number">59</span> GMT
# Content-Type: text/html
# Content-Length: <span class="hljs-number">960</span>
# Last-Modified: Sun, <span class="hljs-number">25</span> Apr <span class="hljs-number">2021</span> <span class="hljs-number">08</span>:<span class="hljs-number">35</span>:<span class="hljs-number">33</span> GMT
# Connection: keep-alive
# ETag: <span class="hljs-string">"608529d5-3c0"</span>
# Accept-Ranges: bytes

sudo cat /<span class="hljs-keyword">var</span>/log/nginx/access.log 

# <span class="hljs-number">192.168</span><span class="hljs-number">.20</span><span class="hljs-number">.20</span> - - [<span class="hljs-number">25</span>/Apr/<span class="hljs-number">2021</span>:<span class="hljs-number">08</span>:<span class="hljs-number">35</span>:<span class="hljs-number">59</span> +<span class="hljs-number">0000</span>] <span class="hljs-string">"HEAD / HTTP/1.1"</span> <span class="hljs-number">200</span> <span class="hljs-number">0</span> <span class="hljs-string">"-"</span> <span class="hljs-string">"curl/7.68.0"</span>
</code></pre><p>As you can see, a new entry has been added to the access.log file. Any request to the server will be logged to this file by default. But we can change this behavior using the <code>access_log</code> directive.</p>
<pre><code class="lang-conf">events {

}

http {

    include /etc/nginx/mime.types;

    server {

        listen 80;
        server_name nginx-handbook.test;

        location / {
            return 200 "this will be logged to the default file.\n";
        }

        location = /admin {
            access_log /var/logs/nginx/admin.log;

            return 200 "this will be logged in a separate file.\n";
        }

        location = /no_logging {
            access_log off;

            return 200 "this will not be logged.\n";
        }
    }
}
</code></pre>
<p>The first <code>access_log</code> directive inside the /admin location block instructs NGINX to write any access log of this URI to the <code>/var/logs/nginx/admin.log</code> file. The second one inside the /no_logging location turns off access logs for this location completely.</p>
<p>Validate and reload the configuration. Now if you send requests to these locations and inspect the log files, you should see something like this:</p>
<pre><code class="lang-shell">curl http://nginx-handbook.test/no_logging
# this will not be logged

sudo cat /var/log/nginx/access.log
# empty

curl http://nginx-handbook.test/admin
# this will be logged in a separate file.

sudo cat /var/log/nginx/access.log
# empty

sudo cat /var/log/nginx/admin.log 
# 192.168.20.20 - - [25/Apr/2021:11:13:53 +0000] "GET /admin HTTP/1.1" 200 40 "-" "curl/7.68.0"

curl  http://nginx-handbook.test/
# this will be logged to the default file.

sudo cat /var/log/nginx/access.log 
# 192.168.20.20 - - [25/Apr/2021:11:15:14 +0000] "GET / HTTP/1.1" 200 41 "-" "curl/7.68.0"
</code></pre>
<p>The error.log file, on the other hand, holds the failure logs. To make an entry to the error.log, you'll have to make NGINX crash. To do so, update your configuration as follows:</p>
<pre><code class="lang-conf">events {

}

http {

    include /etc/nginx/mime.types;

    server {

        listen 80;
        server_name nginx-handbook.test;

        return 200 "..." "...";
    }

}
</code></pre>
<p>As you know, the <code>return</code> directive takes only two parameters – but we've given three here. Now try reloading the configuration and you'll be presented with an error message:</p>
<pre><code class="lang-shell">sudo nginx -s reload

# nginx: [emerg] invalid number of arguments in "return" directive in /etc/nginx/nginx.conf:14
</code></pre>
<p>Check the content of the error log and the message should be present there as well:</p>
<pre><code class="lang-shell">sudo cat /var/log/nginx/error.log 

# 2021/04/25 08:35:45 [notice] 4169#4169: signal process started
# 2021/04/25 10:03:18 [emerg] 8434#8434: invalid number of arguments in "return" directive in /etc/nginx/nginx.conf:14
</code></pre>
<p>Error messages have levels. A <code>notice</code> entry in the error log is harmless, but an <code>emerg</code> or emergency entry has to be addressed right away. </p>
<p>There are eight levels of error messages:</p>
<ul>
<li><code>debug</code> – Useful debugging information to help determine where the problem lies.</li>
<li><code>info</code> – Informational messages that aren't necessary to read but may be good to know.</li>
<li><code>notice</code> – Something normal happened that is worth noting.</li>
<li><code>warn</code> – Something unexpected happened, however is not a cause for concern.</li>
<li><code>error</code> – Something was unsuccessful.</li>
<li><code>crit</code> – There are problems that need to be critically addressed.</li>
<li><code>alert</code> – Prompt action is required.</li>
<li><code>emerg</code> – The system is in an unusable state and requires immediate attention.</li>
</ul>
<p>By default, NGINX records all level of messages. You can override this behavior using the <code>error_log</code> directive. If you want to set the minimum level of a message to be <code>warn</code>, then update your configuration file as follows:</p>
<pre><code class="lang-conf">events {

}

http {

    include /etc/nginx/mime.types;

    server {

        listen 80;
        server_name nginx-handbook.test;

        error_log /var/log/error.log warn;

        return 200 "..." "...";
    }

}
</code></pre>
<p>Validate and reload the configuration, and from now on only messages with a level of <code>warn</code> or above will be logged.</p>
<pre><code class="lang-shell">cat /var/log/nginx/error.log

# 2021/04/25 11:27:02 [emerg] 12769#12769: invalid number of arguments in "return" directive in /etc/nginx/nginx.conf:16
</code></pre>
<p>Unlike the previous output, there are no <code>notice</code> entries here. <code>emerg</code> is a higher level error than <code>warn</code> and that's why it has been logged.</p>
<p>For most projects, leaving the error configuration as it is should be fine. The only suggestion I have is to set the minimum error level to <code>warn</code>. This way you won't have to look at unnecessary entries in the error log. </p>
<p>But if you want to learn more about customizing logging in NGINX, this <a target="_blank" href="https://docs.nginx.com/nginx/admin-guide/monitoring/logging/">link</a> to the official docs may help.</p>
<h2 id="heading-how-to-use-nginx-as-a-reverse-proxy">How to Use NGINX as a Reverse Proxy</h2>
<p>When configured as a reverse proxy, NGINX sits between the client and a back end server. The client sends requests to NGINX, then NGINX passes the request to the back end.</p>
<p>Once the back end server finishes processing the request, it sends it back to NGINX. In turn, NGINX returns the response to the client. </p>
<p>During the whole process, the client doesn't have any idea about who's actually processing the request. It sounds complicated in writing, but once you do it for yourself you'll see how easy NGINX makes it.</p>
<p>Let's see a very basic and impractical example of a reverse proxy:</p>
<pre><code class="lang-conf">events {

}

http {

    include /etc/nginx/mime.types;

    server {
        listen 80;
        server_name nginx.test;

        location / {
                proxy_pass "https://nginx.org/";
        }
    }
}
</code></pre>
<p>Apart from validating and reloading the configuration, you'll also have to add this address to your <code>hosts</code> file to make this demo work on your system:</p>
<pre><code class="lang-hosts">192.168.20.20   nginx.test
</code></pre>
<p>Now if you visit http://nginx.test, you'll be greeted by the original <a target="_blank" href="https://nginx.org">https://nginx.org</a> site while the URI remains unchanged.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/nginx-org-proxy.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You should be even able to navigate around the site to an extent. If you visit http://nginx.test/en/docs/ you should get the <a target="_blank" href="http://nginx.org/en/docs/">http://nginx.org/en/docs/</a> page in response.</p>
<p>So as you can see, at a basic level, the <code>proxy_pass</code> directive simply passes a client's request to a third party server and reverse proxies the response to the client.</p>
<h3 id="heading-nodejs-with-nginx">Node.js With NGINX</h3>
<p>Now that you know how to configure a basic reverse proxy server, you can serve a Node.js application reverse proxied by NGINX. I've added a demo application inside the repository that comes with this article.</p>
<blockquote>
<p>I'm assuming that you have experience with Node.js and know how to start a Node.js application using PM2.</p>
</blockquote>
<p>If you've already cloned the repository inside <code>/srv/nginx-handbook-projects</code> then the <code>node-js-demo</code> project should be available in the <code>/srv/nginx-handbook-projects/node-js-demo</code> directory.</p>
<p>For this demo to work, you'll need to install Node.js on your server. You can do that following the instructions found <a target="_blank" href="https://github.com/nodesource/distributions#debinstall">here</a>.</p>
<p>The demo application is a simple HTTP server that responds with a 200 status code and a JSON payload. You can start the application by simply executing <code>node app.js</code> but a better way is to use <a target="_blank" href="https://pm2.keymetrics.io">PM2</a>.</p>
<p>For those of you who don't know, PM2 is a daemon process manager widely used in production for Node.js applications. If you want to learn more, this <a target="_blank" href="https://pm2.keymetrics.io/docs/usage/quick-start/">link</a> may help.</p>
<p>Install PM2 globally by executing <code>sudo npm install -g pm2</code>. After the installation is complete, execute following command while being inside the <code>/srv/nginx-handbook-projects/node-js-demo</code> directory:</p>
<pre><code class="lang-shell">pm2 start app.js

# [PM2] Process successfully started
# ┌────┬────────────────────┬──────────┬──────┬───────────┬──────────┬──────────┐
# │ id │ name               │ mode     │ ↺    │ status    │ cpu      │ memory   │
# ├────┼────────────────────┼──────────┼──────┼───────────┼──────────┼──────────┤
# │ 0  │ app                │ fork     │ 0    │ online    │ 0%       │ 21.2mb   │
# └────┴────────────────────┴──────────┴──────┴───────────┴──────────┴──────────┘
</code></pre>
<p>Alternatively you can also do <code>pm2 start /srv/nginx-handbook-projects/node-js-demo/app.js</code> from anywhere on the server. You can stop the application by executing the <code>pm2 stop app</code> command.</p>
<p>The application should be running now but should not be accessible from outside of the server. To verify if the application is running or not, send a get request to http://localhost:3000 from inside your server:</p>
<pre><code class="lang-shell">curl -i localhost:3000

# HTTP/1.1 200 OK
# X-Powered-By: Express
# Content-Type: application/json; charset=utf-8
# Content-Length: 62
# ETag: W/"3e-XRN25R5fWNH2Tc8FhtUcX+RZFFo"
# Date: Sat, 24 Apr 2021 12:09:55 GMT
# Connection: keep-alive
# Keep-Alive: timeout=5

# { "status": "success", "message": "You're reading The NGINX Handbook!" }
</code></pre>
<p>If you get a 200 response, then the server is running fine. Now to configure NGINX as a reverse proxy, open your configuration file and update its content as follows:</p>
<pre><code class="lang-conf">events {

}

http {
    listen 80;
    server_name nginx-handbook.test

    location / {
        proxy_pass http://localhost:3000;
    }
}
</code></pre>
<p>Nothing new to explain here. You're just passing the received request to the Node.js application running at port 3000. Now if you send a request to the server from outside you should get a response as follows:</p>
<pre><code class="lang-shell">curl -i http://nginx-handbook.test

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Sat, 24 Apr 2021 14:58:01 GMT
# Content-Type: application/json
# Transfer-Encoding: chunked
# Connection: keep-alive

# { "status": "success", "message": "You're reading The NGINX Handbook!" }
</code></pre>
<p>Although this works for a basic server like this, you may have to add a few more directives to make it work in a real world scenario depending on your application's requirements. </p>
<p>For example, if your application handles web socket connections, then you should update the configuration as follows:</p>
<pre><code class="lang-conf">events {

}

http {
    listen 80;
    server_name nginx-handbook.test

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
    }
}
</code></pre>
<p>The <code>proxy_http_version</code> directive sets the HTTP version for the server. By default it's 1.0, but web socket requires it to be at least 1.1. The <code>proxy_set_header</code> directive is used for setting a header on the back-end server. Generic syntax for this directive is as follows:</p>
<pre><code class="lang-conf">proxy_set_header &lt;header name&gt; &lt;header value&gt;
</code></pre>
<p>So, by writing <code>proxy_set_header Upgrade $http_upgrade;</code> you're instructing NGINX to pass the value of the <code>$http_upgrade</code> variable as a header named <code>Upgrade</code> – same for the <code>Connection</code> header. </p>
<p>If you would like to learn more about web socket proxying, this <a target="_blank" href="https://nginx.org/en/docs/http/websocket.html">link</a> to the official NGINX docs may help.</p>
<p>Depending on the headers required by your application, you may have to set more of them. But the above mentioned configuration is very commonly used to serve Node.js applications.</p>
<h3 id="heading-php-with-nginx">PHP With NGINX</h3>
<p>PHP and NGINX go together like bread and butter. After all the E and the P in the LEMP stack stand for NGINX and PHP.</p>
<blockquote>
<p>I'm assuming you have experience with PHP and know how to run a PHP application.</p>
</blockquote>
<p>I've already included a demo PHP application in the repository that comes with this article. If you've already cloned it in the <code>/srv/nginx-handbook-projects</code> directory, then the application should be inside <code>/srv/nginx-handbook-projects/php-demo</code>.</p>
<p>For this demo to work, you'll have to install a package called PHP-FPM. To install the package, you can execute following command:</p>
<pre><code class="lang-shell">sudo apt install php-fpm -y
</code></pre>
<p>To test out the application, start a PHP server by executing the following command while inside the <code>/srv/nginx-handbook-projects/php-demo</code> directory:</p>
<pre><code class="lang-shell">php -S localhost:8000

# [Sat Apr 24 16:17:36 2021] PHP 7.4.3 Development Server (http://localhost:8000) started
</code></pre>
<p>Alternatively you can also do <code>php -S localhost:8000 /srv/nginx-handbook-projects/php-demo/index.php</code> from anywhere on the server.</p>
<p>The application should be running at port 8000 but it can not be accessed from the outside of the server. To verify, send a get request to http://localhost:8000 from inside your server:</p>
<pre><code class="lang-shell">curl -I localhost:8000

# HTTP/1.1 200 OK
# Host: localhost:8000
# Date: Sat, 24 Apr 2021 16:22:42 GMT
# Connection: close
# X-Powered-By: PHP/7.4.3
# Content-type: application/json

# {"status":"success","message":"You're reading The NGINX Handbook!"}
</code></pre>
<p>If you get a 200 response then the server is running fine. Just like the Node.js configuration, now you can simply <code>proxy_pass</code> the requests to localhost:8000 – but with PHP, there is a better way.</p>
<p>The FPM part in PHP-FPM stands for FastCGI Process Module. FastCGI is a protocol just like HTTP for exchanging binary data. This protocol is slightly faster than HTTP and provides better security. </p>
<p>To use FastCGI instead of HTTP, update your configuration as follows:</p>
<pre><code class="lang-conf">events {

}

http {

      include /etc/nginx/mime.types;

      server {

          listen 80;
          server_name nginx-handbook.test;
          root /srv/nginx-handbook-projects/php-demo;

          index index.php;

          location / {
              try_files $uri $uri/ =404;
          }

          location ~ \.php$ {
              fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
              fastcgi_param REQUEST_METHOD $request_method;
              fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
      }
   }
}
</code></pre>
<p>Let's begin with the new <code>index</code> directive. As you know, NGINX by default looks for an index.html file to serve. But in the demo-project, it's called index.php. So by writing <code>index index.php</code>, you're instructing NGINX to use the index.php file as root instead. </p>
<p>This directive can accept multiple parameters. If you write something like <code>index index.php index.html</code>, NGINX will first look for index.php. If it doesn't find that file, it will look for an index.html file.</p>
<p>The <code>try_files</code> directive inside the first <code>location</code> context is the same as you've seen in a previous section. The <code>=404</code> at the end indicates the error to throw if none of the files are found.</p>
<p>The second <code>location</code> block is the place where the main magic happens. As you can see, we've replaced the <code>proxy_pass</code> directive by a new <code>fastcgi_pass</code>. As the name suggests, it's used to pass a request to a FastCGI service.</p>
<p>The PHP-FPM service by default runs on port 9000 of the host. So instead of using a Unix socket like I've done here, you can pass the request to <code>http://localhost:9000</code> directly. But using a Unix socket is more secure.</p>
<p>If you have multiple PHP-FPM versions installed, you can simply list all the socket file locations by executing the following command:</p>
<pre><code class="lang-shell">sudo find / -name *fpm.sock

# /run/php/php7.4-fpm.sock
# /run/php/php-fpm.sock
# /etc/alternatives/php-fpm.sock
# /var/lib/dpkg/alternatives/php-fpm.sock
</code></pre>
<p>The <code>/run/php/php-fpm.sock</code> file refers to the latest version of PHP-FPM installed on your system. I prefer using the one with the version number. This way even if PHP-FPM gets updated, I'll be certain about the version I'm using.</p>
<p>Unlike passing requests through HTTP, passing requests through FPM requires us to pass some extra information. </p>
<p>The general way of passing extra information to the FPM service is using the <code>fastcgi_param</code> directive. At the very least, you'll have to pass the request method and the script name to the back-end service for the proxying to work. </p>
<p>The <code>fastcgi_param REQUEST_METHOD $request_method;</code> passes the request method to the back-end and the <code>fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;</code> line passes the exact location of the PHP script to run.</p>
<p>At this state, your configuration should work. To test it out, visit your server and you should be greeted by something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/500-on-fastcgi.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Well, that's weird. A 500 error means NGINX has crashed for some reason. This is where the error logs can come in handy. Let's have a look at the last entry in the error.log file:</p>
<pre><code class="lang-shell">tail -n 1 /var/log/nginx/error.log

# 2021/04/24 17:15:17 [crit] 17691#17691: *21 connect() to unix:/var/run/php/php7.4-fpm.sock failed (13: Permission denied) while connecting to upstream, client: 192.168.20.20, server: nginx-handbook.test, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.4-fpm.sock:", host: "nginx-handbook.test"
</code></pre>
<p>Seems like the NGINX process is being denied permission to access the PHP-FPM process.</p>
<p>One of the main reasons for getting a permission denied error is user mismatch. Have a look at the user owning the NGINX worker process.</p>
<pre><code class="lang-shell">ps aux | grep nginx

# root         677  0.0  0.4   8892  4260 ?        Ss   14:31   0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
# nobody     17691  0.0  0.3   9328  3452 ?        S    17:09   0:00 nginx: worker process
# vagrant    18224  0.0  0.2   8160  2552 pts/0    S+   17:19   0:00 grep --color=auto nginx
</code></pre>
<p>As you can see, the process is currently owned by <code>nobody</code>. Now inspect the PHP-FPM process.</p>
<pre><code class="lang-shell"># ps aux | grep php

# root       14354  0.0  1.8 195484 18924 ?        Ss   16:11   0:00 php-fpm: master process (/etc/php/7.4/fpm/php-fpm.conf)
# www-data   14355  0.0  0.6 195872  6612 ?        S    16:11   0:00 php-fpm: pool www
# www-data   14356  0.0  0.6 195872  6612 ?        S    16:11   0:00 php-fpm: pool www
# vagrant    18296  0.0  0.0   8160   664 pts/0    S+   17:20   0:00 grep --color=auto php
</code></pre>
<p>This process, on the other hand, is owned by the <code>www-data</code> user. This is why NGINX is being denied access to this process.</p>
<p>To solve this issue, update your configuration as follows:</p>
<pre><code class="lang-conf">user www-data;

events {

}

http {

      include /etc/nginx/mime.types;

      server {

          listen 80;
          server_name nginx-handbook.test;
          root /srv/nginx-handbook-projects/php-demo;

          index index.php;

          location / {
              try_files $uri $uri/ =404;
          }

          location ~ \.php$ {
              fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
              fastcgi_param REQUEST_METHOD $request_method;
              fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
      }
   }
}
</code></pre>
<p>The <code>user</code> directive is responsible for setting the owner for the NGINX worker processes. Now inspect the the NGINX process once again:</p>
<pre><code class="lang-shell"># ps aux | grep nginx

# root         677  0.0  0.4   8892  4264 ?        Ss   14:31   0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
# www-data   20892  0.0  0.3   9292  3504 ?        S    18:10   0:00 nginx: worker process
# vagrant    21294  0.0  0.2   8160  2568 pts/0    S+   18:18   0:00 grep --color=auto nginx
</code></pre>
<p>Undoubtedly the process is now owned by the <code>www-data</code> user. Send a request to your server to check if it's working or not:</p>
<pre><code class="lang-shell"># curl -i http://nginx-handbook.test

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Sat, 24 Apr 2021 18:22:24 GMT
# Content-Type: application/json
# Transfer-Encoding: chunked
# Connection: keep-alive

# {"status":"success","message":"You're reading The NGINX Handbook!"}
</code></pre>
<p>If you get a 200 status code with a JSON payload, you're good to go. </p>
<p>This simple configuration is fine for the demo application, but in real-life projects you'll have to pass some additional parameters.</p>
<p>For this reason, NGINX includes a partial configuration called <code>fastcgi_params</code>. This file contains a list of the most common FastCGI parameters.</p>
<pre><code class="lang-shell">cat /etc/nginx/fastcgi_params

# fastcgi_param  QUERY_STRING       $query_string;
# fastcgi_param  REQUEST_METHOD     $request_method;
# fastcgi_param  CONTENT_TYPE       $content_type;
# fastcgi_param  CONTENT_LENGTH     $content_length;

# fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
# fastcgi_param  REQUEST_URI        $request_uri;
# fastcgi_param  DOCUMENT_URI       $document_uri;
# fastcgi_param  DOCUMENT_ROOT      $document_root;
# fastcgi_param  SERVER_PROTOCOL    $server_protocol;
# fastcgi_param  REQUEST_SCHEME     $scheme;
# fastcgi_param  HTTPS              $https if_not_empty;

# fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
# fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

# fastcgi_param  REMOTE_ADDR        $remote_addr;
# fastcgi_param  REMOTE_PORT        $remote_port;
# fastcgi_param  SERVER_ADDR        $server_addr;
# fastcgi_param  SERVER_PORT        $server_port;
# fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
# fastcgi_param  REDIRECT_STATUS    200;
</code></pre>
<p>As you can see, this file also contains the <code>REQUEST_METHOD</code> parameter. Instead of passing that manually, you can just include this file in your configuration:</p>
<pre><code class="lang-conf">user www-data;

events {

}

http {

      include /etc/nginx/mime.types;

      server {

          listen 80;
          server_name nginx-handbook.test;
          root /srv/nginx-handbook-projects/php-demo;

          index index.php;

          location / {
              try_files $uri $uri/ =404;
          }

          location ~ \.php$ {
              fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
              fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
              include /etc/nginx/fastcgi_params;
      }
   }
}
</code></pre>
<p>Your server should behave just the same. Apart from the <code>fastcgi_params</code> file, you may also come across the <code>fastcgi.conf</code> file which contains a slightly different set of parameters. I would suggest that you avoid that due to some inconsistencies with its behavior.</p>
<h2 id="heading-how-to-use-nginx-as-a-load-balancer">How to Use NGINX as a Load Balancer</h2>
<p>Thanks to the reverse proxy design of NGINX, you can easily configure it as a load balancer.</p>
<p>I've already added a demo to the repository that comes with this article. If you've already cloned the repository inside the <code>/srv/nginx-handbook-projects/</code> directory then the demo should be in the <code>/srv/nginx-handbook-projects/load-balancer-demo/</code> directory.</p>
<p>In a real life scenario, load balancing may be required on large scale projects distributed across multiple servers. But for this simple demo, I've created three very simple Node.js servers responding with a server number and 200 status code.</p>
<p>For this demo to work, you'll need Node.js installed on the server. You can find instructions in this <a target="_blank" href="https://github.com/nodesource/distributions#debinstall">link</a> to help you get it installed.</p>
<p>Apart from this, you'll also need <a target="_blank" href="https://pm2.keymetrics.io/">PM2</a> for daemonizing the Node.js servers provided in this demo.</p>
<p>If you haven't already, install PM2 by executing <code>sudo npm install -g pm2</code>. After the installation finishes, execute the following commands to start the three Node.js servers:</p>
<pre><code class="lang-shell">pm2 start /srv/nginx-handbook-projects/load-balancer-demo/server-1.js

pm2 start /srv/nginx-handbook-projects/load-balancer-demo/server-2.js

pm2 start /srv/nginx-handbook-projects/load-balancer-demo/server-3.js

pm2 list

# ┌────┬────────────────────┬──────────┬──────┬───────────┬──────────┬──────────┐
# │ id │ name               │ mode     │ ↺    │ status    │ cpu      │ memory   │
# ├────┼────────────────────┼──────────┼──────┼───────────┼──────────┼──────────┤
# │ 0  │ server-1           │ fork     │ 0    │ online    │ 0%       │ 37.4mb   │
# │ 1  │ server-2           │ fork     │ 0    │ online    │ 0%       │ 37.2mb   │
# │ 2  │ server-3           │ fork     │ 0    │ online    │ 0%       │ 37.1mb   │
# └────┴────────────────────┴──────────┴──────┴───────────┴──────────┴──────────┘
</code></pre>
<p>Three Node.js servers should be running on localhost:3001, localhost:3002, localhost:3003 respectively.</p>
<p>Now update your configuration as follows:</p>
<pre><code class="lang-conf">events {

}

http {

    upstream backend_servers {
        server localhost:3001;
        server localhost:3002;
        server localhost:3003;
    }

    server {

        listen 80;
        server_name nginx-handbook.test;

        location / {
            proxy_pass http://backend_servers;
        }
    }
}
</code></pre>
<p>The configuration inside the <code>server</code> context is the same as you've already seen. The <code>upstream</code> context, though, is new. An upstream in NGINX is a collection of servers that can be treated as a single backend.</p>
<p>So the three servers you started using PM2 can be put inside a single upstream and you can let NGINX balance the load between them.</p>
<p>To test out the configuration, you'll have to send a number of requests to the server. You can automate the process using a <code>while</code> loop in bash:</p>
<pre><code class="lang-shell">while sleep 0.5; do curl http://nginx-handbook.test; done

# response from server - 2.
# response from server - 3.
# response from server - 1.
# response from server - 2.
# response from server - 3.
# response from server - 1.
# response from server - 2.
# response from server - 3.
# response from server - 1.
# response from server - 2.
</code></pre>
<p>You can cancel the loop by hitting <code>Ctrl + C</code> on your keyboard. As you can see from the responses from the server, NGINX is load balancing the servers automatically.</p>
<p>Of course, depending on the project scale, load balancing can be a lot more complicated than this. But the goal of this article is to get you started, and I believe you now have a basic understanding of load balancing with NGINX. You can stop the three running server by executing <code>pm2 stop server-1 server-2 server-3</code> command (and it's a good idea here).</p>
<h2 id="heading-how-to-optimize-nginx-for-maximum-performance">How to Optimize NGINX for Maximum Performance</h2>
<p>In this section of the article, you'll learn about a number of ways to get the maximum performance from your server. </p>
<p>Some of these methods will be application-specific, which means they'll probably need tweaking considering your application requirements. But some of them will be general optimization techniques.</p>
<p>Just like the previous sections, changes in configuration will be frequesnt in this one, so don't forget to validate and reload your configuration file every time.</p>
<h3 id="heading-how-to-configure-worker-processes-and-worker-connections">How to Configure Worker Processes and Worker Connections</h3>
<p>As I've already mentioned in a previous section, NGINX can spawn multiple worker processes capable of handling thousands of requests each.</p>
<pre><code class="lang-shell">sudo systemctl status nginx

# ● nginx.service - A high performance web server and a reverse proxy server
#      Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
#      Active: active (running) since Sun 2021-04-25 08:33:11 UTC; 5h 45min ago
#        Docs: man:nginx(8)
#    Main PID: 3904 (nginx)
#       Tasks: 2 (limit: 1136)
#      Memory: 3.2M
#      CGroup: /system.slice/nginx.service
#              ├─ 3904 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
#              └─16443 nginx: worker process
</code></pre>
<p>As you can see, right now there is only one NGINX worker process on the system. This number, however, can be changed by making a small change to the configuration file.</p>
<pre><code class="lang-conf">worker_processes 2;

events {

}

http {

    server {

        listen 80;
        server_name nginx-handbook.test;

        return 200 "worker processes and worker connections configuration!\n";
    }
}
</code></pre>
<p>The <code>worker_process</code> directive written in the <code>main</code> context is responsible for setting the number of worker processes to spawn. Now check the NGINX service once again and you should see two worker processes:</p>
<pre><code class="lang-shell">sudo systemctl status nginx

# ● nginx.service - A high performance web server and a reverse proxy server
#      Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
#      Active: active (running) since Sun 2021-04-25 08:33:11 UTC; 5h 54min ago
#        Docs: man:nginx(8)
#     Process: 22610 ExecReload=/usr/sbin/nginx -g daemon on; master_process on; -s reload (code=exited, status=0/SUCCESS)
#    Main PID: 3904 (nginx)
#       Tasks: 3 (limit: 1136)
#      Memory: 3.7M
#      CGroup: /system.slice/nginx.service
#              ├─ 3904 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
#              ├─22611 nginx: worker process
#              └─22612 nginx: worker process
</code></pre>
<p>Setting the number of worker processes is easy, but determining the optimal number of worker processes requires a bit more work.</p>
<p>The worker processes are asynchronous in nature. This means that they will process incoming requests as fast as the hardware can. </p>
<p>Now consider that your server runs on a single core processor. If you set the number of worker processes to 1, that single process will utilize 100% of the CPU capacity. But if you set it to 2, the two processes will be able to utilize 50% of the CPU each. So increasing the number of worker processes doesn't mean better performance.</p>
<p>A rule of thumb in determining the optimal number of worker processes is <strong>number of worker process = number of CPU cores</strong>.</p>
<p>If you're running on a server with a dual core CPU, the number of worker processes should be set to 2. In a quad core it should be set to 4...and you get the idea.</p>
<p>Determining the number of CPUs on your server is very easy on Linux.</p>
<pre><code class="lang-shell">nproc

# 1
</code></pre>
<p>I'm on a single CPU virtual machine, so the <code>nproc</code> detects that there's one CPU. Now that you know the number of CPUs, all that is left to do is set the number on the configuration.</p>
<p>That's all well and good, but every time you upscale the server and the CPU number changes, you'll have to update the server configuration manually.</p>
<p>NGINX provides a better way to deal with this issue. You can simply set the number of worker processes to <code>auto</code> and NGINX will set the number of processes based on the number of CPUs automatically.</p>
<pre><code class="lang-conf">worker_processes auto;

events {

}

http {

    server {

        listen 80;
        server_name nginx-handbook.test;

        return 200 "worker processes and worker connections configuration!\n";
    }
}
</code></pre>
<p>Inspect the NGINX process once again:</p>
<pre><code class="lang-shell">sudo systemctl status nginx

# ● nginx.service - A high performance web server and a reverse proxy server
#      Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
#      Active: active (running) since Sun 2021-04-25 08:33:11 UTC; 6h ago
#        Docs: man:nginx(8)
#     Process: 22610 ExecReload=/usr/sbin/nginx -g daemon on; master_process on; -s reload (code=exited, status=0/SUCCESS)
#    Main PID: 3904 (nginx)
#       Tasks: 2 (limit: 1136)
#      Memory: 3.2M
#      CGroup: /system.slice/nginx.service
#              ├─ 3904 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
#              └─23659 nginx: worker process
</code></pre>
<p>The number of worker processes is back to one again, because that's what is optimal for this server.</p>
<p>Apart from the worker processes there is also the worker connection, indicating the highest number of connections a single worker process can handle. </p>
<p>Just like the number of worker processes, this number is also related to the number of your CPU core and the number of files your operating system is allowed to open per core.</p>
<p>Finding out this number is very easy on Linux:</p>
<pre><code class="lang-shell">ulimit -n

# 1024
</code></pre>
<p>Now that you have the number, all that is left is to set it in the configuration:</p>
<pre><code class="lang-conf">worker_processes auto;

events {
    worker_connections 1024;
}

http {

    server {

        listen 80;
        server_name nginx-handbook.test;

        return 200 "worker processes and worker connections configuration!\n";
    }
}
</code></pre>
<p>The <code>worker_connections</code> directive is responsible for setting the number of worker connections in a configuration. This is also the first time you're working with the <code>events</code> context. </p>
<p>In a previous section, I mentioned that this context is used for setting values used by NGINX on a general level. The worker connections configuration is one such example.</p>
<h3 id="heading-how-to-cache-static-content">How to Cache Static Content</h3>
<p>The second technique for optimizing your server is caching static content. Regardless of the application you're serving, there is always a certain amount of static content being served, such as stylesheets, images, and so on.</p>
<p>Considering that this content is not likely to change very frequently, it's a good idea to cache them for a certain amount of time. NGINX makes this task easy as well.</p>
<pre><code class="lang-conf">worker_processes auto;

events {
    worker_connections 1024;
}

http {

    include /env/nginx/mime.types;

    server {

        listen 80;
        server_name nginx-handbook.test;

        root /srv/nginx-handbook-demo/static-demo;

        location ~* \.(css|js|jpg)$ {
            access_log off;

            add_header Cache-Control public;
            add_header Pragma public;
            add_header Vary Accept-Encoding;
            expires 1M;
        }
    }
}
</code></pre>
<p>By writing <code>location ~* .(css|js|jpg)$</code> you're instructing NGINX to match requests asking for a file ending with <code>.css</code>, <code>.js</code> and <code>.jpg</code>. </p>
<p>In my applications, I usually store images in the <a target="_blank" href="https://developers.google.com/speed/webp">WebP</a> format even if the user submits a different format. This way, configuring the static cache becomes even easier for me.</p>
<p>You can use the <code>add_header</code> directive to include a header in the response to the client. Previously you've seen the <code>proxy_set_header</code> directive used for setting headers on an ongoing request to the backend server. The <code>add_header</code> directive on the other hand only adds a given header to the response.</p>
<p>By setting the <code>Cache-Control</code> header to public, you're telling the client that this content can be cached in any way. The <code>Pragma</code> header is just an older version of the <code>Cache-Control</code> header and does more or less the same thing. </p>
<p>The next header, <code>Vary</code>, is responsible for letting the client know that this cached content may vary. </p>
<p>The value of <code>Accept-Encoding</code> means that the content may vary depending on the content encoding accepted by the client. This will be clarified further in the next section.</p>
<p>Finally the <code>expires</code> directive allows you to set the <code>Expires</code> header conveniently. The <code>expires</code> directive takes the duration of time this cache will be valid. By setting it to <code>1M</code> you're telling NGINX to cache the content for one month. You can also set this to <code>10m</code> or 10 minutes, <code>24h</code> or 24 hours, and so on.</p>
<p>Now to test out the configuration, sent a request for the the-nginx-handbook.jpg file from the server:</p>
<pre><code class="lang-shell">curl -I http://nginx-handbook.test/the-nginx-handbook.jpg

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Sun, 25 Apr 2021 15:58:22 GMT
# Content-Type: image/jpeg
# Content-Length: 19209
# Last-Modified: Sun, 25 Apr 2021 08:35:33 GMT
# Connection: keep-alive
# ETag: "608529d5-4b09"
# Expires: Tue, 25 May 2021 15:58:22 GMT
# Cache-Control: max-age=2592000
# Cache-Control: public
# Pragma: public
# Vary: Accept-Encoding
# Accept-Ranges: bytes
</code></pre>
<p>As you can see, the headers have been added to the response and any modern browser should be able to interpret them.</p>
<h3 id="heading-how-to-compress-responses">How to Compress Responses</h3>
<p>The final optimization technique that I'm going to show today is a pretty straightforward one: compressing responses to reduce their size.</p>
<pre><code class="lang-conf">worker_processes auto;

events {
    worker_connections 1024;
}

http {
    include /env/nginx/mime.types;

    gzip on;
    gzip_comp_level 3;

    gzip_types text/css text/javascript;

    server {

        listen 80;
        server_name nginx-handbook.test;

        root /srv/nginx-handbook-demo/static-demo;

        location ~* \.(css|js|jpg)$ {
            access_log off;

            add_header Cache-Control public;
            add_header Pragma public;
            add_header Vary Accept-Encoding;
            expires 1M;
        }
    }
}
</code></pre>
<p>If you're not already familiar with it, <a target="_blank" href="https://www.gnu.org/software/gzip/">GZIP</a> is a popular file format used by applications for file compression and decompression. NGINX can utilize this format to compress responses using the <code>gzip</code> directives.</p>
<p>By writing <code>gzip on</code> in the <code>http</code> context, you're instructing NGINX to compress responses. The <code>gzip_comp_level</code> directive sets the level of compression. You can set it to a very high number, but that doesn't guarantee better compression. Setting a number between 1 - 4 gives you an efficient result. For example, I like setting it to 3.</p>
<p>By default, NGINX compresses HTML responses. To compress other file formats, you'll have to pass them as parameters to the <code>gzip_types</code> directive. By writing <code>gzip_types text/css text/javascript;</code> you're telling NGINX to compress any file with the mime types of text/css and text/javascript.</p>
<p>Configuring compression in NGINX is not enough. The client has to ask for the compressed response instead of the uncompressed responses. I hope you remember the <code>add_header Vary Accept-Encoding;</code> line in the previous section on caching. This header lets the client know that the response may vary based on what the client accepts.</p>
<p>As an example, if you want to request the uncompressed version of the mini.min.css file from the server, you may do something like this:</p>
<pre><code class="lang-shell">curl -I http://nginx-handbook.test/mini.min.css

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Sun, 25 Apr 2021 16:30:32 GMT
# Content-Type: text/css
# Content-Length: 46887
# Last-Modified: Sun, 25 Apr 2021 08:35:33 GMT
# Connection: keep-alive
# ETag: "608529d5-b727"
# Expires: Tue, 25 May 2021 16:30:32 GMT
# Cache-Control: max-age=2592000
# Cache-Control: public
# Pragma: public
# Vary: Accept-Encoding
# Accept-Ranges: bytes
</code></pre>
<p>As you can see, there's nothing about compression. Now if you want to ask for the compressed version of the file, you'll have to send an additional header.</p>
<pre><code class="lang-shell">curl -I -H "Accept-Encoding: gzip" http://nginx-handbook.test/mini.min.css

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Sun, 25 Apr 2021 16:31:38 GMT
# Content-Type: text/css
# Last-Modified: Sun, 25 Apr 2021 08:35:33 GMT
# Connection: keep-alive
# ETag: W/"608529d5-b727"
# Expires: Tue, 25 May 2021 16:31:38 GMT
# Cache-Control: max-age=2592000
# Cache-Control: public
# Pragma: public
# Vary: Accept-Encoding
# Content-Encoding: gzip
</code></pre>
<p>As you can see in the response headers, the <code>Content-Encoding</code> is now set to <code>gzip</code> meaning this is the compressed version of the file.</p>
<p>Now if you want to compare the difference in file size, you can do something like this:</p>
<pre><code class="lang-shell">cd ~
mkdir compression-test &amp;&amp; cd compression-test

curl http://nginx-handbook.test/mini.min.css &gt; uncompressed.css

curl -H "Accept-Encoding: gzip" http://nginx-handbook.test/mini.min.css &gt; compressed.css

ls -lh

# -rw-rw-r-- 1 vagrant vagrant 9.1K Apr 25 16:35 compressed.css
# -rw-rw-r-- 1 vagrant vagrant  46K Apr 25 16:35 uncompressed.css
</code></pre>
<p>The uncompressed version of the file is <code>46K</code> and the compressed version is <code>9.1K</code>, almost six times smaller. On real life sites where stylesheets can be much larger, compression can make your responses smaller and faster.</p>
<h2 id="heading-how-to-understand-the-main-configuration-file">How to Understand the Main Configuration File</h2>
<p>I hope you remember the original <code>nginx.conf</code> file you renamed in an earlier section. According to the <a target="_blank" href="https://wiki.debian.org/Nginx/DirectoryStructure">Debian wiki</a>, this file is meant to be changed by the NGINX maintainers and not by server administrators, unless they know exactly what they're doing.</p>
<p>But throughout the entire article, I've taught you to configure your servers in this very file. In this section, however, I'll who you how you should configure your servers without changing the <code>nginx.conf</code> file.</p>
<p>To begin with, first delete or rename your modified <code>nginx.conf</code> file and bring back the original one:</p>
<pre><code class="lang-shell">sudo rm /etc/nginx/nginx.conf

sudo mv /etc/nginx/nginx.conf.backup /etc/nginx/nginx.conf

sudo nginx -s reload
</code></pre>
<p>Now NGINX should go back to its original state. Let's have a look at the content of this file once again by executing the <code>sudo cat /etc/nginx/nginx.conf</code> file:</p>
<pre><code class="lang-conf">user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}


#mail {
#    # See sample authentication script at:
#    # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
# 
#    # auth_http localhost/auth.php;
#    # pop3_capabilities "TOP" "USER";
#    # imap_capabilities "IMAP4rev1" "UIDPLUS";
# 
#    server {
#        listen     localhost:110;
#        protocol   pop3;
#        proxy      on;
#    }
# 
#    server {
#        listen     localhost:143;
#        protocol   imap;
#        proxy      on;
#    }
#}
</code></pre>
<p>You should now be able to understand this file without much trouble. On the main context <code>user www-data;</code>, the <code>worker_processes auto;</code> lines should be easily recognizable to you. </p>
<p>The line <code>pid /run/nginx.pid;</code> sets the process ID for the NGINX process and <code>include /etc/nginx/modules-enabled/*.conf;</code> includes any configuration file found on the <code>/etc/nginx/modules-enabled/</code> directory. </p>
<p>This directory is meant for NGINX dynamic modules. I haven't covered dynamic modules in this article so I'll skip that.</p>
<p>Now inside the the <code>http</code> context, under basic settings you can see some common optimization techniques applied. Here's what these techniques do:</p>
<ul>
<li><code>sendfile on;</code> disables buffering for static files.</li>
<li><code>tcp_nopush on;</code> allows sending response header in one packet.</li>
<li><code>tcp_nodelay on;</code> disables <a target="_blank" href="https://en.wikipedia.org/wiki/Nagle's_algorithm">Nagle's Algorithm</a> resulting in faster static file delivery.</li>
</ul>
<p>The <code>keepalive_timeout</code> directive indicates how long to keep a connection open and the <code>types_hash_maxsize</code> directive sets the size of the types hash map. It also includes the <code>mime.types</code> file by default.</p>
<p>I'll skip the SSL settings simply because we haven't covered them in this article. We've already discussed the logging and gzip settings. You may see some of the directives regarding gzip as commented. As long as you understand what you're doing, you may customize these settings.</p>
<p>You use the <code>mail</code> context to configure NGINX as a mail server. We've only talked about NGINX as a web server so far, so I'll skip this as well.</p>
<p>Now under the virtual hosts settings, you should see two lines as follows:</p>
<pre><code class="lang-conf">##
# Virtual Host Configs
##

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
</code></pre>
<p>These two lines instruct NGINX to include any configuration files found inside the <code>/etc/nginx/conf.d/</code> and <code>/etc/nginx/sites-enabled/</code> directories.</p>
<p>After seeing these two lines, people often take these two directories as the ideal place to put their configuration files, but that's not right.</p>
<p>There is another directory <code>/etc/nginx/sites-available/</code> that's meant to store configuration files for your virtual hosts. The <code>/etc/nginx/sites-enabled/</code> directory is meant for storing the symbolic links to the files from the <code>/etc/nginx/sites-available/</code> directory. </p>
<p>In fact there is an example configuration:</p>
<pre><code class="lang-shell">ln -lh /etc/nginx/sites-enabled/

# lrwxrwxrwx 1 root root 34 Apr 25 08:33 default -&gt; /etc/nginx/sites-available/default
</code></pre>
<p>As you can see, the directory contains a symbolic link to the <code>/etc/nginx/sites-available/default</code> file.</p>
<p>The idea is to write multiple virtual hosts inside the <code>/etc/nginx/sites-available/</code> directory and make some of them active by symbolic linking them to the <code>/etc/nginx/sites-enabled/</code> directory.</p>
<p>To demonstrate this concept, let's configure a simple static server. First, delete the default virtual host symbolic link, deactivating this configuration in the process:</p>
<pre><code class="lang-shell">sudo rm /etc/nginx/sites-enabled/default

ls -lh /etc/nginx/sites-enabled/

# lrwxrwxrwx 1 root root 41 Apr 25 18:01 nginx-handbook -&gt; /etc/nginx/sites-available/nginx-handbook
</code></pre>
<p>Create a new file by executing <code>sudo touch /etc/nginx/sites-available/nginx-handbook</code> and put the following content in there:</p>
<pre><code>server {
    listen <span class="hljs-number">80</span>;
    server_name nginx-handbook.test;

    root /srv/nginx-handbook-projects/<span class="hljs-keyword">static</span>-demo;
}
</code></pre><p>Files inside the <code>/etc/nginx/sites-available/</code> directory are meant to be included within the main <code>http</code> context so they should contain <code>server</code> blocks only.</p>
<p>Now create a symbolic link to this file inside the <code>/etc/nginx/sites-enabled/</code> directory by executing the following command:</p>
<pre><code class="lang-shell">sudo ln -s /etc/nginx/sites-available/nginx-handbook /etc/nginx/sites-enabled/nginx-handbook

ls -lh /etc/nginx/sites-enabled/

# lrwxrwxrwx 1 root root 34 Apr 25 08:33 default -&gt; /etc/nginx/sites-available/default
# lrwxrwxrwx 1 root root 41 Apr 25 18:01 nginx-handbook -&gt; /etc/nginx/sites-available/nginx-handbook
</code></pre>
<p>Before validating and reloading the configuration file, you'll have to reopen the log files. Otherwise you may get a permission denied error. This happens because the process ID is different this time as a result of swapping the old <code>nginx.conf</code> file.</p>
<pre><code class="lang-shell">sudo rm /var/log/nginx/*.log

sudo touch /var/log/nginx/access.log /var/log/nginx/error.log

sudo nginx -s reopen
</code></pre>
<p>Finally, validate and reload the configuration file:</p>
<pre><code>sudo nginx -t

# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful

sudo nginx -s reload
</code></pre><p>Visit the server and you should be greeted with the good old The NGINX Handbook page:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/04/image-100.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you've configured the server correctly and you're still getting the old NGINX welcome page, perform a hard refresh. The browser often holds on to old assets and requires a little cleanup.</p>
<h2 id="heading-how-to-configure-ssl-and-http2">How To Configure SSL and HTTP/2</h2>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/HTTP/2">HTTP/2</a> is the newest version of the wildly popular Hyper Text Transport Protocol. Based on Google's experimental <a target="_blank" href="https://en.wikipedia.org/wiki/SPDY">SPDY</a> protocol, HTTP/2 provides better performance by introducing features like full request and response multiplexing, better compression of header fields, server push and request prioritization.</p>
<p>Some of the notable features of HTTP/2 is as follows:</p>
<ol>
<li><strong>Binary Protocol</strong> - While HTTP/1.x was a text based protocol, HTTP/2 is a binary protocol resulting in less error during data transfer process.</li>
<li><strong>Multiplexed Streams</strong> - All HTTP/2 connections are multiplexed streams meaning multiple files can be transferred in a single stream of binary data.</li>
<li><strong>Compressed Header</strong> - HTTP/2 compresses header data in responses resulting in faster transfer of data.</li>
<li><strong>Server Push</strong> - This capability allows the server to send linked resources to the client automatically, greatly reducing the number of requests to the server.</li>
<li><strong>Stream Prioritization</strong> - HTTP/2 can prioritize data streams based on their type resulting in better bandwidth allocation where necessary.</li>
</ol>
<blockquote>
<p>If you want to learn more about the improvements in HTTP/2 this <a target="_blank" href="https://kinsta.com/learn/what-is-http2/">article</a> by <a target="_blank" href="https://kinsta.com/">Kinsta</a> may help.</p>
</blockquote>
<p>While a significant upgrade over its predecessor, HTTP/2 is not as widely adapted as it should have been. In this section, I'll introduce you to some of the new features mentioned previously and I'll also show you how to enable HTTP/2 on your NGINX powered web server.</p>
<p>For this section, I'll be using the <code>static-demo</code> project. I'm assuming you've already cloned the repository inside <code>/srv/nginx-handbook-projects</code> directory. If you haven't, this is the time to do so. Also, this section has to be done on a virtual private server instead of a virtual machine.</p>
<p>For simplicity, I'll use the <code>/etc/nginx/sites-available/default</code> file as my configuration. Open the file using <code>nano</code> or <code>vi</code> if you fancy that.</p>
<pre><code class="lang-shell">nano /etc/nginx/sites-available/default
</code></pre>
<p>Update the file's content as follows:</p>
<pre><code class="lang-conf">server {
        listen 80;
        server_name nginx-handbook.farhan.dev;  

        root /srv/nginx-handbook-projects/static-demo;
}
</code></pre>
<p>As you can see, the <code>/srv/nginx-handbook-projects/static-demo;</code> directory has been set as the root of this site and <code>nginx-handbook.farhan.dev</code> has been set as the server name. If you do not have a custom domain set up, you can use your server's IP address as the server name here.</p>
<pre><code class="lang-shell">nginx -t

# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful

nginx -s reload
</code></pre>
<p>Test the configuration by executing <code>nginx -t</code> and reload the configuration by executing <code>nginx -s reload</code> commands.</p>
<p>Finally visit your server and you should be greeted with a simple static HTML page.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/OCHoJEYdm.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>One of the pre-requisite to have HTTP/2 working on your server is to have a valid SSL certificate. Lets do that first.</p>
<h3 id="heading-how-to-configure-ssl">How To Configure SSL</h3>
<p>For those of you who may not know, an SSL certificate is what allows a server to make the move from HTTP to HTTPS. These certificates are issued by a certificate authority (CA). Most of the authorities charge a fee for issuing certificates but nonprofit authorities such as <a target="_blank" href="https://letsencrypt.org/">Let's Encrypt</a>, issues certificates for free.</p>
<blockquote>
<p>If you want to understand the theory of SSL in a bit more detail, this <a target="_blank" href="https://www.cloudflare.com/learning/ssl/what-is-an-ssl-certificate/">article</a> on the <a target="_blank" href="https://www.cloudflare.com/learning/">Cloudflare Learning Center</a> may help.</p>
</blockquote>
<p>Thanks to open-source tools like <a target="_blank" href="https://github.com/certbot/certbot">Certbot</a>, installing a free certificate is dead easy. Head over to <a target="_blank" href="https://certbot.eff.org/">certbot.eff.org</a> link. Now select the software and system that powers your server.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/A13UVsSsE.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I'm running NGINX on Ubuntu 20.04 and if you've been in line with this article, you should have the same combination.</p>
<p>After selecting your combination of software and system, you'll be forwarded to a new page containing step by step instructions for installing certbot and a new SSL certificate.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/27NSXHEp2.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The installation steps for certbot may differ from system to system but rest of the instructions should remain same. On Ubuntu, the recommended way is to use <a target="_blank" href="https://snapcraft.io/">snap</a>.</p>
<pre><code class="lang-shell">snap install --classic certbot

# certbot 1.14.0 from Certbot Project (certbot-eff✓) installed

certbot --version

# certbot 1.14.0
</code></pre>
<p>Certbot is now installed and ready to be used. Before you install a new certificate, make sure the NGINX configuration file contains all the necessary server names. Such as, if you want to install a new certificate for <code>yourdomain.tld</code> and <code>www.yourdomain.tld</code>, you'll have to include both of them in your configuration.</p>
<p>Once you're happy with your configuration, you can install a newly provisioned certificate for your server. To do so, execute the <code>certbot</code> program with <code>--nginx</code> option.</p>
<pre><code class="lang-shell">certbot --nginx

# Saving debug log to /var/log/letsencrypt/letsencrypt.log
# Plugins selected: Authenticator nginx, Installer nginx
# Enter email address (used for urgent renewal and security notices)
#  (Enter 'c' to cancel): shovik.is.here@gmail.com

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Please read the Terms of Service at
# https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
# agree in order to register with the ACME server. Do you agree?
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# (Y)es/(N)o: Y

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Would you be willing, once your first certificate is successfully issued, to
# share your email address with the Electronic Frontier Foundation, a founding
# partner of the Let's Encrypt project and the non-profit organization that
# develops Certbot? We'd like to send you email about our work encrypting the web,
# EFF news, campaigns, and ways to support digital freedom.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# (Y)es/(N)o: N
# Account registered.

# Which names would you like to activate HTTPS for?
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 1: nginx-handbook.farhan.dev
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Select the appropriate numbers separated by commas and/or spaces, or leave input
# blank to select all options shown (Enter 'c' to cancel): 
# Requesting a certificate for nginx-handbook.farhan.dev
# Performing the following challenges:
# http-01 challenge for nginx-handbook.farhan.dev
# Waiting for verification...
# Cleaning up challenges
# Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/default
# Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/default

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Congratulations! You have successfully enabled
# https://nginx-handbook.farhan.dev
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# IMPORTANT NOTES:
#  - Congratulations! Your certificate and chain have been saved at:
#    /etc/letsencrypt/live/nginx-handbook.farhan.dev/fullchain.pem
#    Your key file has been saved at:
#    /etc/letsencrypt/live/nginx-handbook.farhan.dev/privkey.pem
#    Your certificate will expire on 2021-07-30. To obtain a new or
#    tweaked version of this certificate in the future, simply run
#    certbot again with the "certonly" option. To non-interactively
#    renew *all* of your certificates, run "certbot renew"
#  - If you like Certbot, please consider supporting our work by:

#    Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
#    Donating to EFF:                    https://eff.org/donate-le
</code></pre>
<p>You'll be asked for an emergency contact email address, license agreement and if you would like to receive emails from them or not.</p>
<p>The certbot program will automatically read the server names from your configuration file and show you a list of them. If you have multiple virtual hosts on your server, certbot will recognize them as well.</p>
<p>Finally if the installation is successful, you'll be congratulated by the program. To verify if everything's working or not, visit your server with HTTPS this time:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/mCbapBf9n.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you can see, HTTPS has been enabled successfully and you can confirm that the certificate is verified by <a target="_blank" href="https://letsencrypt.org/">Let's Encrypt</a> authority. Later on, if you add new virtual hosts to this server with new domains or sub domains, you'll have to reinstall the certificates.</p>
<p>It's also possible to install wildcard certificate such as <code>*.yourdomain.tld</code> for some supported DNS managers. Detailed instructions can be found on the previously shown installation instruction page.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/PLFcZoO8P.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>A newly installed certificate will be valid for 90 days. After that, a renewal will be required. Certbot does the renewal automatically. You can execute <code>certbot renew</code> command with the <code>--dry-run</code> option to test out the auto renewal feature.</p>
<pre><code class="lang-shell">certbot renew --dry-run

# Saving debug log to /var/log/letsencrypt/letsencrypt.log

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Processing /etc/letsencrypt/renewal/nginx-handbook.farhan.dev.conf
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Cert not due for renewal, but simulating renewal for dry run
# Plugins selected: Authenticator nginx, Installer nginx
# Account registered.
# Simulating renewal of an existing certificate for nginx-handbook.farhan.dev
# Performing the following challenges:
# http-01 challenge for nginx-handbook.farhan.dev
# Waiting for verification...
# Cleaning up challenges

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# new certificate deployed with reload of nginx server; fullchain is
# /etc/letsencrypt/live/nginx-handbook.farhan.dev/fullchain.pem
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Congratulations, all simulated renewals succeeded: 
#   /etc/letsencrypt/live/nginx-handbook.farhan.dev/fullchain.pem (success)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
</code></pre>
<p>The command will simulate a certificate renewal to test if it's correctly set up or not. If it succeeds you'll be congratulated by the program. This step ends the procedure of installing an SSL certificate on your server.</p>
<p>To understand what certbot did behind the scenes, open up the <code>/etc/nginx/sites-available/default</code> file once again and see how its content has been altered.</p>
<pre><code class="lang-conf">server {

    server_name nginx-handbook.farhan.dev;  

    root /srv/nginx-handbook-projects/static-demo;

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/nginx-handbook.farhan.dev/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/nginx-handbook.farhan.dev/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = nginx-handbook.farhan.dev) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80;
    listen [::]:80;

    server_name nginx-handbook.farhan.dev;
    return 404; # managed by Certbot
}
</code></pre>
<p>As you can see, certbot has added quite a few lines here. I'll explain the notable ones.</p>
<pre><code class="lang-conf">server {
    # ...
    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    # ...
}
</code></pre>
<p>Like the 80 port, 443 is widely used for listening to HTTPS requests. By writing <code>listen 443 ssl;</code> certbot is instructing NGINX to listen for any HTTPS request on port 443. The <code>listen [::]:443 ssl ipv6only=on;</code> line is for handling IPV6 connections.</p>
<pre><code class="lang-conf">

server {
    # ...
    ssl_certificate /etc/letsencrypt/live/nginx-handbook.farhan.dev/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/nginx-handbook.farhan.dev/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    # ...
}
</code></pre>
<p>The <code>ssl_certificate</code> directive is used for indicating the location of the certificate and the private key file on your server. The <code>/etc/letsencrypt/options-ssl-nginx.conf;</code> includes some common directives necessary for SSL.</p>
<p>Finally the <code>ssl_dhparam</code> indicates to the file defining how OpenSSL is going to perform <a target="_blank" href="https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange">Diffie–Hellman key exchange</a>. If you want to learn more about the purpose of <code>/etc/letsencrypt/ssl-dhparams.pem;</code> file, this stack exchange <a target="_blank" href="https://security.stackexchange.com/questions/94390/whats-the-purpose-of-dh-parameters">thread</a> may help you.</p>
<pre><code class="lang-conf">server {
    if ($host = nginx-handbook.farhan.dev) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80;
    listen [::]:80;

    server_name nginx-handbook.farhan.dev;
    return 404; # managed by Certbot
}
</code></pre>
<p>This newly added server block is responsible for redirecting any HTTP requests to HTTPS disabling HTTP access completely.</p>
<h3 id="heading-how-to-enable-http2">How To Enable HTTP/2</h3>
<p>Once you've successfully installed a valid SSL certificate on your server, you're ready to enable HTTP/2. SSL is a prerequisite for HTTP/2, so right off the bat you can see, security is not optional in HTTP/2.</p>
<p>HTTP/2 support for NGINX is provided by the <a target="_blank" href="https://nginx.org/en/docs/http/ngx_http_v2_module.html">ngx_http_v2_module</a> module. Pre-built binaries of NGINX on most of the systems come with this module baked in. If you've built NGINX from source however, you'll have to include this module manually.</p>
<p>Before upgrading to HTTP/2, send a request to your server and see the current protocol version.</p>
<pre><code class="lang-shell">curl -I -L https://nginx-handbook.farhan.dev

# HTTP/1.1 200 OK
# Server: nginx/1.18.0 (Ubuntu)
# Date: Sat, 01 May 2021 10:46:36 GMT
# Content-Type: text/html
# Content-Length: 960
# Last-Modified: Fri, 30 Apr 2021 20:14:48 GMT
# Connection: keep-alive
# ETag: "608c6538-3c0"
# Accept-Ranges: bytes
</code></pre>
<p>As you can see, by default the server is on HTTP/1.1 protocol. On the next step, we'll update the configuration file as necessary for enabling HTTP/2.</p>
<p>To enable HTTP/2 on your server, open the <code>/etc/nginx/sites-available/default</code> file once again. Find wherever it says <code>listen [::]:443 ssl ipv6only=on;</code> or <code>listen 443 ssl;</code> and update them to <code>listen [::]:443 ssl http2 ipv6only=on;</code> and <code>listen 443 ssl http2;</code> respectively.</p>
<pre><code class="lang-conf">server {

    server_name nginx-handbook.farhan.dev;  

    root /srv/nginx-handbook-projects/static-demo;

    listen [::]:443 ssl http2 ipv6only=on; # managed by Certbot
    listen 443 ssl http2; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/nginx-handbook.farhan.dev/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/nginx-handbook.farhan.dev/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = nginx-handbook.farhan.dev) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80;
    listen [::]:80;

    server_name nginx-handbook.farhan.dev;
    return 404; # managed by Certbot
}
</code></pre>
<p>Test the configuration file by executing <code>niginx -t</code> and reload the configuration by executing <code>nginx -s reload</code> commands. Now send a request to your server again.</p>
<pre><code class="lang-shell">curl -I -L https://nginx-handbook.farhan.dev

# HTTP/2 200 
# server: nginx/1.18.0 (Ubuntu)
# date: Sat, 01 May 2021 09:03:10 GMT
# content-type: text/html
# content-length: 960
# last-modified: Fri, 30 Apr 2021 20:14:48 GMT
# etag: "608c6538-3c0"
# accept-ranges: bytes
</code></pre>
<p>As you can see, HTTP/2 has been enabled for any client supporting the new protocol.</p>
<h3 id="heading-how-to-enable-server-push">How to Enable Server Push</h3>
<p>Server push is one of the many features that HTTP/2 brings to the table. Which means the server can push files to the client without the client having to request for them. In a HTTP/1.x server, a typical request for static content may look like as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/f49aVyg9h.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>But on a server push enabled HTTP/2 server, it may look like as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/wLod0KcsB.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>On a single request for the index.html file the server responds with the style.css file as well, minimizing the number of requests in the process.</p>
<p>In this section, I'll use an open-source HTTP client named <a target="_blank" href="https://nghttp2.org/">Nghttp2</a> for testing the server.</p>
<pre><code class="lang-shell">apt install nghttp2-client -y

# Reading package lists... Done
# Building dependency tree       
# Reading state information... Done
# The following additional packages will be installed:
#   libev4 libjansson4 libjemalloc2
# The following NEW packages will be installed:
#   libev4 libjansson4 libjemalloc2 nghttp2-client
# 0 upgraded, 4 newly installed, 0 to remove and 0 not upgraded.
# Need to get 447 kB of archives.
# After this operation, 1,520 kB of additional disk space will be used.
# Get:1 http://archive.ubuntu.com/ubuntu focal/main amd64 libjansson4 amd64 2.12-1build1 [28.9 kB]
# Get:2 http://archive.ubuntu.com/ubuntu focal/universe amd64 libjemalloc2 amd64 5.2.1-1ubuntu1 [235 kB]
# Get:3 http://archive.ubuntu.com/ubuntu focal/universe amd64 libev4 amd64 1:4.31-1 [31.2 kB]
# Get:4 http://archive.ubuntu.com/ubuntu focal/universe amd64 nghttp2-client amd64 1.40.0-1build1 [152 kB]
# Fetched 447 kB in 1s (359 kB/s)     
# Selecting previously unselected package libjansson4:amd64.
# (Reading database ... 107613 files and directories currently installed.)
# Preparing to unpack .../libjansson4_2.12-1build1_amd64.deb ...
# Unpacking libjansson4:amd64 (2.12-1build1) ...
# Selecting previously unselected package libjemalloc2:amd64.
# Preparing to unpack .../libjemalloc2_5.2.1-1ubuntu1_amd64.deb ...
# Unpacking libjemalloc2:amd64 (5.2.1-1ubuntu1) ...
# Selecting previously unselected package libev4:amd64.
# Preparing to unpack .../libev4_1%3a4.31-1_amd64.deb ...
# Unpacking libev4:amd64 (1:4.31-1) ...
# Selecting previously unselected package nghttp2-client.
# Preparing to unpack .../nghttp2-client_1.40.0-1build1_amd64.deb ...
# Unpacking nghttp2-client (1.40.0-1build1) ...
# Setting up libev4:amd64 (1:4.31-1) ...
# Setting up libjemalloc2:amd64 (5.2.1-1ubuntu1) ...
# Setting up libjansson4:amd64 (2.12-1build1) ...
# Setting up nghttp2-client (1.40.0-1build1) ...
# Processing triggers for man-db (2.9.1-1) ...
# Processing triggers for libc-bin (2.31-0ubuntu9.2) ...

nghttp --version

# nghttp nghttp2/1.40.0
</code></pre>
<p>Lets test by sending a request to the server without server push.</p>
<pre><code class="lang-shell">nghttp --null-out --stat https://nginx-handbook.farhan.dev/index.html

# id  responseEnd requestStart  process code size request path
#  13      +836us       +194us    642us  200  492 /index.html

nghttp --null-out --stat --get-assets https://nginx-handbook.farhan.dev/index.html

# id  responseEnd requestStart  process code size request path
#  13      +836us       +194us    642us  200  492 /index.html
#  15     +3.11ms      +2.65ms    457us  200  45K /mini.min.css
#  17     +3.23ms      +2.65ms    578us  200  18K /the-nginx-handbook.jpg
</code></pre>
<p>On the first request <code>--null-out</code> means discard downloaded data and <code>--stat</code> means print statistics on terminal. On the second request <code>--get-assets</code> means also download assets such as stylesheets, images and scripts linked to this files. As a result you can tell by the <code>requestStart</code> times, the css file and image was downloaded shortly after the html file was downloaded.</p>
<p>Now, lets enable server push for stylesheets and images. Open <code>/etc/nginx/sites-available/default</code> file and update its content as follows:</p>
<pre><code class="lang-conf">server {

    server_name nginx-handbook.farhan.dev;

    root /srv/nginx-handbook-projects/static-demo;

    listen [::]:443 ssl http2 ipv6only=on; # managed by Certbot
    listen 443 ssl http2; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/nginx-handbook.farhan.dev/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/nginx-handbook.farhan.dev/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    location = /index.html {
        http2_push /mini.min.css;
        http2_push /the-nginx-handbook.jpg;
    }

    location = /about.html {
        http2_push /mini.min.css;
        http2_push /the-nginx-handbook.jpg;
    }

}
server {
    if ($host = nginx-handbook.farhan.dev) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80;
    listen [::]:80;

    server_name nginx-handbook.farhan.dev;
    return 404; # managed by Certbot
}
</code></pre>
<p>Two location blocks have been added to exactly match <code>/index.html</code> and <code>/about.html</code> locations. The <code>http2_push</code> directive is used for sending back additional response. Now whenever NGINX receives a request for one of these two locations, it'll automatically send back the css and image file.</p>
<p>Test the configuration by executing <code>nginx -t</code> and reload the configuration by executing <code>nginx -s reload</code> commands.</p>
<pre><code class="lang-shell">nginx -t

# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful

nginx -s reload
</code></pre>
<p>Now send another request to the server using <code>nghttp</code> and do not include <code>--get-assets</code> option.</p>
<pre><code class="lang-shell">nghttp --null-out --stat https://nginx-handbook.farhan.dev/index.html

# id  responseEnd requestStart  process code size request path
#  13     +1.49ms       +254us   1.23ms  200  492 /index.html
#   2     +1.56ms *    +1.35ms    212us  200  45K /mini.min.css
#   4     +1.71ms *    +1.39ms    318us  200  18K /the-nginx-handbook.jpg
</code></pre>
<p>As you can see, although the assets were not requested, the server has sent them to the client. Looking at the time measurements, process time has gone down and the three responses ended almost simultaneously.</p>
<p>This was a very simple example of server push but depending on the necessities of your project, this configuration can become much complex. This <a target="_blank" href="https://www.nginx.com/blog/nginx-1-13-9-http2-server-push/">article</a> by <a target="_blank" href="https://www.nginx.com/people/owen-garrett/">Owen Garrett</a> on the official NGINX blog can help you with more complex server push configuration.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I would like to thank you from the bottom of my heart for the time you've spent on reading this article. I hope you've enjoyed your time and have learned all the essentials of NGINX.</p>
<p>Apart from this one, I've written full-length handbooks on other complicated topics available for free on <a target="_blank" href="https://www.freecodecamp.org/news/author/farhanhasin/">freeCodeCamp</a>.</p>
<p>These handbooks are part of my mission to simplify hard to understand technologies for everyone. Each of these handbooks takes a lot of time and effort to write.</p>
<p>If you've enjoyed my writing and want to keep me motivated, consider leaving starts on <a target="_blank" href="https://github.com/fhsinchy/">GitHub</a> and endorse me for relevant skills on <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>. I also accept sponsorship so you may consider <a target="_blank" href="https://www.buymeacoffee.com/farhanhasin">buying me a coffee</a> if you want to.</p>
<p>I'm always open to suggestions and discussions on <a target="_blank" href="https://twitter.com/frhnhsin">Twitter</a> or <a target="_blank" href="https://www.linkedin.com/in/farhanhasin/">LinkedIn</a>. Hit me with direct messages.</p>
<p>In the end, consider sharing the resources with others, because </p>
<blockquote>
<p>Sharing knowledge is the most fundamental act of friendship. Because it is a way you can give something without loosing something. — Richard Stallman</p>
</blockquote>
<p>Till the next one, stay safe and keep learning.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
