<?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 Muma Ticha on Medium]]></title>
        <description><![CDATA[Stories by Muma Ticha on Medium]]></description>
        <link>https://medium.com/@mumaticha?source=rss-bb56f05b764f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*A6fgEK99D4mfuFy3.</url>
            <title>Stories by Muma Ticha on Medium</title>
            <link>https://medium.com/@mumaticha?source=rss-bb56f05b764f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 11:40:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mumaticha/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[Introduction to Generics]]></title>
            <link>https://medium.com/@mumaticha/introduction-to-generics-842e10b42e77?source=rss-bb56f05b764f------2</link>
            <guid isPermaLink="false">https://medium.com/p/842e10b42e77</guid>
            <category><![CDATA[type-safety]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[generics]]></category>
            <dc:creator><![CDATA[Muma Ticha]]></dc:creator>
            <pubDate>Sun, 20 Sep 2020 17:44:49 GMT</pubDate>
            <atom:updated>2020-09-20T17:44:49.152Z</atom:updated>
            <content:encoded><![CDATA[<p>This article describes the advantages of generics in Java in relation to type safety and the rationale for introducing it in Java 5.</p><h4>Why Generics?</h4><p>Consider the following lines of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2971b5668ff81ce5e9001e477599768/href">https://medium.com/media/b2971b5668ff81ce5e9001e477599768/href</a></iframe><h4>What is wrong with the above code?</h4><p>The first thing we notice is that we are defining a list without specifying what the content should be. In the above definition, List is known as a raw type and if you have read Effective Java, item 23 strongly discourages this. Why is this discouraged?</p><p>Firstly, lines 14 and 15 adds integers into the list but while manipulating these items (like looping in 20 to 23), we may need to add explicit casts if we need to perform Integer-specific actions. The need for explicit casts makes code brittle and can lead to serious issues at runtime. Looking at lines 26–33, we see another danger. The method <strong><em>addItem</em></strong> takes a raw type List as its parameter and in line 27, we called the method with a list of integers. However, a double is added to the list. While assuming that the list contains integers, line 33 tries to cast the added double to an integer, which results in a ClassCastException at runtime. We are not warned by the compiler during this process, making it very dangerous. A good solution will be to use a generic method so that JVM warns us about any potential illegal casts at compile time.</p><h4><strong>Generics enforces type safety at compile time</strong></h4><p>With our knowledge of supertypes Java and that Objects are supertypes of all other types, we may be tempted to write the following generic code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21670a7fff8a18ee47735457eb648185/href">https://medium.com/media/21670a7fff8a18ee47735457eb648185/href</a></iframe><p>However, this fails because of a property in Java called <strong><em>invariance</em></strong> (Lists are invariant while arrays are not). Due to invariance, line 7 will result in a compilation error thus, further enforcing compile-time type safety. This is possible because of generics. This is put in place to avoid unnecessary cast exceptions that may arise at runtime.</p><h4>Generic Types</h4><p>According to the official oracle docs, a <em>generic type</em> is a generic class or interface that is parameterized over types. Imagine we have a class called Box. A Box object can contain any type. To generify this class, we can use Object as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f4e8405f5b70f9c34635eda2f37c114/href">https://medium.com/media/9f4e8405f5b70f9c34635eda2f37c114/href</a></iframe><p>However, as explained above, using Object as a common supertype is too generic and can lead to cast exceptions during runtime. Therefore, the class above can be changed like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44e47734f0f5ca29d261e75d5f0508d0/href">https://medium.com/media/44e47734f0f5ca29d261e75d5f0508d0/href</a></iframe><p>In the above example, our code will not compile when we try to add a Double into a box of Integers. In the above declaration, T is known as a type parameter while the entire class is known as a generic type.</p><h4>Bounded Generics</h4><p>In the example above, we may want to restrict the type argument, T, to a specific supertype, say, Number. A simple reason for this may be that we want our Box objects to only operate on numbers and nothing else.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75c2a55f2ca3d66a4d4af5ccb659b9fe/href">https://medium.com/media/75c2a55f2ca3d66a4d4af5ccb659b9fe/href</a></iframe><p>In the above example, T is an upper-bounded type parameter and the bound is Number.</p><p>Also note that when we do not specify an upper bound as above, Object is explicitly used as the bound.</p><p>Therefore,</p><p><strong>class Box&lt;T&gt; {} is the same as class Box&lt;T extends Object&gt; {}</strong></p><h4>Generic Methods</h4><p>Generic methods are infinitely overloaded, i.e. they can take arguments of any type (although we can also induce bounds to method parameter types). They also ensure type safety by allowing the compiler to flag out issues at compile time thus, avoiding type-specific exceptions that may spring up at runtime.</p><h4>Generic Methods: Examples</h4><p>The Java Collections class defines a method called replaceAll() that reads as follows:</p><pre>public static &lt;T&gt; boolean replaceAll(List&lt;T&gt; list, T oldVal, T newVal)</pre><p>We read this as “Given a List of type T, replace all oldval in the list to newVal”</p><p>Notice that oldVal and newVal must be the same type parameter T.</p><p>We can call the above method like:</p><pre>List&lt;Integer&gt; someList = getListOfIntegers()</pre><pre>booeal allReplaced = replaceAll(someList, 12, 10);</pre><pre>boolean allReplaced = replaceAll(someList, 12, 10.4) // will result to a compilation issue</pre><p>A fix for the <strong><em>addItems</em></strong> in the first example is seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75d97269f842bed1a340bdaa90a2755a/href">https://medium.com/media/75d97269f842bed1a340bdaa90a2755a/href</a></iframe><p>The method is generic and <strong><em>ensures that we don&#39;t add an item into a list of items that are not of the same type as that item</em></strong></p><p><strong>Generic and Type Erasure</strong></p><p>In the above paragraphs, we have seen how generics can enforce compile-time safety. We now understand that it is better for an illegal code to fail the compilation stage than bursting out and production and thus, producing more undesirable outcomes. However, how does generics ensure compile-time type safety? To implement generics, the Java compiler does the following:</p><ol><li>Replace all type parameters (T in the above sections) in the generic types with the bounds (in the case of upper bounded generics) or with Object (we have seen above that when no bound is specified, Object is used as the upper bound) if no bound is specified. The byte code produced at this step, therefore, contains only Interfaces, classes, and methods.</li><li>Insert casts where necessary and notify programmers of potential cast exceptions.</li></ol><h4>Type Replacement due to Type Erasure</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f048382a5aff719298cd70e119a2825/href">https://medium.com/media/1f048382a5aff719298cd70e119a2825/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b972d20efe1598dfa681b96687420dc/href">https://medium.com/media/0b972d20efe1598dfa681b96687420dc/href</a></iframe><p>In the first figure, T is replaced with Object since it is unbounded (remember any unbounded type is bounded by Object). However, in the second figure, T is replaced with Numer by the compiler because it is bounded by Number. The same replacement strategies also apply for generic methods.</p><p><strong>Class casting</strong></p><p>In addition to type replacement, the compiler also performs <strong>explicit</strong> casts during compilation to ensure type safety.</p><p>Box&lt;Integer&gt; intBox = new Box&lt;&gt;();</p><p>intBox.setObject(12.4) // 12.4 is autoboxed to Double and casted to Integer and since this is an illegal cast, the compiler throws a ClassCastException.</p><p>Here, Integer is the inferred type (Note that JVM uses complex algorithms for type inference that will not be discussed int this article)</p><h4>Conclusion</h4><p>Generics is a really cool feature in Java that ensures type safety at compile time. When used well, it prevents unnecessary illegal casts that may result at runtime. Apart from the fact that generic are invariant: we are not allowed to substitute a subtype with a supertype and vice-versa, the compiler also has a property called <strong><em>type erausre </em></strong>which further ensures type safety of generic types. Again, we can specify bounds to generic methods and generic types to further protect our code from illegal assignments as seen in the above sections. Apart from the advantage of making our code extremely flexible, generics also enforees type safety and we should take advantage of this where necessary.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=842e10b42e77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Garbage Collection: Memory Leaks and how they can slow down the application.]]></title>
            <link>https://medium.com/@mumaticha/java-garbage-collection-memory-leaks-and-how-they-can-slow-down-the-application-11ea286c61b0?source=rss-bb56f05b764f------2</link>
            <guid isPermaLink="false">https://medium.com/p/11ea286c61b0</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jvm]]></category>
            <dc:creator><![CDATA[Muma Ticha]]></dc:creator>
            <pubDate>Sat, 01 Aug 2020 02:29:22 GMT</pubDate>
            <atom:updated>2020-08-01T02:29:22.320Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the main advantages of Java is its Garbage Collector. As application developers, we do not need to manually reclaim memory as there are sophisticated GC algorithms that periodically reclaim memory for our applications. Although GC is very efficient, memory leaks can still occur in an application. Sometimes, the effects may not be evident and our application may continue running effectively but sometimes, things can go down the drain.</p><h4>Types of Memory issues</h4><p>Two types of memory issues may arise:</p><ol><li>Memory Leaks: unused references are never freed.</li><li>Dangling Reference: when we try to reference an object that no longer exists, i.e. a deallocated reference.</li></ol><p>Luckily, the Java GC takes care of the above. However, Java designers are faced with a couple of issues when designing GC algorithms:</p><ol><li>Identifying dead objects, .i.e. objects that are not referenced anymore — reference either reassigned to null or another object</li></ol><p>e.g. SomeObject reference = new SomeObject()</p><p>reference = null or reference = some other object of the same type</p><p>2. Keep application pause time minimum: when GC runs and claims dead objects for collection, the application has to pause because if it doesn&#39;t, new objects may be created while old ones are sent for collection and thus causing further issues. Therefore, designers have to keep this pause time to the minimum in order not to affect the overall performance of the application.</p><h4>How Garbage Collection is performed</h4><p>Although different algorithms exist for GC (such as Mark and Sweep, Mark, Sweep and Compact, Mark and Copy, and Generational Collection) the Garbage collector generally needs to:</p><ol><li><strong>Mark</strong> life objects in the heap (remember objects are stored in the heap) by traversing the object graph to mark all reachable objects as life.</li><li><strong>Sweep</strong> through the entire graph and keep track of dead objects before finally destroying them.</li></ol><p>Any algorithm used has to ensure that dead objects are really dead and life objects are really alive in order to avoid dangling references as stated above. in addition, we cannot determine when the garbage collector runs but we know that it runs whenever there are <strong><em>increased memory footprints</em></strong> in our application: when there are many objects to be collected, it simply runs and collects them.</p><p>Even with the sophistication of GC, we can still cause memory leaks in our application;</p><p><strong>Developer induced Memory Leaks</strong></p><p>Effective Java Item 7: Eliminate Obsolete References cites this scenario. Consider the following program</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2YKpjyo456sQCPoIJey2hw.png" /></figure><p>Whenever we call stack.push(Object e), we add a new item into the stack.</p><p>However, when popping from the stack, we are simply decrementing the index. Consider that the following items have been pushed into the stack by doing subsequent stack.push() operations with the corresponding items.</p><p>[Object1, Object2, Object2, Object4]</p><p>Then we decide to pop elements from the stack by calling stack.pop()</p><p>Whenever we pop, we are simply decrementing the counter but the object is still in the heap. GC cannot collect any of these objects because they have not been dereferenced (objects need to be referenced by assigning a new reference. GC also collects when the reference is out of scope).</p><p>Such references are known as <strong><em>obsolete references </em></strong>and can cause memory leaks.</p><p><strong>Effects of Memory Leaks</strong></p><p>Increased memory leaks will increase memory footprints thus, increasing GC activity. Remember that whenever GC runs, the application has to pause. Increases in application pause time can cause overall performance issues and OutOfMemory errors in severe cases. Of course, we can naively increase the heap size during these errors but we still need to root out the issue.</p><h4>Avoiding Obsolete References</h4><p>As noted above, GC will mark an object as dead when it is dereferenced (assigned to a new object to assigned to null). Therefore to avoid these obsolete references, we need to do just this. Let&#39;s modify our pop method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*FdqZfAcGp0CpSL2TTwJYLw.png" /></figure><p>With this, GC will automatically collect all unused objects since they are explicitly dereferenced thus saving us from unforeseen issues.</p><p>Although GC is very efficient and effective in Java, we need to be careful when writing programs in order to avoid so many issues that can arise as a result of memory leaks in our application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11ea286c61b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Array indexing: Why are arrays indexed from zero?]]></title>
            <link>https://medium.com/@mumaticha/array-indexing-why-are-arrays-indexed-from-zero-8a367c04e3e4?source=rss-bb56f05b764f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a367c04e3e4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Muma Ticha]]></dc:creator>
            <pubDate>Sat, 07 Dec 2019 20:18:55 GMT</pubDate>
            <atom:updated>2019-12-07T20:18:55.892Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Array indexing: Why are arrays indexed from zero?</strong></p><p>As a programming novice, I never stopped wondering why array indices start from zero. From intuition, and from the natural flow of numbers, It would make more sense for indices to start from 1! At least that would have saved some stress on my side when coding, I said to myself. Weird right? In this article, I will explain why array indices start at zero instead of one.</p><p>Consider the code below in Java</p><p>int[] myArray = new int[10]</p><p>This is meant to create an array of 10 elements. We know that an integer requires 4 bytes of memory, so an array of 10 integers requires 40bytes of memory. But where should the array be stored in memory? Let&#39;s assume that after storage, the memory is partitioned as below:</p><p><strong>NB: Remember that arrays store data in contiguous memory locations.</strong></p><p><strong>NB2</strong>: <strong>An array can only contain elements of the same type because we need to know how much memory to allocate and this is usually possible if we know how much space each element occupies.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSu6GK6280_aNbM4QJ59nA.png" /></figure><p>bytes x to 1000 are already occupied. So new int[10] allocates 40 bytes of memory. Let&#39;s assume that the partition starts off at the next available byte, i.e. byte 1001 (this is the offset). When we do myArray[0] the compiler knows that this array is offset at 1001, therefore the element at this partition is returned. Generally, the address of the ith element is gotten by:</p><p>address(i) -&gt; offset + i-1 * 4 (since we need 4bytes to store an integer)</p><p>address(1) = 1001 + 0 * 4 = 1001 (0 positions from 1001)</p><p>address(2) = 1001 + 1 * 4 = 1001 + 4 = 1005 (1 position away from 1001)</p><p>address(10) = 1001 + 9 * 4 = 1001 + 36 = 1037.</p><p>According to Albert (<a href="https://medium.com/@albertkoz/why-does-array-start-with-index-0-65ffc07cbce8">https://medium.com/@albertkoz/why-does-array-start-with-index-0-65ffc07cbce8</a>), it makes more sense to think of elements in terms of positions from the offset partition.</p><p>Consequently, the first element is zero positions from the offset, the second element is 1 position from the offset and the nth element is n-1 positions from the offset. The formula above explains this.</p><p>In my opinion, arrays are indexed from zero because of the reasons explained above.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a367c04e3e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>