<?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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kamran Babayev on Medium]]></title>
        <description><![CDATA[Stories by Kamran Babayev on Medium]]></description>
        <link>https://medium.com/@kamran.babayevv?source=rss-e49770b852f2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*v1KXLEv-JzHiq37spTo-yg.jpeg</url>
            <title>Stories by Kamran Babayev on Medium</title>
            <link>https://medium.com/@kamran.babayevv?source=rss-e49770b852f2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:17:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kamran.babayevv/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding Kafka Consumer Groups: A Deep Dive]]></title>
            <link>https://medium.com/@kamran.babayevv/understanding-kafka-consumer-groups-a-deep-dive-53e74e99abc7?source=rss-e49770b852f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/53e74e99abc7</guid>
            <category><![CDATA[kafka-streams]]></category>
            <category><![CDATA[kafka-consumer]]></category>
            <category><![CDATA[kafka-consumer-group]]></category>
            <category><![CDATA[message-broker]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Kamran Babayev]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 14:02:25 GMT</pubDate>
            <atom:updated>2025-03-27T14:02:25.220Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V6hS8XVCqsUq-csW.png" /></figure><p>What Are Kafka Consumer Groups?</p><p>A <strong>Consumer Group</strong> in Kafka is a collection of consumers that collaboratively consume messages from a topic. Each consumer within the group reads messages from different partitions, allowing for parallel processing and improved throughput.</p><blockquote><strong><em>Key Benefit:</em></strong><em> Messages from a topic are distributed among consumers in the group, ensuring efficient load balancing and failover handling.</em></blockquote><h3>How Consumer Groups Work?</h3><ul><li>Each consumer in the group is assigned a unique set of partitions from the topic.</li><li>Messages within a partition are processed by only one consumer at a time, preventing duplication.</li><li>If a consumer leaves or joins the group, Kafka <strong>rebalances</strong> partitions to ensure equal distribution.</li></ul><h3>How Kafka Manages Message Distribution?</h3><p>Kafka follows a <strong>partition-based assignment strategy</strong> to distribute messages within a consumer group. The number of partitions in a topic and the number of consumers in a group determine how messages are allocated.</p><h3>Partition Distribution Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2VuDi13J0TrMvFCD1kF7w.png" /><figcaption><strong>Important:</strong> If there are more consumers than partitions, some consumers will remain idle.</figcaption></figure><h3>What Happens During Consumer Rebalancing?</h3><p>When a consumer joins or leaves a group, Kafka <strong>triggers a rebalance</strong>, reassigning partitions among active consumers.</p><h3>Rebalancing Scenarios</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_SXRhx-F9VfUS8eLJZmcw.png" /><figcaption><strong>Rebalancing ensures high availability</strong> by redistributing the workload among the remaining consumers.</figcaption></figure><h3>Partition Assignment in Kafka</h3><p>Kafka provides multiple <strong>partition assignment strategies</strong> to distribute partitions among consumers:</p><ol><li><strong>Range Assignor</strong> — Consumers receive a contiguous range of partitions.</li><li><strong>Round-Robin Assignor</strong> — Partitions are evenly assigned to consumers.</li><li><strong>Sticky Assignor</strong> — Tries to maintain existing partition assignments during rebalance.</li></ol><p>Each strategy has its own advantages depending on the workload and use case.</p><h3>How Many Partitions Can a Consumer Process?</h3><p>The number of partitions a consumer can handle depends on:</p><ul><li>The <strong>total number of partitions</strong> in the topic.</li><li>The <strong>number of consumers</strong> in the consumer group.</li></ul><p>Kafka attempts to distribute partitions evenly among consumers for <strong>optimal performance</strong>.</p><h3>Optimizing Partitioning</h3><ul><li>Increase <strong>partitions</strong> if consumers are overwhelmed.</li><li>Increase <strong>consumers</strong> if partitions are underutilized.</li></ul><h3>What Happens When a Consumer Shuts Down?</h3><p>When a consumer stops, Kafka triggers <strong>rebalance</strong>, and its partitions are reassigned to remaining consumers.</p><blockquote><strong><em>Key Takeaway:</em></strong><em> This ensures fault tolerance and continuous processing of messages.</em></blockquote><h3>Final Thoughts</h3><p>Kafka Consumer Groups play a crucial role in ensuring scalability, parallelism, and reliability in real-time data processing. Understanding their behavior helps in designing efficient Kafka-based architectures.</p><h3>Key Takeaways:</h3><p>✔ Consumer Groups enable parallel processing by distributing partitions.</p><p>✔ Kafka rebalances partitions when consumers join or leave.</p><p>✔ The number of consumers should match the number of partitions for optimal throughput.</p><p>✔ Different partition assignment strategies impact performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53e74e99abc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensuring Order Consistency in Kafka with Round Robin Partitioning]]></title>
            <link>https://medium.com/@kamran.babayevv/ensuring-order-consistency-in-kafka-with-round-robin-partitioning-7d5160e47e50?source=rss-e49770b852f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d5160e47e50</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[partition]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[consumer]]></category>
            <category><![CDATA[round-robin-algorithm]]></category>
            <dc:creator><![CDATA[Kamran Babayev]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 19:52:15 GMT</pubDate>
            <atom:updated>2025-03-22T19:52:15.693Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/605/0*LpUnXSvlQsc3ufDT.png" /></figure><p>Apache Kafka is a widely used distributed event streaming platform that enables applications to process high-throughput, real-time data streams. However, ensuring the correct order of messages when consuming from Kafka partitions can be challenging, especially when different keys are assigned to different partitions.</p><p>One common scenario involves updating the payment state in a database, where the last recorded state must be <strong>SUCCESS</strong>, but due to partitioning inconsistencies, we might see an intermediate state such as <strong>PENDING_VALIDATION</strong>. In this article, we will discuss how Kafka partitions messages and how a round-robin strategy impacts order consistency.</p><p>Kafka distributes messages across multiple partitions based on a key. The partitioning mechanism follows these rules:</p><ol><li><strong>Same key -&gt; Same partition</strong>: Messages with the same key always go to the same partition, ensuring in-order delivery.</li><li><strong>Different key -&gt; Different partition</strong>: Kafka distributes messages with different keys across available partitions in a round-robin manner (if no key is provided, Kafka’s default producer behavior applies).</li></ol><p>This means that messages within a single partition are ordered, but messages across partitions are not.</p><h3>Problem Scenario: Payment State Inconsistencies</h3><p>Imagine we have a <strong>payment processing system</strong> that tracks payment status in a database. Events are published to Kafka with different payment IDs as keys:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u0c_InSo1g74cirJegUVVA.png" /></figure><p>If Kafka follows the partitioning rules correctly, <strong>PAY_123</strong> events will always be in the same partition (Partition 0). However, if <strong>round-robin partitioning</strong> is applied incorrectly (i.e., without specifying keys), events may land in different partitions, leading to inconsistencies:</p><ul><li>A consumer reading from <strong>Partition 1</strong> might see the <strong>SUCCESS</strong> state first.</li><li>Another consumer reading from <strong>Partition 0</strong> might still be processing <strong>PENDING_VALIDATION</strong>, leading to incorrect state perception.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yqOWHWdocXYUDCd276iCXg.png" /></figure><p>When a consumer reads messages from different partitions asynchronously, it might update the database with incorrect states:<br>Here, the <strong>PENDING_VALIDATION</strong> state overwrites the correct <strong>SUCCESS</strong> state due to out-of-order consumption, causing data inconsistency.</p><h3>Ensuring Order Consistency</h3><p>To maintain correct order and prevent stale data issues:</p><ol><li><strong>Always use a Key for Partitioning</strong>: Ensure that payment-related events have a consistent key (e.g., paymentId). This ensures all events for the same entity land in the same partition.</li><li><strong>Use Consumer Groups Correctly</strong>: Consumers in the same group process messages from assigned partitions. Ensure proper partition assignment and avoid parallel consumers reading from the same key in different partitions.</li><li><strong>Handle Out-of-Order Messages</strong>: Implement <strong>idempotency</strong> and <strong>state validation</strong> at the database level. If an outdated state arrives after the latest state, it should be discarded.</li><li><strong>Enable Kafka Transactions</strong>: Using Kafka transactions can help guarantee atomic writes and reads, preventing inconsistent updates.</li><li><strong>Monitor and Debug with Logs</strong>: Use distributed tracing and log monitoring to detect ordering issues early.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d5160e47e50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding CountDownLatch in Java with an Example]]></title>
            <link>https://medium.com/@kamran.babayevv/understanding-countdownlatch-in-java-with-an-example-6a671c2d310a?source=rss-e49770b852f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a671c2d310a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[countdownlatch]]></category>
            <dc:creator><![CDATA[Kamran Babayev]]></dc:creator>
            <pubDate>Sat, 21 Sep 2024 22:34:07 GMT</pubDate>
            <atom:updated>2024-09-21T22:34:07.876Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/609/0*QPodRiLTmGx0EHPb.png" /></figure><p>The CountDownLatch is a useful synchronization aid in Java, especially when you want to ensure that a set of threads completes their tasks before moving forward with the rest of the program. It works by allowing one or more threads to wait until a set of operations being performed in other threads completes.</p><p>Here’s an example of using CountDownLatch to improve the performance of a factorial calculation in a multi-threaded environment.</p><h3>How CountDownLatch Works</h3><p>A CountDownLatch is initialized with a count (the number of threads). Each time a thread completes its task, it calls countDown() to decrement the latch. When the latch count reaches zero, it allows the waiting threads to continue execution.</p><p><strong>Code Example: </strong>Using CountDownLatch in Java</p><pre>package az.ingress.livecoding.blog;<br><br>import java.util.ArrayList;<br>import java.util.List;<br>import java.util.concurrent.CountDownLatch;<br>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br>import java.util.concurrent.Future;<br><br>public class CountDownLatchExample {<br><br>    public static void main(String[] args) throws Exception {<br>        // A list of integers for which we&#39;ll calculate the factorial<br>        List&lt;Integer&gt; integers = List.of(15, 12, 10, 8, 9, 5, 11);<br><br>        testWithSingleThread(integers);  // Single-threaded execution<br>        // Single-threaded result: 1308197318520<br>        // Time taken in single-thread mode: 7590 ms<br><br>        testWithCountDownLatch(integers);  // Multi-threaded execution using CountDownLatch<br>        // Multi-threaded result: 1308197318520<br>        // Time taken in multi-thread mode: 1641 ms<br>    }<br><br>    public static void testWithSingleThread(List&lt;Integer&gt; integers) throws Exception {<br>        // Measure time in single-threaded mode<br>        long singleThreadStartTime = System.currentTimeMillis();<br>        long singleThreadResult = 0;<br><br>        // Calculate factorials sequentially<br>        for (int number : integers) {<br>            singleThreadResult += calculateFactorialWithMainThread(number);<br>        }<br><br>        long singleThreadEndTime = System.currentTimeMillis();<br>        System.out.println(&quot;Single-threaded result: &quot; + singleThreadResult);<br>        System.out.println(&quot;Time taken in single-thread mode: &quot; + (singleThreadEndTime - singleThreadStartTime) + &quot; ms&quot;);<br>    }<br><br>    public static void testWithCountDownLatch(List&lt;Integer&gt; integers) throws Exception {<br>        // Measure time in multi-threaded mode using CountDownLatch<br>        long multiThreadStartTime = System.currentTimeMillis();<br>        CountDownLatch latch = new CountDownLatch(integers.size());<br><br>        List&lt;Future&lt;Long&gt;&gt; futures = new ArrayList&lt;&gt;();<br><br>        // Create a thread pool<br>        ExecutorService executor = Executors.newFixedThreadPool(integers.size());<br><br>        long multiThreadResult = 0;<br><br>        // Submit factorial tasks to the executor<br>        for (int number : integers) {<br>            Future&lt;Long&gt; submit = executor.submit(() -&gt; calculateFactorialWithCountDownLatch(number, latch));<br>            futures.add(submit);<br>        }<br><br>        // Wait for all threads to finish their work<br>        latch.await();<br><br>        // Collect results from each thread<br>        for (Future&lt;Long&gt; future : futures) {<br>            if (future.isDone()) {<br>                multiThreadResult += future.get();<br>            } else {<br>                System.out.println(&quot;Future result is not done&quot;);<br>            }<br>        }<br><br>        long multiThreadEndTime = System.currentTimeMillis();<br>        System.out.println(&quot;Multi-threaded result: &quot; + multiThreadResult);<br>        System.out.println(&quot;Time taken in multi-thread mode: &quot; + (multiThreadEndTime - multiThreadStartTime) + &quot; ms&quot;);<br><br>        // Shutdown the executor service<br>        executor.shutdown();<br>    }<br><br>    // Factorial calculation for single-threaded mode<br>    private static long calculateFactorialWithMainThread(int number) throws InterruptedException {<br>        long result = 1L;<br><br>        // Perform factorial calculation<br>        for (int i = 1; i &lt;= number; i++) {<br>            result *= i;<br>            // Introduce artificial delay of 100 ms<br>            Thread.sleep(100);<br>        }<br>        return result;<br>    }<br><br>    // Factorial calculation for multi-threaded mode using CountDownLatch<br>    private static Long calculateFactorialWithCountDownLatch(int number, CountDownLatch latch) throws InterruptedException {<br>        long result = 1L;<br><br>        // Perform factorial calculation<br>        for (int i = 1; i &lt;= number; i++) {<br>            result *= i;<br>            // Introduce artificial delay of 100 ms<br>            Thread.sleep(100);<br>        }<br><br>        // Count down the latch when this thread completes its work<br>        latch.countDown();<br>        return result;<br>    }<br>}</pre><h3>How This Example Works</h3><ul><li><strong>Single-threaded Mode</strong>: The program first calculates the factorials of a list of integers one by one in a single thread. This is a sequential approach.</li><li><strong>Multi-threaded Mode Using </strong><strong>CountDownLatch</strong>: The program then calculates the same factorials in parallel using multiple threads. It uses CountDownLatch to ensure that the main thread waits for all the threads to complete their calculations.</li><li><strong>Thread Pool</strong>: We use ExecutorService to manage a pool of threads, submitting tasks that calculate the factorial of each number in the list.</li><li><strong>Factorial Calculation</strong>: Each task includes an artificial delay (Thread.sleep(100)) to simulate some long-running operations.</li><li><strong>CountDownLatch</strong>: Each thread decrements the latch when it finishes its factorial computation (latch.countDown()), and the main thread waits (latch.await()) until all tasks are done.</li></ul><h3>Output</h3><pre>Single-threaded result: 1308197318520<br>Time taken in single-thread mode: 7590 ms<br><br>Multi-threaded result: 1308197318520<br>Time taken in multi-thread mode: 1641 ms</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a671c2d310a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Assimetrik kriptoqrafiya və RSA alqoritminin praktiki izahı]]></title>
            <link>https://medium.com/@kamran.babayevv/assimetrik-kriptoqrafiya-v%C9%99-rsa-alqoritminin-praktiki-izah%C4%B1-4da56362bc13?source=rss-e49770b852f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4da56362bc13</guid>
            <category><![CDATA[https]]></category>
            <category><![CDATA[rsa-algorithm]]></category>
            <category><![CDATA[decryption]]></category>
            <category><![CDATA[assymetric]]></category>
            <category><![CDATA[encryption]]></category>
            <dc:creator><![CDATA[Kamran Babayev]]></dc:creator>
            <pubDate>Tue, 21 May 2024 22:47:20 GMT</pubDate>
            <atom:updated>2024-05-22T06:34:31.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*MIjUo-lshjtkopWuKADcrA.jpeg" /></figure><p>İlk öncə demək istəyərdim ki, <strong>Encryption </strong>2 cür olur <strong><em>assimetrik </em></strong>və <strong><em>simmetrik</em></strong>. Və bunlarında hər birinin müxtəlif alqoritmləri olur. Aşağıdakı şəkildə hər birinin alqoritmləri göstərilmişdir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*eGcpwTn6PO8i0WcTutMGsg.png" /></figure><p>Və qeyd edək ki, <strong>https </strong>assimmetrik və <strong>http </strong>simmetrik <strong>Encryption </strong>istifadə edir<strong>. </strong>Assimetrik-də ən çox istifadə olunan alqoritmlər RSA və <a href="https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange">Diffie-Hellman</a> (qısa məlumat üçün linkdən baxa bilərsiz) alqoritmləridir. Nəzərə alsaq ki, bu gün dünyada ən geniş istifadə olunan <strong>https</strong>-dir biz də <strong>RSA </strong>alqoritmi izah etməyə çalışaq.</p><p><em>Alqoritmə keçməzdən əvvəl http və https nə işə yarayır deyə baxaq:</em></p><p><strong>HTTPS </strong>protokolu <strong>HTTP</strong>-nin uzantısıdır. Sadəcə olaraq, <strong>HTTPS </strong>şifrələmə ilə <strong>HTTP</strong>-dir. Bu <em>“Hypertext Transfer Protocol Secure”</em> mənasını verir və əsas fərq onun Transport Layer Security (TLS) və Secure Sockets Layer (SSL) sertifikatlarından istifadə edilməsidir. O, xüsusi olaraq <strong>HTTP </strong>üzlərinin Man-in-the-Middle hücum zəifliklərinə qarşı çıxmaq üçün yaradılmışdır. <strong>HTTPS </strong>ondan istifadə edənlər üçün bir sıra üstünlüklərə malikdir. O, hərtərəfli şifrələyərək sistem və server arasında məlumatların ötürülməsinə məlumat təhlükəsizliyi səviyyəsini əlavə edir. Bundan əlavə, SSL/TLS prosesi identifikasiya səviyyəsini əlavə etmək üçün SSL sertifikatlarından istifadə edir və müasir veb brauzerlərlə əlaqə saxlayan veb serveri müəyyən etməyə imkan verir.</p><p><strong>HTTPS </strong>olmadan, sayta daxil etdiyiniz hər hansı məlumat (məsələn, istifadəçi adınız/parolunuz, kredit kartınız və ya bank rekvizitləriniz, hər hansı digər forma təqdim etmə məlumatları və s.) şifrələnməmiş açıq mətn kimi göndərilir və buna görə də ələ keçirilməyə və ya dinləmələrə həssasdır. Bu səbəbdən, hər hansı bir məlumat daxil etməzdən əvvəl, xüsusən də bu e-ticarət saytıdırsa və ya hər hansı bir maliyyə məlumatı daxil edirsinizsə, həmişə saytın <strong>HTTPS</strong>-dən istifadə etdiyini yoxlamalısınız.</p><p><strong>RSA </strong>və ya üç yaradıcısının adını daşıyan <strong>R</strong>ivest-<strong>S</strong>hamir-<strong>A</strong>dleman<em> ən məşhur</em> asimmetrik kriptoqrafik alqoritmdir. O, 1977-ci ildə işlənib hazırlanmışdır və o vaxtdan bəri təhlükəsiz rabitə və rəqəmsal imzalar sahəsində təməl daşına çevrilmişdir.</p><p>RSA izah etmək üçün ilk öncə riyaziyyatdan bəzi terminləri yadımıza salaq: <strong><em>1.Ədədin vuruqlarının hasili şəkilində göstərilməsi(factor):</em></strong> Məsələn 12 ədədini 1 × 12, 2 × 6, 3 × 4 şəkilində göstərmək olar.</p><p><strong><em>2.Sadə ədədlər(prime numbers):</em></strong> (yalnız özünə və 1-ə bölünənlər) — məsələn 2 , 3, 5, 7, 11 və.s</p><p><strong><em>3.Yarı-sadə ədədlər(semi-prime numbers):</em></strong> (iki sadə ədədin hasili kimi yazıla bilən müsbət tam ədədlərdir) — məsələn 21 ədədini 3 × 7 şəkilində göstərmək olar.</p><p><strong>4.Qalıq(modulo):</strong> Qısaca arithmetic operatoru yadmıza salaq, 13 % 5 = 3. Hesablamalarda % yerinə MOD yazılır. <strong>13 MOD 5 = 3</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*wSRI6ofaqhOeQ1QodLgM_w.png" /><figcaption>Nümunə</figcaption></figure><p>Verilənlər: İlk öncə 2 sadə ədəd(prime) seçək: P və Q (public parameters)</p><ul><li>P = 7</li><li>Q = 19</li><li>N = P × Q = 7 × 19 = 133 product hesablayırıq.</li><li>T = (P−1) × (Q−1) = (7−1) × (19−1) = 6 × 18 = 108 Euler’s <strong>totient </strong>function hesablayırıq.</li></ul><p>Və <strong>public key(E) </strong>seçməliyik və şəkildəki şərtdən də aydın olur ki, public key sadə ədəd olmalıdır və 1 &lt; E &lt; T şərtini ödəməlidir. Həmçinin, T-nin vuruqlarından (factor) biri olmamalıdır. Yəni <strong>E </strong>ədədinə uyğun mümkün variantlar aşağıdakılardır: 5,7,11,13,17,19,23,25,29,31,35,37,41,43,47,49,53,55,59,61,65,67,71,73,77,79,83,85,89,91,95,97,101,103,107</p><p>Və tapılan mümkün variantlar arasından istədiyimiz bir public key seçək: Mən <strong>E = 29</strong> seçirəm(siz istədiyinizi seçə bilərsiniz).</p><p>İndi isə <strong>private key</strong> seçməliyik. Şəkildəki düstur ilə tapaq, deməli <strong>D </strong>× <strong>E MOD T = 1</strong> olmalıdır.</p><p>Bu şərti təmin edən <strong>D</strong>-ni tapmaq üçün genişlənmiş Evklid alqoritmindən istifadə edək. Genişlənmiş Evklid alqoritmi <em>A </em>və <em>B </em>ədədləri üçün <em>A</em>𝑥+<em>B</em>𝑦=gcd(<em>A,B</em>) tənliyinin həllini tapır. Bizim vəziyyətimizdə <em>A</em>=E=29 və <em>B</em>=T=108-dir. Bizə <strong>D × 29 MOD 108 = 1</strong> şərtini ödəyən D (private key) lazımdır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*pYjs6C0Rw1ubL337hK_Xkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*AGIO7mkCS_AvCh7ZLVZzOQ.png" /></figure><p>Burada gördüyünüz kimi, 1=41×29−11×108 bərabərliyini tapdıq. Bu isə o deməkdir ki, <strong>D=41 (private key)</strong>.</p><p>Gəldik əsas məsələyə <strong><em>encrypt with public key = 29 </em></strong><em>and </em><strong><em>decrypt with private key = 41</em></strong>. Deməli Alice xanım Bob-a <strong>60 </strong>mesajını göndərmək istəyir bunun üçün Alice mesajı yəni 60-ı public key ilə <strong><em>encrypt</em></strong> edir. (60 ^ 29) MOD 133 = 86 bizim <strong><em>encryptdən alınan Chiper Text = 86 oldu. </em></strong>İndi isə Bob private key ilə onu(chiper text-i) <strong><em>decrypt edir. (</em></strong>86 ^ 41) MOD 133 = 60 və mesaj uğurla decrypt olundu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*oP9ut9mqqdEstIeMwJXH7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*wULg41xl-Sc4RSLlBk-nRg.png" /><figcaption>Visaul olaraq nəticə</figcaption></figure><p>Və sonda qeyd edək ki, bizim N = P × Q = 7 × 19 = 133 yalnız 8 bitlik bir ədəddir(izah üçün kiçik ədədlər seçildi). RSA 2015-ci ildən bəri bunun 2048 bitlik ədəd istifadəsini məsləhət görür. Aşağıda 2048 bitlik ədəd nümunəsi göstərilmişdir.</p><pre>26785007119960605692854465691874329818722586627445852583862820166951463<br>21168962729332383032943123887484914720821913991857803442785975826276341<br>25398495330103264242655243419909855984110057820998510116056736308352499<br>40501978417867677583243940833504569431451676833700732658713239273614203<br>34971642378356792605737404896959509163848376171423185082583503121952172<br>82779634798610396421573863749260138585609829251432885822238659758905199<br>42023170470987760508133800325568047992294501200302180519873080004541959<br>74229467643038128554845043012392499516920656504088501911100259298058020<br>46617248635284269607476824050969673901030687294771951855616104446897787<br>927297147292153125390950420821574169431056963419217174666143413544897</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*psoqWgpEL1zY41J79cv5gg.png" /></figure><p>Nəticəni Java kodda da görə bilərik <strong>Main class</strong>-ı run edərək outputa baxa bilərsiniz :)</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        int P = 7;<br>        int Q = 19;<br>        int E = 29;<br>        RSAEncryptor rsa = new RSAEncryptor(P, Q, E);<br><br>        int message = 60; // 60 is &#39;&lt;&#39; in ASCII table<br>        int encryptedMessage = rsa.encrypt(message);<br><br>        System.out.println(&quot;Chipper Text: &quot; + encryptedMessage);<br><br>        int decryptedMessage = rsa.decrypt(encryptedMessage);<br>        System.out.println(&quot;Decrypt message: &quot; + decryptedMessage);<br>    }<br>}</pre><pre>import java.math.BigInteger;<br><br>public class RSAEncryptor {<br>    private int P;<br>    private int Q;<br>    private int N;<br>    private int E;<br>    private int D;<br><br>    public RSAEncryptor(int P, int Q, int E) {<br>        this.P = P;<br>        this.Q = Q;<br>        this.N = P * Q;<br>        this.E = E;<br>        this.D = this.calculatePrivateKey();<br>    }<br><br>    private int calculatePrivateKey() {<br>        int T = (P - 1) * (Q - 1);<br>        BigInteger eBigInteger = BigInteger.valueOf(E);<br>        BigInteger phiBigInteger = BigInteger.valueOf(T);<br>        BigInteger dBigInteger = eBigInteger.modInverse(phiBigInteger);<br>        return dBigInteger.intValue();<br>    }<br><br>    public int encrypt(int message) {<br>        BigInteger m = BigInteger.valueOf(message);<br>        BigInteger encrypted = m.modPow(BigInteger.valueOf(E), BigInteger.valueOf(N));<br>        return encrypted.intValue();<br>    }<br><br>    public int decrypt(int ciphertext) {<br>        BigInteger encrypted = BigInteger.valueOf(ciphertext);<br>        BigInteger decrypted = encrypted.modPow(BigInteger.valueOf(D), BigInteger.valueOf(N));<br>        return decrypted.intValue();<br>    }<br><br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4da56362bc13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Luhn alqoritmi]]></title>
            <link>https://medium.com/@kamran.babayevv/luhn-alqoritmi-6729c8b4835c?source=rss-e49770b852f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6729c8b4835c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[luhn-algorithm]]></category>
            <dc:creator><![CDATA[Kamran Babayev]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 17:34:01 GMT</pubDate>
            <atom:updated>2024-03-01T17:34:01.791Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4n0YW53AEtvD3LXEQQMug.png" /></figure><p>Modul 10 və ya mod 10 alqoritmi kimi tanınan Luhn alqoritmi kredit kartı nömrələri, IMEI nömrələri kimi müxtəlif identifikasiya nömrələrini yoxlamaq üçün istifadə edilən sadə yoxlama düsturudur. <strong><em>LUHN </em></strong>düsturu 1960-cı illərin sonunda bir qrup riyaziyyatçı tərəfindən yaradılmışdır. Qısa müddətdən sonra kredit kartı şirkətləri bunu qəbul etdilər.</p><p>Alqoritm bu formada irəliləyir ki, kartın ilk rəqəmi <strong>(x2)</strong> vurulur sonrakı rəqəm vurulmur və beləcə bir rəqəmdən bir kard rəqəmləri <strong>(x2)</strong> vurulur. Əgər <strong>(x2)</strong> vurulan rəqəm ikirəqəmli alınarsa <strong>(&gt;9)</strong> o zaman həmin ədədin rəqəmləri cəmi toplanaraq şəkildəki üçüncü sətirə yazılır. Yəni, bizim nümunədə kredit kardının rəqəmləri <strong>“5678 1234 5670 1234” </strong>belədir və bir rəqəmdən bir 2-yə vurulandan sonra ikinci sətirdəki nəticə alınır. Bildiyimiz kimi <strong>5 x 2=10</strong> olur və <strong>10 </strong>iki rəqəmli ədəddir, onun rəqəmləri cəmi <strong>1 + 0 = 1 </strong>olur. Sonrakı kard rəqəmi 6 skip olunur 7 yenidən<strong> 7 x 2 =14 </strong>olur və <strong>1 + 4 = 5 </strong>və beləcə sona qədər davam edir. Şəkildəki üçüncü sətirin hər bir xanasındakı rəqəmi toplayırıq alınan ədəd <strong>10 tam bölünürsə</strong> nömrə <strong>valid </strong>sayılır.</p><pre>public class LuhnAlgorithm {<br><br>    public static void main(String[] args) {<br>        String creditCardNumber = &quot;5678 1234 5670 1234&quot;; <br>        boolean isValid = isValid(creditCardNumber);<br><br>        if (isValid) {<br>            System.out.println(&quot;The credit card number is valid.&quot;);<br>        } else {<br>            System.out.println(&quot;The credit card number is not valid.&quot;);<br>        }<br>    }<br><br>    public static boolean isValid(String number) {<br>        // Boşluqları və rəqəmsiz simvolları silir<br>        number = number.replaceAll(&quot;[^0-9]&quot;, &quot;&quot;);<br>        int sum = 0;<br>        boolean alternate = true;<br><br>        for (int i = 0; i &lt; number.length(); i++) {<br>            int digit = Character.getNumericValue(number.charAt(i));<br><br>            if (alternate) {<br>                digit *= 2;<br>                if (digit &gt; 9) {<br>                    digit = digit / 10 + digit % 10;<br>                }<br>            }<br><br>            sum += digit;<br>            alternate = !alternate;<br>        }<br>        System.out.println(&quot;Sum is : &quot; + sum);<br>        return (sum % 10 == 0);<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6729c8b4835c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Http metodun Idempotent və Safe olması nə dərəcədə əhəmiyyətlidir?]]></title>
            <link>https://medium.com/@kamran.babayevv/idempotent-metod-o-metod-adlan%C4%B1r-ki-%C9%99m%C9%99liyyat-t%C9%99krar-edilirs%C9%99-response-success-200-ok-d%C3%B6nm%C9%99lidir-0be691e0155f?source=rss-e49770b852f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0be691e0155f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[safe]]></category>
            <category><![CDATA[http-methods]]></category>
            <category><![CDATA[maintainability]]></category>
            <category><![CDATA[idempotent]]></category>
            <dc:creator><![CDATA[Kamran Babayev]]></dc:creator>
            <pubDate>Wed, 14 Feb 2024 18:17:40 GMT</pubDate>
            <atom:updated>2024-02-14T18:38:39.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AcyTvwyKLfbnLMPoAn_iFA.png" /></figure><p><strong>Idempotent </strong>metod o metod adlanır ki, əməliyyat təkrar edilərsə response success (200 OK) dönməlidir. Məsələn, hər hansı bir app üzərindən pay edirsiniz, həmin button 2-dən artıq click olunsa sizin balansdan cəmi bir dəfə pul çıxılmalıdır.</p><p><strong>Safe </strong>metod o metod adlanır ki, request-in sayından asılı olmayaraq database-da heç bir dəyişiklik olmamalıdır. Məsələn, user-i primary key-ə (id) görə taparkən həmişə eyni nəticə qayıtması kimi.</p><p>İndi isə keçək <strong><em>@PUT</em></strong> və <strong><em>@POST</em></strong> metodları üzərində bunları daha aydın izah etməyə çalışaq. Yuxarıdakı şəkildə göründüyü kimi PUT metodu safe deyil, amma idempotent-dir. POST metodu isə nə idempotent-dir, nə də safe.</p><p>Deməli, düşünək ki biz özümüzə pizza sifariş etmək istəyirik, bu zaman daxil olduğumuz app-də sifariş verən zaman çalışan <strong><em>API </em>@POST</strong> metodu ilə aşağıdakı kimi yazılmışdır.</p><pre>@PostMapping<br> public ResponseEntity&lt;OrderResponse&gt; createOrder(@RequestBody OrderRequest orderRequest) {<br>        return ResponseEntity.status(HttpStatus.CREATED)<br>                  .body(orderService.createOrder(orderRequest));<br> }</pre><p>Və həmin an sistem network problemi yaşayır və biz bir neçə dəfə <strong>“indi sifariş et”</strong> button-a click etmişik, network problemi aradan qalxdıqdan sonra mənzərə aşağıdakı şəkildəki kimi olacaq.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*C2azIMOt-gXImhyNEc9jPA.jpeg" /></figure><p>Amma həm create, həm də update bir yerdə yazsaq həmin sifariş yoxdursa yenisi yarancaq, varsa hər request-də update oluncaq və bizim <strong>“indi sifariş et”</strong> button-a bir neçə dəfə click etməymizə baxmayaraq bu yalnız bir sifariş kimi qəbul ediləcək.</p><pre>  @PutMapping(&quot;/{orderId}&quot;)<br>   public ResponseEntity&lt;OrderResponse&gt; createOrUpdateOrder(@PathVariable UUID orderId, @RequestBody OrderRequest orderRequest) {<br>     return ResponseEntity.ok(orderService.createOrUpdateOrder(orderId, orderRequest));<br>   }</pre><p>Və network problemi aradan qalxdıqdan sonra mənzərə yalnız bir pizza olacaq.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*fj4OKhwCIOL7Y32Y6JqyTg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0be691e0155f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HashMap daxildə necə işləyir?]]></title>
            <link>https://medium.com/@kamran.babayevv/hashmap-daxild%C9%99-nec%C9%99-i%C5%9Fl%C9%99yir-ea6fea10eb56?source=rss-e49770b852f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea6fea10eb56</guid>
            <category><![CDATA[collections-in-java]]></category>
            <category><![CDATA[hashmap]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kamran Babayev]]></dc:creator>
            <pubDate>Sat, 07 Oct 2023 07:44:12 GMT</pubDate>
            <atom:updated>2023-12-01T14:13:45.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xFa1hYCH4XtaOx9Uc_UgQ.jpeg" /></figure><p>HashMap- də bucket anlayışı var (Şəkildə solda gördüyünüz index-lər bucketlərdir). Yəni bizim put elədiyimiz element xüsusi bir alqoritm vasitəsilə gedib həmin bucket-ə oturur. Bucket-i sanki array-dəki index kimi başa düşmək olar. 0-index həmişə <strong>key = null</strong> olanlar oturur. İkinci dəfə <strong>key=null</strong> versək gedib value-nu sonucuya uyğun override edəcək.</p><p><strong>HashMap</strong> initial capacity <strong>16</strong> load factor <strong>0.75</strong> dir. Yəni HashMap-ə 12 element put olunduqdan sonra 75% dolanda avtomatik olaraq 16-lıq array’a yeni 16-lıq array əlavə edir. Nəticə olaraq 32 bucket olur. 32-lik bucket-in 75% də dolanda 64-lük bucket yaranır.</p><p>Yuxarıda qeyd etdiyimiz alqoritm bu düsturla hesablanır:</p><p><strong>index = hashcode(key) &amp; (n — 1)</strong></p><p>n — initial capacity 16 olur amma capacity artdıqca n də dəyişir. Buna resize və ya rehash deyilir. İlk halda (capacity = 16 olduqda) index = 4 alınırsa bir element üçün capacity = 32 olduqda bu index dəyişə bilər.</p><p><em>Bizim bir HashMap-miz var:</em></p><p><strong>HashMap &lt;String, String&gt; map = new HashMap&lt;&gt;();</strong></p><p>Fərz edək ki, biz (“123kdkd8” , “K”) put edirik və index = 4 olur, yenidən (“456jhdo6”,”N”) put edirik yenidən gedib index = 4 olsa sonuncu put etdiyimiz next element olacaq. Amma biz key-ə eyni dəyər versək value həmin bucket-də override olunacaq. Əgər bucket-dəki elementlərin sayı 8-ə çatsa ordakı elementin search mexanizmi red black tree olur və bu da bizə ən pis halda O(log n) (worst case) time complexity verir istədiyimiz elementi axtararkən. Tutaq ki, bizim bir bucket-mizdə 1.000.000 data var. Əvvəl bildiyimiz kimi search mexanizimi LinkedList-ə görə getsəydi bu ən pis halda (worst case) 1.000.000 operation deməkdir. Amma red black tree algoritiminə görə bu log₂(1.000.000)=20 təxminən 20 əməliyyat edir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*sJAq8JSJXHOl2tOD4YyItg.png" /><figcaption>Red black tree (Java 8-də gələn böyük dəyişikliklərdən biri)</figcaption></figure><p>Əgər biz axtarışda hashCode-u hesabladıq və məsələn index 2 çıxdı və getdik gördük ki, 2-ci bucket-də 1 yox, 50 data var. Bəs onda necə biləcəyik ki, biz axtaran element ordadır ya yox. Bu hal Hash Collision adlanır və bu halda artıq bucket-i tapdıqdan sonra equals ilə bir-bir ordakı data-ları, biz axtardığımız ilə müqayisə edirik və nəticə olaraq elementi tapırıq. Ona görədə equals hashCode doğru çalışması üçün key-də custom class saxlıyırıqsa onların hər ikisi override olunmalıdır ki, düzgün nəticə ala bilək.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea6fea10eb56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Singleton Class and Enum]]></title>
            <link>https://medium.com/@kamran.babayevv/java-singleton-class-and-enum-806475482cb6?source=rss-e49770b852f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/806475482cb6</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[singleton-pattern]]></category>
            <category><![CDATA[enumeration]]></category>
            <dc:creator><![CDATA[Kamran Babayev]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 16:37:22 GMT</pubDate>
            <atom:updated>2023-08-18T21:41:43.355Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*EdKe6Z3y4Q9PtPWo8gcc2w.jpeg" /></figure><p>Singleton design pattern növlərindən biridir. Singleton design pattern-dən danışacayıq çünki, Enumlar da bu məntiqlə çalışırlar. Gəlin Singleton design pattern nədir ona baxaq və sintaksisi ilə tanış olaq.</p><p>Java-da Singleton bir sinifin yalnız bir obyektə malik olmasını təmin edən dizayn nümunəsidir. Singleton sinif yaratmaq üçün aşağıda göstərilən 3 şərtə baxaq:</p><ul><li>private konstruktor yaratmaq.</li><li>private dəyişən yaratmaq sinifin tipində.</li><li>public static getInstance() adlı bir metod yaratmaq ki, bu yalnız bir dəfə həmin sinifin obyektin yaratsın.</li></ul><pre>class Database {<br>    private static Database dbObject;<br><br>    private Database() {<br>    }<br><br>    public static Database getInstance() {<br><br>        if (dbObject == null) {<br>            dbObject = new Database();<br>        }<br>        return dbObject;<br>    }<br><br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Database db1 = Database.getInstance();<br>        Database db2 = Database.getInstance();<br>        System.out.println(db1.hashCode());//1521118594 <br>        System.out.println(db2.hashCode());//1521118594<br>    }<br>}</pre><p>Burda yalnız və yalnız bir obyekt yaranacaq bunu hashcode()-u ekrana çap edərəkdə görə bilərik ki, bunlar eyni obyektə referans edirlər.</p><p>Enumeration qısa olaraq <strong>enum </strong>özündə<strong> </strong>sabit dəyərləri saxlayan bir data tipidir. Enum-u declare etmək üçün <strong>enum</strong> keyword-dən istifadə olunur. Dəyərlərdən sonra heç bir ifadə gəlmirsə semicolon <strong>;</strong> optional olur, yəni istəyə bağlı qoyada bilərsiz qoymayada amma dəyərlər arasında <strong>,</strong> mütləq qoyulmalıdır. Gəlin sintaksisinə baxaq:</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        for (Size s : Size.values())<br>            System.out.println(s);<br>    }<br>}<br><br>enum Size {<br>    SMALL, MEDIUM, LARGE, EXTRALARGE<br>}</pre><p><em>Nəticə:</em></p><pre>SMALL<br>MEDIUM<br>LARGE<br>EXTRALARGE</pre><p>Adətən enum-un içindəki sabit dəyərlər upperCase, yəni böyük hərflərlə olur.</p><p>String kimi Enum-lar da switch statement də işlənə bilir:</p><pre>enum Size {<br> SMALL, MEDIUM, LARGE, EXTRALARGE<br>}<br><br>class Test {<br> Size pizzaSize;<br> public Test(Size pizzaSize) {<br>   this.pizzaSize = pizzaSize;<br> }<br> public void orderPizza() {<br>   switch(pizzaSize) {<br>     case SMALL:<br>       System.out.println(&quot;I ordered a small size pizza.&quot;);<br>       break;<br>     case MEDIUM:<br>       System.out.println(&quot;I ordered a medium size pizza.&quot;);<br>       break;<br>     default:<br>       System.out.println(&quot;I don&#39;t know which one to order.&quot;);<br>       break;<br>   }<br> }<br>}<br><br>public class Main {<br> public static void main(String[] args) {<br>   Test t1 = new Test(Size.MEDIUM);<br>   t1.orderPizza();<br> }<br>}</pre><p><em>Nəticə:</em></p><pre>I ordered a medium size pizza.</pre><p>Enum class-ları da normal konkret class-lar kimi özündə fields,methods,constructor və.s saxlaya bilər. Biz enum class yaradərkən, compiler hər enum sabitinin obyektin yaradacaq və bütün dəyişənlər default olaraq public static final olacaqdır.</p><p><strong>Enum class-nin method-ları:</strong></p><pre><br>public class Main {<br>    public static void main(String[] args) {<br>        int index = Size.EXTRALARGE.ordinal();//massiv məntiqi ilə index 0-dan başlıyır<br>        System.out.println(index);//3<br>        String name = Size.SMALL.name();<br>        System.out.println(name);//SMALL<br>        Size size = Size.valueOf(&quot;LARGE&quot;);<br>        System.out.println(size);//LARGE<br>        Size[] enumArray = Size.values();<br>        System.out.println(Arrays.toString(enumArray));//[SMALL, MEDIUM, LARGE, EXTRALARGE]<br>        String value = Size.MEDIUM.toString();<br>        System.out.println(value);//MEDIUM<br>    }<br>}<br><br>enum Size {<br>    SMALL, MEDIUM, LARGE, EXTRALARGE<br>}</pre><p>method-ların nəticələri comment-lərdə göstərilmişdir. String return edən iki methodumuz var name() və toString(). Biz toString() method-unu override edərək öz məntiqimizi də yaza bilərik amma name() methodu final olduğundan bu alınmır.</p><pre>enum Size {<br>   SMALL {<br><br>      // overriding toString() for SMALL<br>      public String toString() {<br>        return &quot;The size is small.&quot;;<br>      }<br>   },<br><br>   MEDIUM {<br><br>     // overriding toString() for MEDIUM<br>      public String toString() {<br>        return &quot;The size is medium.&quot;;<br>      }<br>   };<br>}<br><br>class Main {<br>   public static void main(String[] args) {<br>      System.out.println(Size.MEDIUM.toString());//The size is medium.<br>   }<br>}</pre><p><strong>Enum-ların üstünlükləri:</strong></p><pre>public class Size {<br>   public final static int SMALL = 1;<br>   public final static int MEDIUM = 2;<br>   public final static int LARGE = 3;<br>   public final static int EXTRALARGE = 4;<br>}</pre><pre>public enum Size {<br>   SMALL, MEDIUM, LARGE, EXTRALARGE<br>}</pre><p>Size class-ındakı dəyişənləri çapa versək görərik ki, yalnız rəqəm çap olunur ki, bu da lazımsız və mənasız olur. Həmçinin, enum <strong>compile-time type safety təmin</strong> edir.</p><p>Normal konkret class-lar kimi burda da konstruktor yaratmaq mümkündür , amma bu konstruktor ya private ya da package-private, yəni default olmalıdır. Gəlin bir nümunəyə baxaq:</p><pre>enum Size {<br><br>   // enum constants calling the enum constructors <br>   SMALL(&quot;The size is small.&quot;),<br>   MEDIUM(&quot;The size is medium.&quot;),<br>   LARGE(&quot;The size is large.&quot;),<br>   EXTRALARGE(&quot;The size is extra large.&quot;);<br><br>   private final String pizzaSize;<br><br>   // private enum constructor<br>   private Size(String pizzaSize) {<br>      this.pizzaSize = pizzaSize;<br>   }<br><br>   public String getSize() {<br>      return pizzaSize;<br>   }<br>}<br><br>class Main {<br>   public static void main(String[] args) {<br>      Size size = Size.SMALL;<br>      System.out.println(size.getSize());//The size is small.<br>   }<br>}<br><br></pre><p><strong>Enum-lara aid yadda saxlanmalı məqamlar:</strong></p><ul><li>Enum improves type safety</li><li>Enum can be easily used in switch</li><li>Enum can be traversed</li><li>Enum can have fields, constructors and methods</li><li>Enum may implement many interfaces but cannot extend any class because it internally extends Enum class</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=806475482cb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exceptions in Java]]></title>
            <link>https://medium.com/@kamran.babayevv/exceptions-in-java-4ba50a6832a3?source=rss-e49770b852f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ba50a6832a3</guid>
            <category><![CDATA[java-programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[exception]]></category>
            <category><![CDATA[exceptions-in-java]]></category>
            <category><![CDATA[exception-handling]]></category>
            <dc:creator><![CDATA[Kamran Babayev]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 17:05:16 GMT</pubDate>
            <atom:updated>2023-08-03T11:42:50.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bd7LSpgjLOjNOcw_3CoZPQ.jpeg" /></figure><p><strong>Exception </strong>— proqramın axışını dəyişən hadisədir (event). Exception bir növü bir mexanizmdir, hansı ki onun köməkliyi ilə siz proqramda hər hansı bir gözlənilməz hal, xəta yarananda, baş vermiş xətanın məzmununa uyğun proqramın istiqamətinə istədiyiniz şəkildə yön verə bilərsiniz. Bütün exceptions <strong>Throwable </strong>classından törəyir.</p><p><strong>Error </strong>— elə hallar olur ki, bu developer-dən asılı olmur. Misal internet kəsildisə proqram çalışmasa bu errordur,amma bu error global məsələdir artıq.Ümumiyyətlə, Javada errorları handle etmək məsləhət görülmür. Daha bir error misalı <strong>recursion </strong>olanda <strong>StackOverFlow </strong>errordur və yaxud heap yaddaşın dolması bu<strong> OutOfMemory </strong>erroru<strong> </strong>adlanır. Bunlar hər ikisi <strong>VirtualMachineError </strong>class-nın subclasslarıdır. Göründüyü kimi, <strong>VirtualMachineError </strong>bu developerdən asılı deyil, yəni artıq bizim proqram çökür bunu handle etmək isə mənasız olur.</p><p><strong>Runtime exception </strong>— <strong>RuntimeException </strong>və ondan törəyən subclasslar vasitəsilə yaradılan exceptionlar hesab edilirlər. Runtime exceptionlar da gözlənilməyən istisnalar hesab edilir, amma errorlar kimi qorxulu deyil. Java bu exceptionları tutmağı(catch) mütləq <strong>handle</strong> etməlisən demir, onsuz onun nə olduğunu anlayıram deyir. Amma proqram runtime exception fırlatsa həmin line-da proqram qırılacaq və növbəti sətirlər icra olunmayacaq. Buna görədə biz runtime exceptionları try{ } catch{ } bloklarının içində yazaraq proqramın axıra qədər bütün sətirlərinin icra olunmasını təmin etmişik oluruq. Bu exceptionlar həm də <strong>unchecked </strong>exceptions adlanır.</p><p><strong>Checked exception</strong> — Exception və ondan törəyən bütün subclasslar (RuntimeException classı istisna olmaqla) bu exceptiona daxildir. Checked exceptionlar əvvəlcədən görülə bilən exceptionlar hesab edilir. Bunlara həmçini <strong>IOException class-nın </strong>subclasslarıdır deyə bilərik. Bəs nə üçün bu exceptionlar “checked” adlanır? Çünki java bu exceptionların “handle” və ya “declare” olunmasını tələb edir. “<strong>handle</strong>” — <strong>try-catch</strong> mexanizmi vasitəsilə xətanın yaxalanması, tutulması anlamına gəlir. <strong>declare</strong> isə <strong>throws </strong>açar sözündən istifadə etməklə olur, yəni bunu atırıq Javanın öz üzərinə. Gəlin misallar baxaq və daha aydın başa düşək:</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        System.out.println(50/0);//Burda exception baş versədə Java bunu optional edib.<br>        //Amma <br>        System.out.println(Class.forName(&quot;Student&quot;));//Bu yazılış artıq checked exception olur yəni Java burda nə baş verdiyini tam anlamır.<br>        //Bizə iki yol sunur ya try catch ya methodun başına throws yazmaq<br>    }<br>}</pre><pre>public class Main {<br>    public static void main(String[] args) {<br>        System.out.println(50/0);   <br>    //birinci variant   <br>        try {<br>            System.out.println(Class.forName(&quot;Student&quot;));<br>        } catch (ClassNotFoundException e) {<br>            throw new RuntimeException(e);<br>        }<br><br>    }<br>}</pre><pre>public class Main {<br>    public static void main(String[] args) throws ClassNotFoundException {<br>        System.out.println(50/0);   <br>    //ikinci variant   <br>        System.out.println(Class.forName(&quot;Student&quot;));<br>       <br>        }<br>    }</pre><p><strong>throw </strong>açar sözünü biz yeni exception fırlatmaq üçün istifadə edirik. throws açar sözü ilə isə elan edirik ki, bu metod exceptionu öz üzərindən onu çağıran metodun üzərinə atır.</p><p>Yuxarıdakı nümunə ilə bağlı qısa olaraq qeyd etmək olar ki, checked exception`lar əvvəlcədən göründüyünə görə Java proqramçını məcbur edir ki, onunla bağlı bir tədbir görsün, ya handle etsin, ya da declare. Amma unchecked exception`lar belə desək qeyri-müəyyəndir, əvvəlcədən təyin etmək çətindir. Məsələn, NullPointerException null referans üzərindən hər hansı bir üzvü (member) çağırmağa cəhd edən zaman yaranır və bu da istənilən metodda baş verə bilər. Biz əgər buna görə hər yerdə bu exceptionu declare etməli olsaq, kodda qarmaqarışıqlıq yaranacaq. Bu səbəbdən Java unchecked (runtime) exception`ları handle və ya declare etməyi tələb etmir.</p><p>Gəlin test nümunəsinə baxaraq daha dərin başa düşək:</p><pre>package game;<br>public class BasketBall {<br> public static void main(String[] dribble) {<br> try {<br> System.out.print(1);<br> throw new ClassCastException();<br> } catch (ArrayIndexOutOfBoundsException ex) {<br> System.out.print(2);<br> } catch (Throwable ex) {<br> System.out.print(3);<br> } finally {<br> System.out.print(4);<br> }<br> System.out.print(5);<br> }<br>}</pre><p><em>Output</em></p><pre>1345<br>//Exception ArrayIndexOutOfBoundsException aid olmadığından Throwable classı yazılan <br>//block işə düşəcək daha sonra finally block daha sonra System.out.print(5);</pre><pre>package game;<br>public class Football {<br> public static void main(String officials[]) {<br> try {<br> System.out.print(&#39;A&#39;);<br> throw new RuntimeException(&quot;Out of bounds!&quot;);<br> } catch (ArrayIndexOutOfBoundsException t) {<br> System.out.print(&#39;B&#39;);<br> throw t;<br> } finally {<br> System.out.print(&#39;C&#39;);<br> }<br> }<br>}</pre><p><em>Output</em></p><pre>AC runtime exception fırladacaq mesaj hissəsində Out of bounds! yazılacaq</pre><p>finally block həmişə icra olunan blockdur bunun qarşısını almaq üçün yalnız try və ya catch blockun içinə System.exit(0) yazmaq olar. Test nümunəsinə baxsaq görərik ki, try içində System.out.print(‘A’); kodu yazılıb bu problemsiz çalışacaq və A print olunacaq,amma sonrakı sətirdə exception atılıb deyə catch blocku işə düşəcək, amma bu block yalnız ArrayIndexOutOfBoundsException tutmaq üçün nəzərdə tutlduğundan və RuntimeException classının subclassı olduğundan bunu handle edə bilmir. Və nəticə finally blok işə düşür C print olunur və daha sonra Out of bounds! mesajı ilə RuntimeException fırlanır.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ba50a6832a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference between abstract class and interface]]></title>
            <link>https://medium.com/@kamran.babayevv/difference-between-abstract-class-and-interface-49f7357b0a63?source=rss-e49770b852f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/49f7357b0a63</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[java-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[oop-principles]]></category>
            <dc:creator><![CDATA[Kamran Babayev]]></dc:creator>
            <pubDate>Sun, 09 Jul 2023 15:48:15 GMT</pubDate>
            <atom:updated>2023-07-09T15:48:15.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*zIwc-ffv8zcWcqdbsvlP_Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*zFpxYif10HtBDJQkB0q1wA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49f7357b0a63" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>