<?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 Barış Ayten on Medium]]></title>
        <description><![CDATA[Stories by Barış Ayten on Medium]]></description>
        <link>https://medium.com/@baytendev?source=rss-75b342b9ae32------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rZyjV6obj4r522kDHQ_n4A.png</url>
            <title>Stories by Barış Ayten on Medium</title>
            <link>https://medium.com/@baytendev?source=rss-75b342b9ae32------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 10:04:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@baytendev/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[Abstract Classes and Interfaces in Java: Abstraction and Flexibility]]></title>
            <link>https://levelup.gitconnected.com/abstract-classes-and-interfaces-in-java-abstraction-and-flexibility-669c858b18af?source=rss-75b342b9ae32------2</link>
            <guid isPermaLink="false">https://medium.com/p/669c858b18af</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Barış Ayten]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 04:14:07 GMT</pubDate>
            <atom:updated>2023-06-13T11:26:39.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*s2OBJh2vLWySOidlJQzzpw.png" /></figure><p>Hello everyone, 🖖🏼</p><p>In this article, I want to address Abstract and Interface, which are topics that have often confused me and made it difficult to understand which one to use and why. I will provide a detailed explanation of what these classes are, why they are used, and the differences between them. I hope you find this article informative and enjoyable.</p><p>Happy reading! 🎇</p><p>In Java, Abstract and Interface classes are two distinct structures that enable a strong representation of the abstraction concept in software design. Both are abstract classes and cannot be instantiated directly, meaning they cannot be created as objects. However, these structures exhibit differences and offer unique advantages based on the scenarios in which they are used.</p><p>Abstract classes are <strong>used to define and share common properties among concrete classes through their abstraction capabilities</strong>. They serve as an ideal tool to group classes with common characteristics in a class hierarchy and pass on these characteristics through inheritance.</p><p>Abstract classes <strong>can combine abstract and concrete methods to specify the methods that must be implemented by subclasses</strong>. This increases <strong>code’s reusability and ensures interoperability</strong>.</p><p>On the other hand, Interface classes are used <strong>as a kind of contract to define common behaviors or functionality among various classes</strong>. They determine which methods a class must implement, serving as a guideline. Interfaces in Java enable multiple inheritance by allowing a class to implement multiple interfaces, thus leveraging the flexibility advantage offered by multiple inheritance. They contribute to making the code more flexible, extensible, and easy to maintain.</p><p>Now that we have taken a brief look at both concepts, we can delve into them in more detail. 🐱‍🏍</p><h3>Abstract Classes</h3><p>Abstraction is used to represent complex systems in a simpler and more understandable way in the real world. For example, let’s think of a car and the common features that all the cars have: fuel consumption, speed, braking system, number of doors of color… We can take these common features as a foundation and create a model. With this foundation, we can then differentiate and customize the features to create cars with different characteristics. Basically, what we are doing here is abstraction, and we use this abstract class to create new classes.</p><p>Abstract classes are abstract structures <strong>that define the properties (instance variables, etc.) and behaviors of an abstract class</strong>. These classes <strong>can be inherited and used by other concrete classes</strong>. One of the key features that differentiates abstract classes from interfaces is that <strong>they can contain both abstract and concrete methods</strong>. The abstract methods they contain are defined by the classes that inherit the abstract class, providing flexibility in the written code.</p><p>Let’s create an example to abstract class.</p><pre>abstract class Shape {<br>   protected String color;<br>   <br>   public Shape(String color) {<br>      this.color = color;<br>   }<br>   <br>   public abstract double area();<br>   <br>   public void display() {<br>      System.out.println(&quot;Bu bir &quot; + color + &quot; şekildir.&quot;);<br>   }<br>}</pre><p>This is an example of an abstract class called “Shape”. It includes the common property of <strong>Shape</strong>, which is the <strong>“color”</strong> variable, and the <strong>“display”</strong> method. Also, the <strong>“area”</strong> method is defined as abstract, which means that each subclass inheriting from this class can override the <strong>“area”</strong> method according to its own implementation.</p><p>Now, let’s create two different classes that inherits from the abstract class <strong>“Shape”</strong> and take a look at their usage.</p><pre>class Circle extends Shape {<br>   private double radius;<br>   <br>   public Circle(String color, double radius) {<br>      super(color);<br>      this.radius = radius;<br>   }<br>   <br>   public double area() {<br>      return Math.PI * radius * radius;<br>   }<br>}<br><br>// -----------<br><br>class Rectangle extends Shape { <br>   private double length;<br>   private double width;<br>   <br>   public Rectangle(String color, double length, double width) {<br>      super(color);<br>      this.length = length;<br>      this.width = width;<br>   }<br>   <br>   public double area() {<br>      return length * width;<br>   }<br>}</pre><p>When the classes <strong>Rectangle</strong> and <strong>Circle</strong> inherit from the abstract class <strong>Shape</strong>, they acquire the properties defined in this class. However, they can also include their own properties on top of these inherited ones, if they want to. For example, <strong>the Circle</strong> class may have a “<strong>radius</strong>” property, and the <strong>Rectangle</strong> class may have a “<strong>width</strong>” property.</p><h3>IS-A Relationship</h3><p>Here is another thing I’d like to point out: the <strong>is-a</strong> relationship. Abstract classes and the classes inheriting from them form an is-a relationship. If we were to briefly illustrate this relationship using our scenario as an example,</p><blockquote><em>The Rectangle </em><strong><em>is-a</em></strong><em> shape. The Circle </em><strong><em>is-a</em></strong><em> shape.</em></blockquote><p>So, rectangle or circle are a Shape and they possess all the properties of Shape.</p><h3>Real Life Examples</h3><p>So far so good. But how and when can these abstract classes be used in real-life projects? Let me provide some brief examples.</p><ul><li>Imagine that we are developing an e-commerce application. In this application, we can create an abstract class that <strong>represents the general characteristics of products</strong>. For instance, we can create an abstract class named ‘<strong>Product</strong>’ to define the common traits of products. Subclasses can represent different product categories and define their own customized methods using the properties of the abstract class.</li><li>Alternatively, let’s imagine that we are designing a <strong>banking application</strong>. For this, we can utilize an abstract class that <strong>represents different types of bank accounts</strong>. For example, creating an abstract class named ‘<strong>BankAccount</strong>’, we can define common attributes such as account number and balance. Subclasses can define methods and operations specific to different account types (e.g., current account, savings account, credit card account).</li></ul><h3>Summary</h3><p>Now that we have discussed the real-life examples, let’s try to summarize the whole topic in bullet points.</p><ul><li>Abstract classes can contain both methods and variables.</li><li>They cannot be instantiated directly, meaning they cannot be called with the ’new()’ keyword.</li><li>They can be inherited.</li><li>They can contain both abstract and concrete methods.</li><li>They have constructors.</li><li>They form an “is-a” relationship with the classes that inherit from them.</li></ul><p>Now let’s move on to our next concept, <strong>Interface classes</strong>.</p><h3>Interface Classes</h3><p>Interface classes are a construct used in the Java programming language to <strong>define related methods and behaviors</strong>. An interface allows a class <strong>to implement a specific behavior or fulfill an interface</strong>. This enables Java to <strong>support multiple inheritance and allows different classes to have similar behavior</strong>.</p><p>An interface only <strong>defines the signatures of methods (parameter list and name) without specifying the implementation details</strong>. This means that interfaces can be thought of as a contract or agreement between classes. When a class implements an interface, it is obligated to implement all the methods defined in that interface.</p><p>The author of the book <strong><em>‘Learning Java’ </em></strong>makes a great analogy about interfaces.</p><blockquote>Interfaces are kind of like Boy Scout or Girl Scout merit badges. A scout who has learned to build a birdhouse can walk around wearing a little sleeve patch with a picture of one. This says to the world, “I know how to build a birdhouse.” <strong>Similarly, an interface is a list of methods that define some set of behavior for an object. Any class that implements each method listed in the interface can declare at compile time that it implements the interface and wear, as its merit badge, an extra type — the interface’s type</strong>.</blockquote><h3>CAN-DO Relationship</h3><p>A similar relationship to the is-a relationship mentioned in abstract classes exists here as well. I believe that these relationships contribute to a clearer and easier understanding of these concepts.</p><p>In the case of interface classes, a <strong>can-do</strong> relationship is established between the interface and the classes implementing it. We can think of it as <strong>having a certain skill</strong>. When a class implements an interface, <strong>it can possess the abilities defined by that interface</strong>.</p><p>To describe with a small example,</p><blockquote>WhatsApp <strong>can do</strong> voice call</blockquote><p>Let’s imagine in this example that we have an interface class named “<strong>Phone</strong>” and a subclass named “<strong>WhatsApp</strong>” where the “<strong>WhatsApp</strong>” class implements the “<strong>Phone</strong>” interface. Let’s put this into code💻</p><pre>public interface Phone(){<br>    void voiceCall();<br>    void textMessage(String message);<br>}</pre><p>Here, we have created a “<strong>Phone</strong>” interface and specified its methods. Now, we’re going to enhance our previous example and demonstrate the usage of multiple interfaces.</p><pre>public class WhatsApp() implements Phone{<br>   private String logoColor;<br>   <br>   public WhatsApp(String color){<br>      this.logoColor = color;<br>   }<br><br>   @Override<br>   public void voiceCall(){<br>      System.out.println(&quot;Starting voice call via WhatsApp&quot;);<br>   }<br><br>    @Override<br>   public void textMessage(String message){<br>      System.out.println(message + &quot; message sent via WhatsApp&quot;);<br>   }<br>}</pre><p>In this example, by implementing the <strong>Phone interface</strong>, we have added the <strong>voiceCall()</strong> and <strong>textMessage()</strong> functionalities to the <strong>WhatsApp class</strong>.</p><p>So far, we have only used a single interface, but Java <strong>supports multiple interface inheritance</strong>. This means that <strong>a class can implement multiple interfaces</strong>. Now, let’s enhance our previous example to demonstrate the usage of multiple interfaces.</p><pre>public interface Phone {<br>    void makeCall(String phoneNumber);<br>    void sendMessage(String message);<br>}<br><br>public interface Camera {<br>    void takePhoto();<br>    void recordVideo();<br>}</pre><p>Here are created two separate interface classes, <strong>Phone and Camera</strong>. Now let’s implement them in the WhatsApp class.</p><pre>public class Whatsapp implements Phone, Camera {<br>   private String logoColor;<br>   <br>   public WhatsApp(String color){<br>      this.logoColor = color;<br>   }<br><br>   @Override<br>   public void makeCall(String phoneNumber) {<br>        System.out.println(phoneNumber+&quot; calling via WhatsApp&quot;);<br>   }<br><br>   @Override<br>   public void sendMessage(String message) {<br>        System.out.println(message+&quot; was sent via WhatsApp&quot;);<br>   }<br><br>   @Override<br>   public void takePhoto() {<br>        System.out.println(&quot;Photo taking via WhatsApp&quot;);<br>   }<br><br>   @Override<br>   public void recordVideo() {<br>        System.out.println(&quot;Video recording via WhatsApp&quot;);<br>   }<br>}</pre><p>As shown in the example, by implementing two different interfaces in the WhatsApp class, we provided the class with different capabilities.</p><p>Now that we have covered some of the examples, let’s explore a few more to see how we can apply these concepts in our real projects.</p><h3>Real Life Examples</h3><ul><li>As we did with Abstract, we’ll look into it in the case of e-commerce<strong>.</strong> Suppose we want to <strong>integrate a payment system</strong>. We can create a <strong>common interface called PaymentGateway</strong>. Whenever we want to integrate a new payment system into the system, each payment system would implement the PaymentGateway interface and implement its own payment methods. Another example could be related to shipping options. We can think of different classes representing various shipping providers, and we can create a common interface for them. Each shipping provider would implement this common interface and carry out the shipping operations.</li><li>Another example could be an <strong>hotel management system</strong>. We can create an interface called <strong>Room to represent different types of rooms</strong>. Each room type would implement the Room interface and handle operations such as room booking and receiving room information.</li></ul><p>So far, we have examined both concepts separately and provided examples. Now, we’re going to combine what we have learned and write a sample code that uses both concepts(abstract+interface) together.</p><pre>// Abstract<br>abstract class Animal {<br>    abstract void sound();<br>}<br><br>// Interface<br>interface Swimming{<br>    void swim();<br>}<br><br><br>// The Duck class that inherited from <br>// Animal and implemented from Swimmable<br>class Duck extends Animal implements Swimming{<br>    @Override<br>    void sound() {<br>        System.out.println(&quot;Duck sound..&quot;);<br>    }<br><br>    @Override<br>    public void swim() {<br>        System.out.println(&quot;Duck is swimming..&quot;);<br>    }<br>}<br><br>// Main class<br>public class Main {<br>    public static void main(String[] args) {<br>        Duck duck = new Duck();<br>        duck.sound(); <br>        duck.swim();   <br>    }<br>}</pre><p>In this example, we created an abstract class named <strong>Animal and an interface named Swimming</strong>. Then, we wrote <strong>the Duck class</strong>, which <strong>inherits from the Animal class and implements the Swimming interface</strong>. The Duck class fulfills the requirements of the sound method from the abstract class and the swim method from the interface. And so, we see that<strong> in Java, a class can inherit from an abstract class and implement an interface at the same time</strong>.</p><p>Now that we have also covered the concept of interfaces, it’s time to summarize everything we have discussed in brief bullet points.</p><ul><li>Interfaces only contain method signatures, <strong>not method implementations</strong>.</li><li>They establish a <strong>can-do</strong> relationship with the classes that implement them.</li><li>A class can inherit <strong>from multiple interfaces</strong>.</li><li>By default, all interface members are implicitly abstract and public. You don’t need to explicitly specify it.</li><li>Interfaces specify what a class should do, not how it should do it.</li><li>Like abstract classes, interface classes cannot be instantiated using the <strong>“new”</strong> keyword.</li></ul><h3>Interface vs. Abstract Classes</h3><p>At the end of this article, here is a comparative table serving as the summary of the entire article that includes everything we have covered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*v6LVdrcP6thocV2jt86ZAQ.png" /></figure><p>Thank you for taking the time to read this article. I have tried to provide information about Interface and Abstract classes as best as I can. I hope it has been a helpful piece of writing.</p><p>Happy Coding🖖🏼</p><p>For more reading you can visit my blog www.bayten.dev</p><h3>REFERENCES</h3><ul><li>Abstract Methods and Classes (The JavaTM Tutorials, Learning the Java Language, Interfaces and Inheritance) <a href="https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html">https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html</a></li><li>Interfaces. In Learning java: An Introduction to Real-World Programming with Java (Fifth, pp. 161–162). O’REILLY MEDIA.</li></ul><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=669c858b18af" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/abstract-classes-and-interfaces-in-java-abstraction-and-flexibility-669c858b18af">Abstract Classes and Interfaces in Java: Abstraction and Flexibility</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java’da Abstract ve Interface Sınıflar: Soyutlama ve Esneklik]]></title>
            <link>https://baytendev.medium.com/javada-abstract-ve-interface-s%C4%B1n%C4%B1flar-soyutlama-ve-esneklik-76089a365a8e?source=rss-75b342b9ae32------2</link>
            <guid isPermaLink="false">https://medium.com/p/76089a365a8e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Barış Ayten]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 13:28:16 GMT</pubDate>
            <atom:updated>2023-06-12T13:28:16.570Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*2PgjmamVyh2T7J5LI0V9Ow.png" /></figure><p>Herkese selamlar, 🖖🏼</p><p>Bu makalede, benim de çoğu zaman kullanırken kafamın karıştığı, hangisini neden kullandığımı anlayamadığım bir konu olan <strong>Abstract </strong>ve <strong>Interface </strong>kavramına değinmek istedim. Bu sınıfların ne olduğuna, neden kullanıldığına ve aralarındaki farklılıklara ayrıntılı olarak değinip anlatmaya çalışacağım. Şimdiden iyi okumalar🎇</p><p>Java’da Abstract ve Interface sınıflar, yazılım tasarımında abstraction kavramının güçlü bir şekilde temsil edilmesini sağlayan iki farklı yapıdır. <strong>Her ikisi de soyut sınıflardır ve doğrudan örneklendirilemezler, yani nesne olarak oluşturulamazlar.</strong> Ancak, bu yapılar kullanıldıkları senaryolara göre farklılıklar gösterirler ve benzersiz avantajlar sunarlar.</p><p>Abstract sınıflar, soyutlama yetenekleri sayesinde somut sınıflar arasında <strong>ortak özellikleri tanımlamak ve paylaşmak</strong> için kullanılır. Bu sınıflar, bir sınıf hiyerarşisinde ortak özelliklere sahip sınıfları gruplandırmak ve bu özellikleri miras yoluyla aktarmak için ideal bir araçtır.</p><p>Abstract sınıflar<strong> soyut ve somut metotları bir araya getirerek</strong>, alt sınıflar tarafından uygulanması gereken metotları belirleyebilirler. Böylece, <strong>kodun yeniden kullanılabilirliğini artırır ve birlikte çalışabilirlik</strong> sağlar.</p><p>Diğer yandan, Interface sınıflar, <strong>çeşitli sınıflar arasında ortak davranış ya da davranışları tanımlamak için</strong>, <strong>bir sınıfın hangi metotları uygulaması gerektiğini belirleyen bir nevi sözleşme olarak kullanılırlar.</strong> <strong>Java’ya çoklu miras desteğini sağlayıp, birden fazla interface’i uygulayabilmesini ve bu sayede çoklu mirasın sunduğu esneklik avantajını kullanabilmesini sağlar</strong>. Bu sayede kodun daha <strong>esnek, genişletilebilir ve bakımı kolay</strong> hale gelmesine yardımcı olurlar.</p><p>Buraya kadar her iki kavrama da kısa bir bakış attığımıza göre şimdi bu konseptleri daha detaylı bir şekilde inceleyebiliriz.🐱‍🏍</p><h3>Abstract Classes</h3><p><strong>Abstraction</strong>, gerçek dünyadaki karmaşık sistemleri daha basit ve anlaşılır bir şekilde temsil etmek için kullanılır. Örneğin, bir araba ve tüm arabalarda olabilecek ortak özelliklerini düşünelim. Yakıt tüketimi, hız, fren sistemi, kapı sayısı ya da renk gibi özellikler her arabada olabilir. İşte bu ortak özellikleri bir temel olarak kabul edip bir model yaratabiliriz. Ve bu temel modeli alıp özelliklerini farklılaştırarak değişik özelliklere sahip arabalar yaratabiliriz. İşte aslında burada yaptığımız şey bir soyutlama ve bu soyut sınıfı kullanarak yeni yeni sınıflar yaratmak.</p><p>Abstract sınıflar da böyle kullanılırlar. Temel özelliklere sahip bir abstract sınıf oluşturup tanımlayabiliriz. Farklı marka ve modellerdeki arabaları bu Abstract sınıftan türeterek özelleştirebiliriz.</p><p>Abstract sınıflar, soyut bir sınıfın <strong>özelliklerini (instance variables vs.) ve davranışlarını</strong> tanımlayan soyut yapılardır. Bu sınıflar, <strong>diğer somut sınıflar tarafından miras alınarak kullanılabilirler</strong>. Abstract sınıfları Interface’lerden ayıran en önemli özelliklerden biri, <strong>hem soyut hem de somut metotlar içerebiliyor olmalarıdır</strong>. İçerdikleri soyut sınıflar, abstract sınıfı inherit eden sınıflar tarafından tanımlanır. Böylece yazılan kodda esneklik sağlanır.</p><p>Hadi örnek olarak bir tane abstract sınıf yaratalım.</p><pre>abstract class Shape {<br>   protected String color;<br>   <br>   public Shape(String color) {<br>      this.color = color;<br>   }<br>   <br>   public abstract double area();<br>   <br>   public void display() {<br>      System.out.println(&quot;Bu bir &quot; + color + &quot; şekildir.&quot;);<br>   }<br>}</pre><p>Bu örnekte, <strong>Shape </strong>adında bir Abstract sınıf oluşturduk. Shape’in ortak özelliği olan “<strong>color</strong>” değişkenini ve “<strong>display</strong>” metodunu içeriyor. Ayrıca “<strong>area</strong>” metodu da soyut olarak tanımlanmıştır yani bu sınıfı inherit eden her alt sınıf <strong>area</strong> metodunu kendine göre yazabilir(<em>override</em>).</p><p>Şimdi <strong>Shape</strong> abstract sınıfını miras alan iki farklı sınıf yaratalım ve kullanımına bir bakalım.</p><pre>class Circle extends Shape {<br>   private double radius;<br>   <br>   public Circle(String color, double radius) {<br>      super(color);<br>      this.radius = radius;<br>   }<br>   <br>   public double area() {<br>      return Math.PI * radius * radius;<br>   }<br>}<br><br><br>// -----------<br><br><br>class Rectangle extends Shape { <br>   private double length;<br>   private double width;<br>   <br>   public Rectangle(String color, double length, double width) {<br>      super(color);<br>      this.length = length;<br>      this.width = width;<br>   }<br>   <br>   public double area() {<br>      return length * width;<br>   }<br>}</pre><p>Burada yazdığımız <strong>Rectangle</strong> ve <strong>Circle</strong> sınıfları <strong>Shape</strong> abstract sınıfını miras aldıklarında bu sınıfta tanımlı olan özelliklere sahip oluyorlar. Tabii eğer isterlerse de bu özellikler üzerine kendi özelliklerini ekleyebiliyorlar, mesela <strong>Circle</strong> sınıfındaki <strong>radius</strong> ya da <strong>Rectangle</strong> sınıfındaki <strong>width</strong> gibi…</p><h3>IS-A İlişkisi</h3><p>Burada aslında bahsetmek istediğim bir nokta daha var; <strong>is-a</strong> ilişkisi. Abstract sınıflar ve o abstract sınıfı inherit eden sınıflar arasında bir is-a ilişkisi kurulmuş olur. Bu ilişkiye, senaryomuzu da kullanarak kısaca örnek verecek olursak,</p><blockquote>The Rectangle <strong>is-a</strong> shape.</blockquote><blockquote>The Circle <strong>is-a</strong> shape.</blockquote><p>Yani en nihayetinde <strong>Rectangle </strong>ya da <strong>Circle </strong>bir <strong>Shape’dir </strong>ve <strong>Shape’in </strong>sahip olduğu tüm özelliklere sahiptir.</p><h3>Gerçek Hayat Projeleri</h3><p>Peki tamam her şey iyi güzel de, ben bu abstract sınıfları gerçek hayat projelerinde nasıl ya da ne zaman kullanacağım. Şimdi bunlar hakkında da bazı ufak örnekler vermeye çalışayım;</p><ul><li>Örneğin bir <strong>e-ticaret uygulaması</strong> yazdığımızı düşünelim. Bu uygulamada, ürünlerin genel özelliklerini temsil eden bir Abstract sınıf oluşturabiliriz. Örneğin, <strong>“Product”</strong> adında bir abstract sınıf oluşturarak ürünlerin <strong>ortak özelliklerini</strong> tanımlayabiliriz. Alt sınıflar, farklı ürün kategorilerini temsil edebilir ve abstract sınıfın özelliklerini kullanarak kendi özelleştirilmiş metotları tanımlayabilirler.</li><li>Ya da bir <strong>banka uygulaması</strong> kurguladığımızı düşünelim. Burada farklı banka hesap türlerini temsil eden bir abstract sınıf kullanabilirsiniz. Örneğin, <strong>“BankAccount”</strong> adında bir abstract sınıf oluşturarak hesap numarası, bakiye gibi ortak özellikleri tanımlayabiliriz. Alt sınıflar, farklı hesap türlerine (vadesiz hesap, birikim hesabı, kredi kartı hesabı) özgü metotları ve işlemleri tanımlayabilirler.</li></ul><h3>Özet</h3><p>Gerçek hayat örneklerinden de bahsettiğimize göre şimdi tüm konuyu maddeler halinde toparlamaya çalışalım;</p><ul><li>Abstract sınıflar hem metod hem de değişken içerebilirler.</li><li>Nesne olarak yaratılamazlar yani <strong>new() </strong>anahtar sözcüğü ile çağıralamazlar.</li><li>Miras alınabilirler.</li><li>Hem <strong>soyut </strong>hem de <strong>somut </strong>metotlar içerebilirler.</li><li>Yapıcı metotları(Constructor) vardır.</li><li>Kendilerini miras alan sınıflarla aralarında <strong>is-a</strong> ilişkisi kurulur.</li></ul><p>Şimdi bir diğer kavramımız olan Interface sınıflara göz atmaya başlayalım</p><h3>Interface Classes</h3><p>Interface sınıflar, Java programlama dilinde <strong>birbiriyle ilişkili metotları ve davranışları</strong> tanımlamak için kullanılan bir yapıdır. Bir interface, <strong>bir sınıfın belirli bir davranışı uygulamasını veya bir arayüzü gerçekleştirmesini</strong> sağlar. Bu sayede Java’da çoklu kalıtımı desteklemek ve <strong>farklı sınıfları benzer bir davranışa</strong> sahip olmasına olanak tanır.</p><p>Bir interface, <strong>sadece metodların imzalarını</strong> (aldığı parametre listesi ve isim) tanımlar, fakat bu metodların <strong>nasıl uygulanacağına dair detayları içermez</strong>. Bu da interface’leri, sınıflar arasında bir sözleşme veya kontrat olarak düşünebileceğimiz anlamına gelir. Bir sınıf, bir interface’i uyguladığında, o interface’de tanımlanan <strong>tüm metodları gerçekleştirmek zorundadır</strong>.</p><p>“<strong><em>Learning Java</em></strong>” kitabında interface’ler hakkında şöyle güzel bir benzetme yapmış yazar:</p><blockquote>Interfaces are kind of like Boy Scout or Girl Scout merit badges. <strong>A scout who has learned to build a birdhouse can walk around wearing a little sleeve patch with a picture of one. This says to the world, “I know how to build a birdhouse.”</strong> Similarly, an interface is a list of methods that define some set of behavior for an object. Any class that implements each method listed in the interface can declare at compile time that it implements the interface and wear, as its merit badge, an extra type — the interface’s type.</blockquote><p>Yani basit bir çeviriyle, <strong>bir izci ekibinin sahip olduğu becerileri bir rozet gibi üzerinde taşımasına, “Hey bakın, ben bunu ve şunu yapmayı biliyorum”</strong> demesine benzetiyor. Bu benzetme tam yerinde ve interface’leri çok güzel anlatan bir örnek olmuş.</p><h3>Can-Do İlişkisi</h3><p>Abstract class’larda bahsettiğim is-a ilişkisine benzer bir ilişki burada da mevcut. Bu ilişkilerin, bu konseptleri daha rahat ve kolay anlaşılmasına olanak sağladığını düşünüyorum.</p><p>Interface sınıflar ile bu sınıfı implement eden alt sınıflar arasında can-do ilişkisi kurulur. Yani bir beceriye sahip olma gibi düşünebiliriz. Bir sınıf, bir interface’i uyguladığında o interface’in tanımladığı becerilere sahip olabilir.</p><p>Küçük bir örnek ile anlatacak olursak,</p><blockquote><em>WhatsApp </em><strong><em>can do</em></strong><em> voice call</em></blockquote><p>Bu örnekte <strong>Phone</strong> adında bir interface sınıfı ve <strong>WhatsApp</strong> adında bir alt sınıfımız olduğunu hayal edelim ve <strong>WhatsApp</strong> sınıfı <strong>Phone</strong> interface’ini implement etsin. Hadi bunu koda dökelim.</p><pre>public interface Phone(){<br>    void voiceCall();<br>    void textMessage(String message);<br>}</pre><p>Burada bir Phone interface’i oluşturduk ve metotlarını belirttik. Şimdi WhatsApp adında bir sınıf oluşturalım ve bu interface’i kullanalım.</p><pre>public class WhatsApp() implements Phone{<br>   private String logoColor;<br>   <br>   public WhatsApp(String color){<br>      this.logoColor = color;<br>   }<br><br>   @Override<br>   public void voiceCall(){<br>      System.out.println(&quot;Starting voice call via WhatsApp&quot;);<br>   }<br><br>    @Override<br>   public void textMessage(String message){<br>      System.out.println(message + &quot; message sent via WhatsApp&quot;);<br>   }<br>}</pre><p>Bu örnekte Phone interface’ini implement ederek WhatsApp sınıfına voiceCall() ve textMessage() özelliklerini kazandırmış olduk.</p><p>Şimdiye kadar hep tek interface’i kullanmış olduk fakat <strong>Java’da çoklu interface desteği de bulunur</strong>. Yani bir sınıf birden fazla interface’i implement edebilir. Şimdi önceki örneğimizi geliştirerek çoklu interface kullanımına da örnek verelim.</p><pre>public interface Phone {<br>    void makeCall(String phoneNumber);<br>    void sendMessage(String message);<br>}<br><br>public interface Camera {<br>    void takePhoto();<br>    void recordVideo();<br>}</pre><p><strong>Phone</strong> ve <strong>Camera</strong> adında iki farklı interface sınıf oluşturdum. Şimdi bunları <strong>WhatsApp’a</strong> implement edelim.</p><pre>public class Whatsapp implements Phone, Camera {<br>   private String logoColor;<br>   <br>   public WhatsApp(String color){<br>      this.logoColor = color;<br>   }<br><br>   @Override<br>   public void makeCall(String phoneNumber) {<br>        System.out.println(phoneNumber+&quot; calling via WhatsApp&quot;);<br>   }<br><br>   @Override<br>   public void sendMessage(String message) {<br>        System.out.println(message+&quot; was sent via WhatsApp&quot;);<br>   }<br><br>   @Override<br>   public void takePhoto() {<br>        System.out.println(&quot;Photo taking via WhatsApp&quot;);<br>   }<br><br>   @Override<br>   public void recordVideo() {<br>        System.out.println(&quot;Video recording via WhatsApp&quot;);<br>   }<br>}</pre><p>Örneğimizde de gördüğümüz gibi <strong>WhatsApp</strong> sınıfında iki farklı interface implement edip bu sınıfa farklı beceriler kazandırmış olduk.</p><p>Peki örnekler de tamam, her şeyi anladık diye düşünüyorum. Fakat bu konsepti gerçek projelerimizde nasıl uygulayacağız, birkaç örnekle de buna bakalım.</p><h3>Gerçek Hayat Örnekleri</h3><ul><li>Abstract’ta olduğu gibi yine e-ticaret özelinde bir bakalım. Mesela <strong>ödeme sistemi</strong> entegre etmek istiyor olalım. Bir tane <strong>PaymentGateway</strong> adında ortak bir interface oluşturup sisteme her yeni bir ödeme sistemi entegre etmek istediğimizde, her ödeme sistemi, PaymentGateway interface’ini uygular ve kendi ödeme yöntemlerini gerçekleştirebilir. Ya da başka bir örnek olarak kargo seçeneklerini düşünelim; farklı kargo sağlayıcılarını temsil eden sınıflar için ortak bir interface yazabiliriz. Her kargo sağlayıcısı, bu ortak interface’i uygular ve kargo işlemlerini gerçekleştirir.</li><li>Bir başka örnek de bir <strong>otel yönetim sistemi</strong> olabilir. Farklı oda tiplerini temsil eden sınıflar için <strong>Room</strong> adında bir interface yazılabilir. Her oda tipi, <strong>Room</strong> interface’ini uygular ve oda rezervasyonu, oda bilgileri gibi işlemleri gerçekleştirir.</li></ul><p>Buraya kadar her iki kavramı da ayrı ayrı inceleyerek örnekler yaptık. Şimdi öğrendiklerimizi birleştirip iki kavramı da aynı anda kullandığımız bir örnek kod yazalım.</p><pre>// Abstract<br>abstract class Animal {<br>    abstract void sound();<br>}<br><br>// Interface<br>interface Swimable {<br>    void swim();<br>}<br><br><br>// The Duck class that inherited from <br>// Animal and implemented from Swimmable<br>class Duck extends Animal implements Swimable {<br>    @Override<br>    void sound() {<br>        System.out.println(&quot;Duck sound..&quot;);<br>    }<br><br>    @Override<br>    public void swim() {<br>        System.out.println(&quot;Duck is swimming..&quot;);<br>    }<br>}<br><br>// Main class<br>public class Main {<br>    public static void main(String[] args) {<br>        Duck duck = new Duck();<br>        duck.sound(); <br>        duck.swim();   <br>    }<br>}</pre><p>Bu örnekte, Animal adında bir abstract sınıf ve Swimable adında bir interface yarattık.Sonrasında yazdığımız Duck sınıfı, Animal sınıfını inherit eder ve Swimable interface’ini implement eder. Duck sınıfı, sound metodu için abstract sınıftan ve swim metodu için interface’den gelen gereksinimleri yerine getirir. Böylelikle <strong>Java’da bir sınıfın Abstract sınıftan inherit alırken aynı zamanda Interface’i de implement edebildiğini</strong> görmüş olduk.</p><p>Buraya kadar Interface kavramını da incelediğimize göre şimdi tüm bu bahsettiklerimizi kısa özet maddeler şeklinde toparlamaya çalışalım.</p><ul><li>Interface içinde metodların yalnızca imzaları yer alır, <strong>metod implementasyonu yer almaz.</strong></li><li>Kendisini inherit eden sınıflar ile arasında <strong>can-do</strong> ilişkisi kurulur.</li><li>Bir sınıf birden fazla interface’i inherit edebilir.</li><li>Bir interface sınıfında varsayılan olarak tüm interface üyeleri abstract ve public olarak tanımlanır. Sizin özellikle belirtmeniz gerekmez.</li><li>Bir sınıfın ne yapması gerektiğini belirtir, <strong>nasıl yapması gerektiğini değil.</strong></li><li>Abstractlar gibi interface sınıflar da <strong>new anahtar kelimesi ile örneklendirilemezler.</strong></li></ul><h3>Interface vs. Abstract Sınıflar</h3><p>Bu yazının da yavaştan sonuna gelmeden önce tüm bu makaleye kuş bakışı bakmamızı sağlayacak, her şeyin özeti olabilecek karşılaştırmalı tablomuzu hazırlayalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*mHm2zlzlI7rK5kjkwsJ84A.png" /></figure><p>Buraya kadar zaman ayırıp okuduğunuz için teşekkürler, elimden geldiğince Interface ve Abstract sınıflar hakkında bahsetmeye çalıştım. Umarım faydalı bir yazı olmuştur.</p><p>Happy Coding🖖🏼</p><h3><strong>REFERENCES</strong></h3><ul><li>Abstract Methods and Classes (The JavaTM Tutorials, Learning the Java Language, Interfaces and Inheritance) <a href="https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html">https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html</a></li><li>Interfaces. In Learning java: An Introduction to Real-World Programming with Java (Fifth, pp. 161–162). O’REILLY MEDIA.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76089a365a8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns | Fundamentals]]></title>
            <link>https://levelup.gitconnected.com/design-patterns-fundamentals-d1ba1c5a1859?source=rss-75b342b9ae32------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1ba1c5a1859</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Barış Ayten]]></dc:creator>
            <pubDate>Tue, 30 May 2023 12:24:12 GMT</pubDate>
            <atom:updated>2023-05-30T12:24:12.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*NKx9xxzg27zGmIHPimMGFw.png" /></figure><p>Hello Folks! 🖖🏼</p><p>I’ve decided to embark on a new article series, and I’m going to tackle <strong>Design Patterns</strong>. Combining the notes I’ve taken from the articles I’ve read and watched while learning Design Patterns, I’ve decided to create a perpetual resource on my blog.</p><p>I’m planning to divide this article series into <strong>four parts</strong>, where I’ll delve into each category and pattern in detail, accompanied by examples. Throughout the examples, <strong>I’ll be using Java as the programming language</strong>.</p><p>The article series will progress in the following order, as I anticipate:</p><ol><li><strong>Design Pattern Fundamentals</strong></li><li><strong>Creational Design Patterns</strong></li><li><strong>Structural Design Patterns</strong></li><li><strong>Behavioral Design Patterns</strong></li></ol><p>We’ll start with this article to provide <strong>a nice introduction and gain a general overview and understanding of Design Pattern concepts</strong>. In the subsequent articles, we’ll meticulously delve into each remaining part separately.</p><p>Without further ado, let’s dive into our first topic! 🤘🏼</p><p>Design Patterns, in the realm of software development, hold a significant place as the cool-sounding name for a set of standardized software designs that developers employ to <strong>tackle recurring problems, create more flexible, sustainable, and reusable code in their projects</strong>.</p><p>These designs, comprising numerous different patterns, are categorized into <strong>three distinct groups based on their usage and purposes, as outlined below</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*2ngMSVQTgr0zyNiko7u7ig.png" /></figure><p>Let’s now roughly delve into the realm of <strong>Creational Design Patterns</strong>, which will be one of the pillars of our article series, and try to grasp what they are all about.🎉</p><h3>Creational Design Patterns</h3><p>Creational Design Patterns encompass a category of design patterns that <strong>revolve around the process of creating new objects</strong>. In this category, the patterns focus on <strong>how an object can be created in a flexible and reusable manner</strong>.</p><blockquote>“In software engineering, creational design patterns are design patterns that deal with <strong>object creation mechanisms, trying to create objects in a manner suitable to the situation.</strong> The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.”<em> (1)</em></blockquote><p>We’ve covered it quite extensively in the previous lines, but if we were to highlight them in bullet points, these design patterns address the following concerns:</p><ul><li>How objects are created.</li><li>Managing the processes involved in creating large and complex objects.</li><li>Defining the requirements during the creation of objects.</li><li>Determining which objects to use in the object’s creation.</li></ul><p>Within this category, we’ll explore 6 different patterns. Now, let’s take a quick peek at them.🧐</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*p9SjGNk0pOn5In27-I5SJg.png" /></figure><ul><li><strong>Singleton Pattern</strong>: It is used to design a class with only one instance.</li><li><strong>Factory Method Pattern</strong>: It allows subclasses to use the interface of the parent class to create objects.</li><li><strong>Abstract Factory Pattern</strong>: It enables the creation of objects in a group that are related to each other.</li><li><strong>Builder Pattern</strong>: It allows the step-by-step construction of complex objects.</li><li><strong>Prototype Pattern</strong>: It is used to create copies of objects.</li></ul><p>As mentioned at the beginning of the article, we briefly covered each pattern. Now, let’s take a look at our next category, <strong>Structural Design Patterns</strong>. 🐱‍🏍</p><h3>Structural Design Patterns</h3><p>The patterns within this category determine how the different components of software will:</p><ul><li>Come together,</li><li>Get organized, and</li><li>Interact with each other.</li></ul><p>These design patterns are in line with the principles of <strong>object-oriented programming (OOP) and help optimize the interaction between the various components of the software</strong>.</p><blockquote>Structural design patterns explain <strong>how to assemble objects and classes into larger structures, while keeping these structures flexible and efficient.</strong><em> (2)</em></blockquote><p>Structural Design Patterns allow for <strong>easier understanding and more convenient maintenance of the code and the resulting structure</strong>. These design patterns, especially during the development of large and complex software, provide developers with <strong>opportunities to better organize and reuse their code</strong>.</p><p>Within the <strong>Structural Pattern</strong> category, there are 7 different design patterns.</p><p>These include:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*BXyRrtjhLgXpPAqxa0QxYw.png" /></figure><ul><li><strong>Adapter Pattern</strong>: It is a structural design pattern that enables two classes with different interfaces to work together harmoniously.</li><li><strong>Bridge Pattern</strong>: It is a design pattern that separates the abstraction and implementation, allowing them to vary independently.</li><li><strong>Composite Pattern</strong>: It is a design pattern that creates objects in a hierarchical structure, enabling operations to be performed on the entire structure instead of individually handling each object.</li><li><strong>Decorator Pattern</strong>: It is a structural design pattern that dynamically adds new features to an existing object.</li><li><strong>Facade Pattern:</strong> It is a design pattern that simplifies a complex system by providing an interface for clients to interact with, making it easier for clients to use the system.</li><li><strong>Flyweight Pattern:</strong> It is a design pattern that prevents the repeated creation of similar objects, thereby improving system performance.</li><li><strong>Proxy Pattern:</strong> It is a design pattern that acts as a substitute for an object and controls access to that object.</li></ul><p>Up until now, we have gained some understanding about two different categories and the 12 design patterns within them. At least now we’re not completely clueless! 😁</p><p>Now, let’s take a look at our final guest of this article, <strong>Behavioral Design Patterns</strong>.</p><h3>Behavioral Design Patterns</h3><p>Our pals in this design pattern category actually have similar goals. They assist in <strong>organizing interactions and responsibilities among objects</strong>.</p><p>Let’s dive into the various <strong>Behavioral Design Patterns</strong> and explore their roles.</p><blockquote>Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects.<em> (3)</em></blockquote><p>These patterns help <strong>make object behaviors more flexible and cohesive</strong>. They are used to <strong>facilitate easier maintenance and development of software</strong>.</p><p>Here are some important <strong>Behavioral Design Patterns</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*8eweLwh-TMSKOF4NjuNgSA.png" /></figure><ul><li><strong>Observer Pattern</strong>: Establishes a relationship between objects, enabling automatic updates to dependent objects when one object changes.</li><li><strong>Command Pattern:</strong> Encapsulates a command-containing class, allowing separation of objects responsible for executing and parameterizing the command. This enables different ways of invoking and undoing the command.</li><li><strong>Iterator Pattern</strong>: Provides an interface for accessing elements of a collection sequentially, ensuring the access method remains consistent even if the collection’s structure changes.</li><li><strong>Template Method Pattern:</strong> Defines the steps of a process and allows subclasses to implement these steps as desired.</li><li><strong>Strategy Pattern:</strong> Encapsulates a class containing an algorithm, enabling different objects to apply the algorithm. This allows the algorithm to be applied in different ways and changed at runtime.</li><li><strong>Chain of Responsibility Pattern:</strong> Creates a chain of objects where each object is responsible for handling a specific request. The request is passed along the chain until it is handled.</li><li><strong>State Pattern:</strong> Used to manage an object’s state and change its behavior based on the current state.</li><li><strong>Interpreter Pattern:</strong> Provides an object structure for interpreting a specific part of a language and interpreting the data accordingly.</li><li><strong>Mediator Pattern:</strong> Instead of direct communication between objects, it uses a mediator object to facilitate communication and maintain independence among objects.</li><li><strong>Visitor Pattern:</strong> Provides an interface for accessing elements in an object structure and allows different objects to perform different operations on these elements.</li></ul><p>These patterns <strong>contribute to creating more flexible and maintainable software systems by defining clear interactions and responsibilities among objects</strong>.</p><p>Let’s summarize it. We have three different categories of patterns at our disposal. These are:</p><ul><li><strong>Creational</strong></li><li><strong>Structural</strong></li><li><strong>Behavioral</strong></li></ul><p>And each of these categories focuses on a different mechanism.</p><ul><li>Creational Patterns <strong>deal with the creation of objects</strong>.</li><li>Structural Patterns address <strong>how objects will come together and be organized once they are created</strong>.</li><li>Behavioral Patterns allow us to <strong>make adjustments regarding interactions and responsibilities among objects.</strong></li></ul><p>Thank you for taking the time to read through it. If you notice any missing or incorrect points, please feel free to let me know, and I’ll be happy to make the necessary corrections. I hope that the notes I have gathered here will be of some use to you and contribute to your work, even a little bit.</p><p>Happy Coding 🖖🏼</p><p>For more reading you can visit my blog bayten.dev</p><h3>References</h3><ul><li>Design Patterns. <a href="https://sourcemaking.com/design_patterns">https://sourcemaking.com/design_patterns</a> (1),(2)</li><li>Tasarım Desenleri, <a href="https://yusufyilmazfr.gitbook.io/tasarim-desenleri-turkce-kaynak/tasarim-desenleri/tasarim-deseni-nedir">https://yusufyilmazfr.gitbook.io/tasarim-desenleri-turkce-kaynak/tasarim-desenleri/tasarim-deseni-nedir</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1ba1c5a1859" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/design-patterns-fundamentals-d1ba1c5a1859">Design Patterns | Fundamentals</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode | Backspace String Compare]]></title>
            <link>https://baytendev.medium.com/leetcode-backspace-string-compare-4d10afe92e1d?source=rss-75b342b9ae32------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d10afe92e1d</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <dc:creator><![CDATA[Barış Ayten]]></dc:creator>
            <pubDate>Sun, 16 Apr 2023 13:38:22 GMT</pubDate>
            <atom:updated>2023-04-16T13:38:22.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*biGh-tR2-0j2bzGAiHW1Yg.png" /></figure><h3>Herkese selamlar🤘🏼</h3><p>Bugünkü sorumuz <a href="https://leetcode.com/problems/backspace-string-compare/">Backspace String Compare</a>. Soru <strong>kolay</strong> katergorisinde bulunuyor.</p><p>Yavaştan soruya geçelim.</p><h3>Soruyu Anlayalım🤔</h3><p>Soruda bize s ve t adında iki tane String değişkeni veriliyor. Bu değişkenler # karakteri içeriyor ve bu karakterin silme görevi yani <strong><em>backspace</em></strong> olduğu söylenmiş. Bizden istenen ise, <strong>her bir değişkende backspace karakterinden önce hangi karakter var ise, bu karakteri String değişkenimizden silmemiz.</strong></p><p>Soruyu daha net anlayıp, kafamızda canlandırabilmek için bize sunduğu örnekleri inceleyelim.</p><h3>Örnek 1</h3><pre>Input: s = &quot;ab#c&quot;, t = &quot;ad#c&quot;<br><br>Output: true<br><br>Açıklama: s değişkeninde # karakterinden önce &#39;b&#39; karakterini ve <br>          t değişkeninde # karakterinden önce gelen &#39;d&#39; karakterini <br>          kaldırdığımızda elimizde iki tane aynı String ifade olmuş<br>          oluyor, &quot;ac&quot; ve &quot;ac&quot; olarak. Bu yüzde True dönüyoruz.</pre><h3>Örnek 2</h3><pre>Input: s = &quot;ab##&quot;, t = &quot;c#d#&quot;<br><br>Output: true<br><br>Açıklama: Burda da iki kez kaldırma işlemi yapıyoruz. Ve sonunda<br>          elimizde iki tane boş String oluyor &quot;&quot; ve &quot;&quot;. Bu yüzden<br>          true olarak sonucu dönüyoruz.</pre><h3>Örnek 3</h3><pre>Input: s = &quot;a#c&quot;, t = &quot;b&quot;<br><br>Output: false<br><br>Explanation: Burada da aynı işlemleri uygulayınca (t değişkeninde<br>             backspace yok) elimizde &quot;a&quot; ve &quot;b&quot; kalıyor. Dolayısıyla<br>             eşit olmadıkları için False dönüyoruz.</pre><h3>Soruya Girişelim 🥊</h3><p>Burada yapmamız gerekenler aslında basit. Temelde # karakterini gördüğümüz yerde, bir önceki elemanı değişkenden silmek. Peki bunu nasıl uygulayabiliriz?</p><p>Benim ilk aklıma gelen <strong>Stack</strong> mantığını burada kullanmak. Yani mesela elimizde s = &quot;barr#is&quot; değişkeni olduğunu varsayalım ve bir döngü ile bu değişkenin her bir karakterinde ilerleyelim. Eğer karakter # backspace karakterimize eşit değilse, o karakteri stack’e ekleyelim. Eğer # backspace karakterine denk gelirsek de, stack’imizden elemanı çıkaralım.</p><p>Burada ben bu stack mantığını <strong>StringBuilder</strong> ile implemente edeceğim. Neden bunu seçtim? Öncelikle elimizdeki değişken bir <strong>String</strong> yani aslında <strong>char dizisi</strong>. Ve String değişkenleri <strong>immutable</strong> değişkenler olduğu için ben her manipule etmeye çalıştığımda hafızada yeni bir alan yaratılıp, manipule edilen hali orada tutulacak. <strong>Yani kısacası gereksiz hafıza kullanımından kaçınmak istiyorum.</strong> (Detayı için bknz. <a href="https://bayten.dev/posts/string-stringbuilder-and-stringbuffer-in-java/">String, StringBuilder, and StringBuffer in Java</a>)</p><p>Bir diğer sebebi de, StringBuilder’ın sahip olduğu append() ve deleteCharAt() metodları. append() ile stack gibi en sona ekleme yapabileceğim, deleteCharAt() metodu ile de istediğim yerden, aslında en sondan, silme işlemini (stack’lerde olduğu gibi) gerçekleştirebileceğim.</p><p>Şimdi bu düşündüklerimizi koda dökelim.</p><pre>   public static boolean backspaceCompare(String s, String t) {<br>        String sb1 = getFinalString(s);<br>        String sb2 = getFinalString(t);<br><br>        return sb1.equals(sb2);<br>    }<br><br><br>    // tek tek aynı adımları yapmak yerine<br>    // ayrı bir fonksiyon yazdım<br>    public static String getFinalString(String s) {<br>      StringBuilder sb = new StringBuilder();<br><br>      for (char c : s.toCharArray()) {<br>        if (c == &#39;#&#39; &amp;&amp; sb.length() &gt; 0) sb.deleteCharAt(sb.length()-1);<br>        else sb.append(c);<br>       }<br>      return sb.toString();<br>    }</pre><p>Yazdığımız bu kodu adım adım inceleyelim;</p><ul><li>backspaceCompare() fonksiyonu, iki string parametresi alır: s ve t. İlk önce, her iki string de # karakterinden önceki karakterleri silerek, geriye kalan karakterleri içeren yeni stringler oluşturulur. Bunu yapmak için, getFinalString() fonksiyonunu kullanır.</li><li>getFinalString() fonksiyonu ile # karakterinden önceki karakterleri silerek sonuçta geriye kalan karakterleri içeren yeni bir string oluşturuyoruz.</li><li>Burada bir <strong>StringBuilder</strong> nesnesi oluşturuyoruz. Bu nesne aslında bizim <strong>stack’imizi</strong> temsil edecek ve silme işlemlerinden sonra geriye kalan karakterleri tutmak için kullanılacak.</li><li>Daha sonra, for döngüsü kullanarak, fonksiyona gönderilen <strong>String</strong> değişkeninin üzerindeki her karakteri tek tek kontrol ediyoruz.</li><li>Döngü, her karakteri kontrol edip ‘<strong>#’</strong> karakteri ile karşılaştığında ve StringBuilder nesnesi <strong>boş değilse</strong>, buradaki son karakteri siler (backspace’ten önceki karakter silindiği için).</li><li>Diğer durumlarda ise, karakter <strong>StringBuilder</strong> nesnesine eklenir.</li><li>Son olarak, fonksiyon geri döndürülmeden önce StringBuilder nesnesi, <strong>String’e</strong> dönüştürülür ve geri döndürülür.</li><li>Son olarak, fonksiyondan dönen her iki <strong>String</strong> karşılaştırır. Eğer stringler birbirine eşitse, true döndürülür, aksi takdirde false döndürülür.</li></ul><p>Yazdığımız bu kodun <strong>time complexity</strong>‘sinden bahsedecek olursak eğer, burada oluşturduğumuz getFinalString() fonksiyonu parametre olarak aldığı s değişkeninin tüm elemanlarını ziyaret ediyor. Durum böyle olunca time complexity için <strong>O(n)</strong> diyebiliriz. Buradaki <strong>N</strong> aslında bize input olarak verilen s ve t String’lerinin uzunluğudur. Bu nedenle, programın çalışması, <strong>String’lerin toplam karakter sayısına bağlı olarak artacaktır.</strong></p><p>Tabii ki bu problemin birden farklı ve daha efektif çözüm yolları olabilir, benim çözüm yolum bu şekildeydi ve bunu açıklayıcı bir şekilde anlatmak istedim.</p><p>Buraya kadar zaman ayırıp okuduğunuz için teşekkürler,</p><p>Happy Coding🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d10afe92e1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Method Overriding and Overloading in Java]]></title>
            <link>https://levelup.gitconnected.com/method-overriding-and-overloading-in-java-fab89e19b0a7?source=rss-75b342b9ae32------2</link>
            <guid isPermaLink="false">https://medium.com/p/fab89e19b0a7</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[intervi]]></category>
            <dc:creator><![CDATA[Barış Ayten]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 15:55:47 GMT</pubDate>
            <atom:updated>2023-06-15T00:59:16.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t0mJsAbX-uGJpR4pHvr5RA.png" /></figure><p>Hello everyone 🤘🏼</p><p>In this article, we’ll be taking a look at the concepts of method <strong>overloading</strong> and <strong>overriding</strong> in Java, which I believe are often forgotten and confused by beginners (at least I was 😁).</p><p>Before delving into these two concepts in detail, I’d like to briefly mention them. Method overriding is simply changing the functionality of a method without changing its signature, while method overloading is redefining a method with a different signature.</p><blockquote><strong>These two definitions may not make much sense yet because I have only mentioned them briefly and in a simplistic manner. Although this section consists of only two sentences that may seem meaningless for now, by the end of the article, they will have the power to summarize the entire article.</strong> 🙂</blockquote><p>Before we dive into the topic fully, there is one tiny concept we need to learn and understand: <strong>The Method Signature</strong>.</p><p>Method signatures consist of <strong>the name of a method</strong> and its <strong>method parameters</strong>. As shown in the image below, the signature of the method named justFun consists of its name “<strong>justFun</strong>” and its parameters int num1, int num2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*w0ZpI01ql1Wvmyq5vtRcTw.png" /></figure><p>I believe we have clarified this simple and short concept. Now, let’s dive into the main concepts of this article. 🚀</p><h3>Method Overriding</h3><p>Method overriding, in simple terms, refers to methods that <strong>have the same signature but perform different tasks</strong>. How does this situation arise?</p><p>Let’s assume that we have a class named Animal with a method named eat(). Now, I have created another class named Dog, and I want it to inherit from the Animal class. When we perform the inheritance process, we would like to use the eat() method inherited from the super class in a way that is suitable for our subclass. Therefore, <strong>we change its functionality</strong>. In other words, we override the eat() method.🙂</p><p>Let’s give an example!</p><pre>class Animal{  <br>  public void eat(){System.out.println(&quot;eating...&quot;);}  <br>}  <br><br>//Overriding way<br>class Dog extends Animal{  <br>  public void eat(){System.out.println(&quot;eating bread...&quot;);}  <br>}<br><br>class Cat extends Animal{  <br>  public void eat(){System.out.println(&quot;eating fish...&quot;);}  <br>}</pre><p>As we saw in the example, I did not touch the method signatures in any way. I did not change the method name or send a new parameter to that method… <strong>I just played with the internal dynamics of the method and added a completely different functionality.</strong></p><p>Well, you may have a question like this in your mind🤔:</p><blockquote><strong>“What about the access modifiers of the methods we override? Do they have to be the same?”</strong></blockquote><p>Our answer to this question will be no.</p><p>They do not have to be the same, <strong>but the access modifier of the overriding method must be the same or less restrictive than the original method.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*NNa2SOOPPed-SRSifsjlww.png" /></figure><p>According to the restriction diagram in the image, if a protected method is to be overridden, <strong>its access modifier cannot be default or private</strong>. It can either remain protected or be made public. In short, when overriding a method, <strong>the access modifier in the subclass must be the same as or less restrictive than that in the superclass.</strong></p><p>Another question that might come up is ☝🏼,</p><blockquote><strong>“Do the return types of the methods we override have to be the same? Can’t I specify a different return type?”</strong></blockquote><p>Our answer to this question <strong>will be no</strong> 🙂.</p><p>When overriding a method, <strong>the return type of the method must remain the same, along with the method signature</strong>. This is primarily based on Java’s principle of type safety.</p><p>If a subclass could use a different return type while overriding methods of the superclass, it could lead to errors in places where the superclass is used.</p><p>However, there is an exception to this rule where <strong>the return type of the overridden method can be a co-variant return type</strong>.</p><p>For example, suppose the return type of a superclass is Animal, and the return type of the subclass is Cat. While overriding the superclass method, the subclass can specify the return type as Cat. This way, the object returned by the subclass will not be of type Animal, but of a more specific subtype, which is Cat.</p><p>Well, maybe another question that could arise is 🎇,</p><blockquote><strong>“Can I override every method?”</strong></blockquote><p>It may be the most fundamental question to ask. Our answer to this question, unfortunately, will still be no. 😁</p><p>If the method to be overridden is:</p><ul><li><strong><em>final</em></strong></li><li><strong><em>static</em></strong></li><li><strong><em>private</em></strong></li></ul><p>then we cannot override these methods. This is because <strong>the nature of the override operation is based on inheritance</strong>. Methods with these three keywords cannot be inherited, so they cannot be overridden either.</p><p>However, sometimes a subclass can redefine a static method of the superclass. Some of us might have seen this situation before. This is not an override but is called <strong>Method Hiding.</strong></p><p>If we summarize the process of overriding;</p><ul><li>After the override process, the method signature remains the same (method name and parameters must stay the same), only the functionality of the method changes.</li><li>The return type of the overridden method should not change or it should be a co-variant return type.</li><li>The access modifier of the overridden method should be the same or less restrictive than the original method.</li><li>private, static, final methods cannot be overridden.</li></ul><p>Now that we have gained a general understanding and logic about overriding, let’s take a look at the concept of overloading 🤘🏼.</p><h3>Method Overloading</h3><p>Method Overloading is <strong>the redefinition of a method with the same name but different parameters</strong>. This means that the parameter section of the method signature is changed. This allows for the creation of different methods that perform the same task but with different parameter types, which can be called independently.</p><p>Let’s try to clarify the situation with some short code examples,</p><pre>public class Calculator {<br>  public int summation(int num1, int num2) {<br>      return num1 + num2;<br>  }<br>  <br>  public int summation(int num1, int num2, int num3) {<br>      return num1 + num2 + num3;<br>  }<br>  <br>  public static void main(String[] args) {<br>      Calculator calc = new Calculator();<br>      int result1 = calc.summation(2, 3);<br>      int result2 = calc.summation(2, 3, 4);<br><br>      System.out.println(&quot;Summation of 2 and 3: &quot; + result1);<br>      System.out.println(&quot;Summation of 2, 3 and 4:  &quot; + result2);<br>  }<br>}</pre><p>In the example above, we defined two different methods with the name summation() inside the Calculator class, where the first method takes <strong>two integer parameters</strong>, and the second method takes <strong>three integer parameters</strong>. In the main method, we call both methods with different parameters and print the result to the screen.</p><p>Let’s take a look at another example to reinforce our understanding.</p><pre>public class HelloWorld {<br>    public void greet() {<br>        System.out.println(&quot;Hello, world!&quot;);<br>    }<br>    <br>    public void greet(String name) {<br>        System.out.println(&quot;Hello, &quot; + name + &quot;!&quot;);<br>    }<br>    <br>    public static void main(String[] args) {<br>        HelloWorld helloWorld = new HelloWorld();<br>        helloWorld.greet();<br>        helloWorld.greet(&quot;John&quot;);<br>    }<br>}</pre><p>In the example above, the HelloWorld class defines two different methods named greet().</p><p>The first method is a simple greeting method that takes <strong>no parameters</strong> and prints the message <em>“Hello, world!”</em>. The second method takes <strong>a parameter of type String</strong> and uses it to create a customized greeting message. Both methods are called in the main method and their results are printed to the console.</p><p>Okey, now that we have gone through the examples, I think we have some understanding about method overloading. Let’s delve into some details about overloading using the same questions we used for understanding override.</p><p>Then our first question can be as follows🎇</p><blockquote><strong>“When overriding a method, we had to carefully choose the Access Modifier. That is, we had to either use the same Access Modifier as the previous method or a less restrictive one. Is this also true for Overloading?”</strong></blockquote><p>Our answer should be no 🙂</p><p>The logic here is different from overriding. Access modifier selection was important for overriding because inheritance played a leading role. However, in overloading, <strong>we have no constraints and we are completely free to choose any modifier we want.</strong></p><p>As in the example below,</p><pre>public int sum(int a, int b, int c) {<br>        return a + b + c;<br>    }<br><br>protected void sum() {<br>        System.out.print(&quot;Nothing to sum&quot;);<br>    }</pre><p>And for our another question,</p><blockquote><strong>“The return types of the methods we override must be the same or a co-variant type. How does this work in Overloading?”</strong></blockquote><p>Actually, we have already demonstrated this situation in the example we provided earlier. <strong>The return type is not important in Overloading. It can be the same or different.</strong></p><blockquote><strong>“Can I overload every method?”</strong></blockquote><p>The answer to this question should be yes 🙂 There is no problem with overloading a method that is private, static, or final.</p><p>Let’s reinforce this situation with the example below.</p><pre>public class Example {<br>    public static void doSomething(int x) {<br>        System.out.println(&quot;doSomething with int: &quot; + x);<br>    }<br>    <br>    public static void doSomething(double x) {<br>        System.out.println(&quot;doSomething with double: &quot; + x);<br>    }<br>    <br>    public final void doSomething(String x) {<br>        System.out.println(&quot;doSomething with String: &quot; + x);<br>    }<br>}</pre><p>If we summarize the overloading process in short points;</p><ul><li>After the overloading process, <strong>the method signature changes (method name remains the same, method parameters change).</strong></li><li>The return type of the overloaded method can <strong>remain the same or be different.</strong></li><li>The access modifier of the overloaded method can remain the same or be different. private, static, final methods can also be overloaded, there is no restriction.</li></ul><p>If we’ve made it this far understanding, I believe we have an idea about the concepts of <strong>Overloading and Overriding</strong>. This has been a compilation of what I’ve learned and researched about Override and Overload. Thank you for taking the time to read this far.</p><p>Happy Coding! 🤞🏼</p><p>⭐For the original article -&gt; <a href="https://bayten.dev/posts/method-overriding-and-overloading-in-java/">https://bayten.dev/posts/method-overriding-and-overloading-in-java/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fab89e19b0a7" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/method-overriding-and-overloading-in-java-fab89e19b0a7">Method Overriding and Overloading in Java</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mutability and Immutability in Java]]></title>
            <link>https://baytendev.medium.com/mutablity-and-immutablity-in-java-a003b754b642?source=rss-75b342b9ae32------2</link>
            <guid isPermaLink="false">https://medium.com/p/a003b754b642</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[Barış Ayten]]></dc:creator>
            <pubDate>Thu, 23 Mar 2023 13:09:26 GMT</pubDate>
            <atom:updated>2023-03-23T19:25:27.503Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*l4gd4VaxTks-3OCkpxVKSA.png" /></figure><p>Hello Folks 🖖🏼,</p><p>The topic of this article will be about the concept of Mutablity and Immutablity in Java. I will try to answer questions such as <strong>“What does Mutable &amp; Immutable mean?”</strong>, “<strong>What is the logic behind this functionality?</strong>”, “<strong>How are Mutable or Immutable classes created?</strong>”, “<strong>What are the advantages and disadvantages?</strong>”.</p><p>Let’s dive right in and explore these fascinating concepts together. 🚀</p><h3>1. Mutable Classes</h3><p>Mutable objects are objects that <strong>can be modified after they are initialized</strong>. In some cases, these types of classes can be preferred over immutable classes due to their flexibility and mutable fields.</p><p>Examples of these classes include <strong>StringBuffer</strong>, <strong>StringBuilder</strong>, and the <strong>Date</strong> class found in the Java util package. To further clarify what I mean, let me provide a short code example.</p><pre>// Initialize variable called myString<br>StringBuilder myString = new StringBuilder(&quot;Hello&quot;);<br><br>//and manipulate it<br>myString.append(&quot; Word&quot;);<br>    <br>System.out.println(myString); // Hello World</pre><p>In fact, those who are not familiar with the topic may be a little surprised. They might say, ‘<strong><em>I can already do this in any variable I want, can’t I?</em></strong>’ Our friends will be able to grasp the underlying logic more clearly when we delve into the details of the topic and the immutable part 🙂</p><p>When a change is made in mutable classes, the change is made on the same field <strong>without creating a new space in memory</strong> (the situation is the opposite in immutables 🙂). In fact, the logic behind mutable classes is that they have a <strong>set()</strong> method that we call a <strong>setter</strong>.</p><p>However, <strong>being changeable</strong> is not always a good thing for us, as it can cause some side effects…</p><p>For example, using mutable classes in threaded operations can sometimes cause problems for us. <strong>When two execution threads try to access and change a mutable value at the same time, a situation may arise where one overrides the other</strong>. Therefore, we should be careful when using mutable classes.</p><p>We mentioned that there are mutable classes that already come with Java. So how would we create our own if we wanted to?</p><p>I’ll try to explain this with a short code.</p><pre>public class MutableClass {<br><br>   private int mutableField1;<br>   private String mutableField2;<br><br>   public MutableClass(int fld1, String fld2) {<br>      this.mutableField1 = fld1;<br>      this.mutableField2 = fld2;<br>   }<br><br>   public int getMutableField1() {<br>      return mutableField1;<br>   }<br><br>   public void setMutableField1(int mutableField1) {<br>      this.mutableField1 = mutableField1;<br>   }<br><br>   public String getMutableField2() {<br>      return mutableField2;<br>   }<br><br>   public void setMutableField2(String mutableField2) {<br>      this.mutableField2 = mutableField2;<br>   }<br>}</pre><p>In this example, we defined the class fields as mutable. Additionally, we created two setter methods, <strong>setMutableField1()</strong> and <strong>setMutableField2()</strong>, for each field to enable us to change their values. This way, <strong>the fields of this class can be modified as desired after the initial use</strong>.</p><p>🌟<strong>In summary</strong>,</p><ul><li>Mutable objects are ones that <strong>can be changed without creating a new object in memory</strong>.</li><li>They have a <strong>setter method</strong> in their class.</li><li>They may cause disadvantages in threaded operations due to <strong>race conditions</strong>.</li></ul><h3>2.Immutable</h3><p>In fact, in this concept, the opposite of the situations explained above is present. <strong>Once an immutable object is initialized, we cannot change its value</strong>. Examples of these objects include <strong>primitive types</strong>, <strong>Wrapper Classes</strong>, <strong>Legacy classes</strong> <a href="https://www.javatpoint.com/legacy-class-in-java">(what!?)</a>, and the <strong>String</strong> class. As an example, readers can refer to my blog post “<a href="https://bayten.dev/posts/string-stringbuilder-and-stringbuffer-in-java/">String, StringBuilder, and StringBuffer in Java</a>” where I discussed the implications of being mutable or immutable for these three classes.</p><p>In immutable classes, unlike mutable classes, only <strong>Getter methods are present</strong>. When a change is desired in these classes, <strong>a new area is created in memory and the manipulated version of the variable is stored in this new area</strong>. This creates <strong>unnecessary memory usage</strong> as a new area is constantly created for each manipulation, making immutable classes slower in terms of performance compared to mutable classes.</p><p>Another difference from mutable classes is that <strong>they are safer in threaded processes since they are immutable and cannot be changed</strong>.</p><p>So, what should we do if we want to create an immutable class? Let’s take a look:</p><ul><li>We can define the class as <strong>final</strong>.</li><li>We can define the variables that will be used in the class as final and assign their initial values through the <strong>constructor method.</strong> Therefore, since these fields are final and have initial values, they will give an error if they are attempted to be changed.</li><li>We do not use the <strong>Setter</strong> method.</li></ul><p>Let’s now show all that has been explained in the code. In fact, let’s try to make the “<strong>MutableClass</strong>” that we created above immutable now.</p><pre>public final class ImmutableClass {<br><br>   private final int immutableField1;<br>   private final String immutableField2;<br><br>   public ImmutableClass(int fld1, String fld2) {<br>      this.immutableField1 = fld1;<br>      this.immutableField2 = fld2;<br>   }<br><br>   public int getImmutableField1() {<br>      return immutableField1;<br>   }<br><br>   public String getImmutableField2() {<br>      return immutableField2;<br>   }<br>}</pre><p>In the code I wrote above, we declared the fields of the class as <strong>final</strong> and assigned <strong>their initial values in the constructor</strong>, making it immutable. Additionally, since we do not have any <strong>setter methods</strong>, the fields of this class cannot be accessed and assigned any value.</p><p>To summarize the whole topic and make a comparative analysis, we can create a table as follows, from start to finish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*m0trud4flUMrQ1_mFicuBA.png" /></figure><p><strong>In conclusion</strong>🌟,</p><p>The use of Mutable and Immutable classes in Java is important for software developers to <strong>improve code quality, minimize errors, and optimize performance</strong>. While the use of Mutable classes can be <strong>advantageous in terms of flexibility and customization, their misuse can lead to program errors</strong>.</p><p>The use of Immutable classes is <strong>ideal for writing safe and shareable code, but in some cases, they may be disadvantaged in terms of performance.</strong> By choosing the right class types according to the needs of the application, programmers can improve code quality and create more secure, scalable, and performant applications.</p><p>If you have taken the time to read this far, thank you very much. If you notice any mistakes, please feel free to contact me via email or comments.</p><p>Happy coding! 🎉</p><p>⭐For the original article -&gt; <a href="https://bayten.dev/posts/mutable-and-immutable-in-java/">https://bayten.dev/posts/mutable-and-immutable-in-java/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a003b754b642" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leetcode | Best Time to Buy and Sell Stock]]></title>
            <link>https://baytendev.medium.com/leetcode-best-time-to-buy-and-sell-stock-da37fa60f7e4?source=rss-75b342b9ae32------2</link>
            <guid isPermaLink="false">https://medium.com/p/da37fa60f7e4</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <dc:creator><![CDATA[Barış Ayten]]></dc:creator>
            <pubDate>Fri, 17 Mar 2023 13:01:32 GMT</pubDate>
            <atom:updated>2023-03-17T13:01:32.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*pxNG2oDk4HrGrleautnD1Q.png" /></figure><h3>Selamlar🖖🏼</h3><p>Bu yazının konusu bir Leetcode sorusu olacak. <strong>Competitive Algorithm</strong> konusuna ayrıca bir önem ve özen göstermeye çalışıyorum. Ne kadar çok proje yapmış ya da ne kadar tecrübeli olsanız da, bu alan sürekli pratik istiyor. Ben de imkan buldukça her gün bir soru çözüp, kendimi olabildiğince diri ve antrenmanlı tutmaya çalışıyorum. Blogumda da çözdüğüm ve hoşuma giden güzel soruların çözüm yollarını ve kodunu açıklamaya çalışacağım.</p><p>Bugünkü sorumuz <a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock/"><strong>Best Time to Buy and Sell Stock</strong></a>. <strong>Google</strong>‘ın mülakat sorularından ve kolay kategorisinde olduğu belirtilmiş.</p><p>Yavaştan soruya geçelim.</p><h3>Soruyu Anlayalım🤔</h3><p>Soruda bize, fiyat bilgilerinin bulunduğu bir integer array dizisi prices veriliyor ve bu dizinin indisi i günü (1. gün, 3.gün gibi…) prices[i] de o günün fiyatını belirtiyor . Sorunun bizden istediği, <strong>fiyatın en düşük olduğu günde alım yapıp, kârımızı maksimum yapabileceğimiz günde satış yapmak ve böylece ulaşılabilecek maksimum kâra ulaşmamız</strong>.</p><h4>Örnek 1</h4><pre>Input    : prices = [7,1,5,3,6,4]<br>Output   : 5<br>Açıklama : Aslında burada yapılan işlem 2.günde 1 birimden alış <br>           yapıp(indisin 1den başladığını düşünüyoruz, sıfırıncı gün yok) <br>           5.günde 6 birimden satıp, 6 - 1 = 5, 5 birimlik kâr elde etmek.</pre><h4>Örnek 2</h4><pre>Input    : prices = [2,8,3,1,12,5]<br>Output   : 11<br>Açıklama : Burada da 4.gün alıp 5.gün satarsak eğer maksimum <br>           11 birimlik kâr elde ederiz.</pre><h4>Örnek 3</h4><pre>Input    : prices = [7,6,4,3,1]<br>Output   : 0<br>Açıklama : Mesela burada da bir türlü kâra geçirecek bir pozisyon <br>           bulunmadıı için alım-satım yapılamıyor dolayısıyla sıfır <br>           döndürülüyor.</pre><h3>Soruya Girişelim🥊</h3><p>Aslında yapmamız gereken şey temelde basit, <strong>alım yaptığın günün fiyatı, satış yaptığın günün fiyatından küçük olsun ki herhangi bir kârdan bahsedebilelim</strong>. Yani kontrol etmemiz gereken durumlardan ilki, <strong>kâr ediyor muyuz?</strong> Tamam, diyelim ki kâr ediyoruz. Fakat bize her kâr lazım değil, <strong>maksimum olanı gerekli</strong>.</p><p>Ve bu kontrolleri de, son güne kadar gerçekleştirmek. Ardından maksimum kârı bulup bunu döndürebiliriz.</p><p>Şimdi bu düşündüklerimizi <strong>pseudo-code</strong> olarak yazalım.</p><pre>1. maxProfit ve localProfit integer değişkenleri oluşturulup sıfıra atanır.<br><br>2. buyDay ve sellDay integer değişkenleri 0 ve 1 olarak atanır.<br><br>3. sellDay, prices dizisinin uzunluğundan küçük olduğu sürece <br>   bir döngü başlatılır.<br><br>    4. Eğer prices[buyDay] &lt; prices[sellDay] ise:<br>        5. localProfit değişkenine prices[sellDay] - prices[buyDay] atanır.<br><br>        6. maxProfit, localProfit ve maxProfit arasındaki maksimum değere atanır.<br><br>    7. Aksi takdirde, buyDay değişkenine sellDay değeri atanır.<br><br>    8. sellDay değiskeni bir artırılır.<br><br>9. Döngü tamamlandığında, maxProfit değişkeni döndürülür.</pre><p>Şimdi buradaki mantığı açıklamaya çalışayım.</p><ul><li>İlk olarak maxProfit ve localProfit adında iki değişken oluşturup, bunlara sıfır atadım. maxProfit bizim asıl sonucumuz olacak, localProfit de kâr ihtimallerini tutan değişkenimiz olacak.</li><li>Sonrasında buyDay ve sellDay adında 0 ve 1 atanmış iki değişkenimiz ile günler üzerinde gezineceğimiz pointer’larımızı tanımladık, yani bir nevi i ve j. sellDay‘i 1 olarak tanımladık çünkü satış günü hep bir sonraki gün olacak.</li><li>Ardından prices dizisinin içinde bir while döngüsü başlatıyoruz. sellDay yani satış gününü temsil eden değişkenimiz son güne ulaşınca döngüyü tamamlamış oluyoruz.</li><li>Döngüye girdiğimizde her iterasyonda prices[sellDay] - prices[buyDay] ile kâr ihtimalimiz var mı kontrol ediyoruz, eğer böyle bir durum varsa da bunu hesaplayıp localProfit‘e atıyoruz. Ardından elimizdeki maxProfit ile karşılaştırıyoruz, hangisi daha büyük? Büyük olanı maxProfit‘e tekrar atıyoruz.</li><li>Eğer kâr ihtimalimiz yok ise buyDay‘i, sellDay‘in olduğu noktaya getiriyoruz. Çünkü kâr ihtimali yok ise oradan alış yapmamıza gerek yok, bu yüzden o değişkeni ileri çekmiş oluyoruz.</li><li>Son olarak da artık sellday‘i bir ileri alıyoruz yeni bir iterasyona geçiş ve yeni kâr hesaplaması için.</li></ul><p>Buraya kadar sorun yoksa asıl koda geçebiliriz.</p><h3>Coding💻</h3><pre>public int maxProfit(int[] prices) {<br>    int maxProfit = 0;<br>    int localProfit = 0;<br><br>    int buyDay = 0;<br>    int sellDay = 1;<br><br>    while (sellDay &lt; prices.length) {<br>        if (prices[buyDay] &lt; prices[sellDay]) {<br>            localProfit = prices[sellDay] - prices[buyDay];<br>            maxProfit = Math.max(maxProfit, localProfit);<br>        }<br>        else <br>            buyDay = sellDay;<br>        sellDay++;<br>    }<br>    return maxProfit;<br>}</pre><p>Kodun <strong>Time Complexity</strong>’sine bakacak olursak da, burada bir while döngüsü kullanarak prices array’inin elemanlarını yani tüm input’u dolaştığımız için <strong>BigO </strong>notasyonumuzun O(n) olduğunu görürüz. Yani yapılan işlem sayısı input’un boyutu n ile doğru orantılıdır diyebiliriz.</p><p>Tabii ki bu problemin birden farklı ve daha efektif çözüm yolları olabilir, benim çözüm yolum bu şekildeydi ve bunu açıklayıcı bir şekilde anlatmak istedim.</p><p>Buraya kadar zaman ayırıp okuduğunuz için teşekkürler,</p><p>Happy Coding🎉</p><p>Makalenin orjinal hali için -&gt; <a href="https://bayten.dev/posts/best-time-to-buy-and-sel-stock/#">https://bayten.dev/posts/best-time-to-buy-and-sel-stock/#</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da37fa60f7e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[String, StringBuilder, and StringBuffer in Java]]></title>
            <link>https://levelup.gitconnected.com/string-stringbuilder-and-stringbuffer-in-java-55d358e2dce6?source=rss-75b342b9ae32------2</link>
            <guid isPermaLink="false">https://medium.com/p/55d358e2dce6</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-development]]></category>
            <dc:creator><![CDATA[Barış Ayten]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 12:18:20 GMT</pubDate>
            <atom:updated>2023-06-15T00:59:03.960Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ZdQG9vqnEbKp8v8w38COZA.png" /></figure><p>Hello!🖖🏼</p><p>This article will be about the <strong>String</strong> class that we frequently use in Java and its alternatives, <strong>StringBuilder</strong> and <strong>StringBuffer</strong>. There may be points that I missed, skipped, or inadvertently conveyed incorrectly. If you give me feedback via email in such a situation, I would be very happy.</p><p>Now, let’s get started 🚀</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FBpGWitbFZflfSUYuZ9%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FBpGWitbFZflfSUYuZ9&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMW9xaXUwaHZxeWY3c2k0azBnY3B5N2ZxNG85OXc3MTl6YjBjYm5iYyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FBpGWitbFZflfSUYuZ9%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="361" frameborder="0" scrolling="no"><a href="https://medium.com/media/10bd0fd3d7da7e925c9cc7ca636352ea/href">https://medium.com/media/10bd0fd3d7da7e925c9cc7ca636352ea/href</a></iframe><h3>1.String</h3><p>First, let’s look at the String class. As we all know, the String class is one of the complex data types in Java that represents character arrays. This class stores an array of characters and provides multiple functions for manipulating these characters. When we want to use it, we define it as shown below and assign a value.</p><pre>String str= &quot;Merhaba&quot;;</pre><p>So far, there is no problem here. However, as we know, in Java, the <strong>String</strong> class is “<strong>immutable</strong>” meaning it cannot be changed. But of course, some of you might say, “<em>Oh no, I have changed and assigned many times and performed the operations I wanted!</em>”</p><p>This is where situations arise that prompted me to write this article.</p><p>In fact, when we manipulate a String variable, the value that the variable points to does not change 🙂. In such an operation, a new space is opened in the Heap, and the manipulated value is placed there, and our reference points to this new address.</p><pre>String str = &quot;Merhaba&quot;;<br>str.conjcat(&quot;Dünya&quot;);</pre><p>When we define as shown above and then perform the “<em>conca</em>t” operation, as mentioned, a new space is created in memory, and our “<em>str</em>” variable now references the address where the “<em>MerhabaDünya</em>” variable is located.</p><p>So, a new space is being constantly opened in memory every time the variable is manipulated. And of course, this is not something we would want because it causes both performance and time loss. 🙂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*LrDKhF20mwT8Vdbo-QO6QQ.png" /><figcaption>The heap representation in memory.</figcaption></figure><p>At this point, the <strong>StringBuilder</strong> class comes to our help.</p><h3>2.StringBuilder</h3><p>The role of <strong>StringBuilder</strong> is also the same as <strong>String</strong>. It represents character strings. However, the difference from String is that it is a “<strong>mutable</strong>” or changeable class. Therefore, it is a better choice than the <strong>String</strong> class for efficient text manipulation.</p><p>For example, if we want to convert all the words in a text file to uppercase, the <strong>StringBuilder</strong> class can easily do this without recreating the entire text in memory (String was creating a new space in memory for this new value).</p><p>Or a very simple example like the one below.</p><pre>StringBuilder sentence = new StringBuilder(&quot;This is a sentence.&quot;);<br>sentence.append(&quot;Added word.&quot;);<br><br>System.out.println(sentence.toString()); //This is a sentence.Added word.</pre><p>However, there is an important drawback to this class that has not yet been mentioned, which is its lack of a thread-safe structure. If a process involving threads is to be used, the <strong>StringBuilder</strong> class is not suitable in this scenario. This limitation can be explained with the following code snippet:</p><pre> StringBuilder sb = new StringBuilder();<br><br>//Thread 1<br> Thread t1 = new Thread(() -&gt; {<br>      for(int i=0; i&lt;10000; i++){<br>          sb.append(&quot;A&quot;);<br>      }<br>  });<br><br>//Thread 2<br> Thread t2 = new Thread(() -&gt; {<br>      for(int i=0; i&lt;10000; i++){<br>          sb.append(&quot;B&quot;);<br>      }<br>  });<br><br>  t1.start();<br>  t2.start();<br><br>  t1.join();<br>  t2.join();<br><br>  System.out.println(sb.toString());</pre><p>In this example, two distinct threads, <strong>t1</strong> and <strong>t2</strong>, access the <strong>StringBuilder</strong> object concurrently and append the characters “A” and “B” 10,000 times each in a sequential manner. However, due to the lack of synchronization in the <strong>StringBuilder</strong> object, the resulting output is indeterminate and can yield varying results on each execution. In essence, a data race condition is introduced.</p><p>To address this issue, we can use the <strong>StringBuffer</strong> class instead.</p><h3>3.StringBuffer</h3><p>I won’t repeat the same information with StringBuffer here, if you have read this far, you can already guess that the only difference of this class is its “thread-safe” or synchronized structure. It has the same methods and logic as StringBuilder.</p><p>However, this great feature also brings some drawbacks. Its synchronized structure causes it to work slower than StringBuilder.</p><p>If we try to explain this with a small code snippet,</p><pre>public class StringBufferVsStringBuilder {<br>  public static void main(String[] args) {<br>      int N = 1000000;<br>      long startTime, endTime, duration;<br><br>      // StringBuffer performance test<br>      StringBuffer buffer = new StringBuffer();<br>      startTime = System.nanoTime();<br>      for (int i = 0; i &lt; N; i++) buffer.append(&quot;hello&quot;);<br>      <br>      endTime = System.nanoTime();<br>      duration = (endTime - startTime);<br>      System.out.println(&quot;Time taken by StringBuffer: &quot; + duration + &quot; nanoseconds&quot;);<br>      //Time taken by StringBuffer: 19494000 nanoseconds<br><br>      // StringBuilder performance test<br>      StringBuilder builder = new StringBuilder();<br>      startTime = System.nanoTime();<br>      for (int i = 0; i &lt; N; i++) builder.append(&quot;hello&quot;);<br>      <br>      endTime = System.nanoTime();<br>      duration = (endTime - startTime);<br>      System.out.println(&quot;Time taken by StringBuilder: &quot; + duration + &quot; nanoseconds&quot;);<br>      //Time taken by StringBuilder: 17145000 nanoseconds<br>  }<br>}</pre><p>This code calculates the elapsed time for <strong>StringBuilder</strong> and <strong>StringBuffer</strong> to append the word “<em>hello</em>” one million times. When we run this code, we can easily observe that <strong>StringBuffer</strong> works slower due to its synchronized structure. We can make this difference more prominent by increasing the value of N.</p><p>As a summary, I am adding the features of both classes in the table below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*YZgkFHP4rB7oVSDvvzF6Lw.png" /></figure><p>Finally,</p><ul><li>There is no harm in using the <strong>String</strong> class, but we should keep in mind that it is immutable, and every time we try to modify it, <strong>a new memory space is created</strong>.</li><li><strong>StringBuilder</strong>, on the other hand, performs all operations without the need for creating new memory spaces, but it may provide incorrect results in thread-containing applications since it does not have a synchronized structure.</li><li>We can solve the problem of <strong>StringBuilder</strong> by using <strong>StringBuffer</strong>, which operates in a synchronized structure, but this class may cause some performance loss compared to <strong>StringBuilder</strong>.</li></ul><p>If you have taken the time to read this far, thank you very much. If you notice any mistakes, please feel free to contact me via email.</p><p>Happy coding! 🎉</p><p>⭐For the original article -&gt; <a href="https://bayten.dev/posts/string-stringbuilder-and-stringbuffer-in-java/">https://bayten.dev/posts/string-stringbuilder-and-stringbuffer-in-java/</a></p><h3>References</h3><ul><li><a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html">https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html</a></li><li><a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringBuffer.html">https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringBuffer.html</a></li><li><a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringBuilder.html">https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/StringBuilder.html</a></li><li><a href="https://www.digitalocean.com/community/tutorials/string-vs-stringbuffer-vs-stringbuilder">https://www.digitalocean.com/community/tutorials/string-vs-stringbuffer-vs-stringbuilder</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55d358e2dce6" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/string-stringbuilder-and-stringbuffer-in-java-55d358e2dce6">String, StringBuilder, and StringBuffer in Java</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Yapay Sinir Ağlarında Aktivasyon Fonksiyonları]]></title>
            <link>https://medium.com/databulls/yapay-sinir-a%C4%9Flar%C4%B1nda-aktivasyon-fonksiyonlar%C4%B1-11002b8ac522?source=rss-75b342b9ae32------2</link>
            <guid isPermaLink="false">https://medium.com/p/11002b8ac522</guid>
            <category><![CDATA[veri-bilimi]]></category>
            <category><![CDATA[databulls]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[derin-ogrenme]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Barış Ayten]]></dc:creator>
            <pubDate>Thu, 18 Mar 2021 10:10:51 GMT</pubDate>
            <atom:updated>2021-04-12T10:37:33.407Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*wAWxs5o9TLQYSAgKR0niiA.png" /></figure><p>Herkese merhaba 🖖,</p><p>Bugün yapay sinir ağ modellerimizde kullandığımız aktivasyon fonksiyonlarını anlatmaya çalışacağım. Ben de aktif olarak Derin Öğrenme algoritmaları üzerine kendimi geliştirmeye çalışıyorum. Bu sırada öğrendiğim ne varsa burada da anlatmaya çalışarak hem pekiştirmeye hem de kaynak oluşturmaya çalışıyorum.</p><p>Yazının akışını şu şekilde planladım;</p><ol><li><strong>Aktivasyon Fonksiyonu Nedir?</strong></li><li><strong>İyi Bir Aktivasyon Fonksiyonunun Özellikleri Nelerdir?</strong></li><li><strong>Aktivasyon Fonksiyonları Çeşitleri</strong></li><li><strong>Hangi Aktivasyon Fonksiyonunu Seçmeliyiz?</strong></li></ol><p>Vakit kaybetmeden başlayalım.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FXyaQAnihoZBU3GmFPl%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fmemecandy-XyaQAnihoZBU3GmFPl&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2FXyaQAnihoZBU3GmFPl%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="242" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f58851710cea6a47648435d633f14d9/href">https://medium.com/media/3f58851710cea6a47648435d633f14d9/href</a></iframe><h3>Aktivasyon Fonksiyonu Nedir?</h3><p>Bu alana uzaktan yakından dokunmuşsanız eğer mutlaka aktivasyon fonksiyonu kavramını duymuşsunuzdur. Peki nedir bu aktivasyon fonksiyonu?</p><p>Eğittiğimiz yapay sinir ağı modeline gerçek dünya verilerini, yani karmaşık verileri öğretebilmek için kullandığımız fonksiyonlardır. Aktivasyon fonksiyonu olmayan bir yapay sinir ağı, verilerdeki kompleks yapıları öğrenip tespit etmekte çok zorlanacaktır hatta çoğu zaman da yetersiz kalacaktır. Aktivasyon fonksiyonu içermeyen bir yapay sinir ağı, basit bir lineer regresyon modelinden farksız olacaktır.</p><p>Bu yüzden elimizdeki yapay sinir ağının güçlü olmasını, karmaşık verilerden isabetli sonuçlar çıkarmasını istiyorsak bir aktivasyon fonksiyonu kullanmamız gerekli.</p><h3><strong>İyi Bir Aktivasyon Fonksiyonunun Özellikleri Nelerdir?</strong></h3><p>Peki iyi bir aktivasyon fonksiyonu nasıl olmalıdır? Zorunlu olmamakla beraber bunun için birden fazla kıstas mevcut. Bunlardan bazıları şunlar;</p><ul><li><strong>Doğrusal olmamalı</strong></li></ul><blockquote>Doğrusal aktivasyon fonksiyonları ile oluşturulmuş Yapay Sinir Ağları genel olarak tek katmanlı yapay sinir ağları gibi davranır. Yani karmaşık problemlerin çözümünde iyi bir performans sergilemez.</blockquote><ul><li><strong>Türevlenebilir olmalı</strong></li></ul><blockquote>Türev bizim her şeyimiz. Biliyoruz ki yapay sinir ağ eğitiminde minimum kayıp(<strong>Loss</strong>) değerini veren parametleri biz geri yayılım algoritması <strong>(Back Propagation</strong>) ile belirliyoruz. Eğer türevlenebilir olmazsa, <strong>Back Propagation da</strong> olmaz, yani belki de mükemmel modeli kuracak parametleri hiçbir zaman öğrenemeyiz.</blockquote><ul><li><strong>Alt ve üst sınıra sahip olmalı</strong></li></ul><blockquote>Sınırları olmayan bir aktivasyon fonksiyonunda bazı durumlarda sonuç alamama durumları ortaya çıkabilir.</blockquote><ul><li><strong>Monoton artan veya azalan olmalı</strong></li></ul><blockquote>Aktivasyon fonksiyonun monoton artan ve azalan olması, minimum ve maksimum noktasının bulunmasını garantiler.</blockquote><ul><li><strong>Orjin noktasında kendine yakınsamalı</strong></li></ul><blockquote>Bir aktivasyon fonksiyonunun orjin noktasında kendine yakınsaması, rastgele ağırlık değerleriyle başlatılmış bir modelin eğitimini kolaylaştırır.</blockquote><p>Güzel, iyi bir aktivasyon fonksiyonunun özelliklerinden de bahsettiğimize göre şimdi çok sık kullanılan aktivasyon fonksiyonlarını inceleyelim.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl2JhORT5IFnj6ioko%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Ffocusworld-focus-world-in-a-valley-of-violence-l2JhORT5IFnj6ioko&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fl2JhORT5IFnj6ioko%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="179" frameborder="0" scrolling="no"><a href="https://medium.com/media/64a8e5d841f450620af72db610d2b115/href">https://medium.com/media/64a8e5d841f450620af72db610d2b115/href</a></iframe><h3>Aktivasyon Foksiyonları Çeşitleri</h3><p><a href="https://medium.com/databulls/come-write-with-us-as-a-dataprofessional-or-enthusiast-771a641c4a48">Come Write With Us as a “DataProfessional” or “Enthusiast”</a></p><h3><strong>1. Binary Step Function</strong></h3><p>İlk bahsedeceğimiz fonksiyon <strong>Binary Step Function</strong>. Bu fonksiyon ikili sınıflandırma durumunda kullanılır. Çoklu sınıflandırmada işe yaramaz. Genellikle çıkış katmanlarında (<strong>Output Layer</strong>) kullanılır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*4xQA_FqacHTEdAxUx6ebsg.png" /><figcaption>Binary Step Fonksiyonu Grafiği</figcaption></figure><p>Türevi sıfır olduğu için de <strong>Geri Yayılım</strong>(Back Propagation) sırasında parametreler güncellenmez yani öğrenme işlemi gerçekleşmez. Bu yüzden de <strong>Gizli Katmanlarda</strong>(Hidden Layers) tercih edilmez.</p><h3>2. Linear Function</h3><p>Bir diğer fonksiyonumuz <strong>Lineer Fonksiyon</strong>. Fakat yukarıda bahsettiğimiz sorunlar burada da devam ediyor. Model optimizasyonu sırasında, türevi sabit bir değere eşit olacağı için öğrenme işlemi burada da sınıfta kalacaktır. Bu yüzden bu fonksiyon çok basit görevler dışında kullanılması tercih edilmez.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*KTHcVawMdjl-AtICZuKNcQ.png" /><figcaption>Lineer Fonksiyon Grafiği</figcaption></figure><h3>3. Sigmoid Function</h3><p>En çok kullanılan aktivasyon fonksiyonlarından birisidir. Şimdiye kadar bahsettiğimiz ilk <strong>doğrusal olmayan(non-linear) </strong>fonksiyondur. Karar vermeye yönelik olasılıksal bir yaklaşımdır ve değer aralığı [0,1] arasındadır. Yani çıktının hangi sınıfa ait olduğuna dair olasılıksal bir değer verir bize. Ve iyi haber, Sigmoid fonksiyonu sürekli yani türevlenebilir bir fonksiyon olduğundan öğrenme işlemi gerçekleşir.</p><pre>g(x) = 1/(1+e^(-x))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*FXyC5UElEGMGy3Z39qEKhg.png" /><figcaption>Sigmoid Fonksiyon Grafiği</figcaption></figure><p>Fakat Sigmoid de mükemmel değildir. Çünkü türev değeri, tablodan da görebildiğimiz üzere, uç noktalarda sıfıra yakınsar (<strong>Vanishing Gradient)</strong>.Bu durum <strong>Back Propagation</strong> sırasında öğrenmenin durmasına sebebiyet verir . Bu sebeple <strong>çok katmanlı ağlarda</strong> kullanılması tavsiye edilmez.</p><h3>4. Hiperbolik Tanjant (tanh)</h3><p><strong>Sigmoid</strong> fonksiyonu ile oldukça benzerdir. Bu fonksiyon da ikili sınıflandırma için kullanılır. Fakat <strong>tanh</strong> [-1,1] değer aralığında değerler alır ve orjin etrafında simetriktir.</p><pre>tanh(x) = 2sigmoid(2x)-1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*Oyjt-jtKv2LehdlGR3Zhlg.png" /><figcaption>Hiperbolik Tanjant Fonksiyonu Grafiği</figcaption></figure><p>Grafikten gördüğümüz üzere, uç noktalarda türev sıfıra yakınsar. Yani <strong>tanh</strong> fonksiyonu da <strong>Vanishing Gradient</strong> probleminden muzdariptir. Model kurulacağı zaman katman sayısı dikkate alınmalıdır, çok katmanlı ağlarda tercih edilmemelidir.</p><h3>5. Rectified Linear Unit (ReLU)</h3><p>Bir diğer fonksiyonumuz <strong>Rectifier Linear Unit</strong>. Genellikle <strong>Convolutional Neural Network (CNN)</strong>’te ve ara katmanlarda çok sık kullanılan <strong>ReLU</strong> fonksiyonunun ana avantajı aynı anda tüm nöronları aktive etmemesidir. Yani bir nöron negatif değer üretirse, aktive edilmeyeceği anlamına gelir.</p><p>Tablodan da görebileceğimiz üzere negatif değerler üreten nöronlar sıfır değerini alır. Bu durum, <strong>ReLU</strong>’nun <strong>Hiperbolik Tanjant</strong> ve <strong>Sigmoid </strong>fonksiyonundan daha verimli ve hızlı çalışmasını sağlar. Bu nedenle <strong>ReLU</strong>, çok katmanlı sinir ağlarında daha çok tercih edilir.</p><pre>                   x if x&gt;= 0<br>g(x) = max(0,x) =<br>                   0 if x&lt;0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*abqja-rrroNvUkRUto2EIw.png" /><figcaption>ReLU Grafiği</figcaption></figure><p><strong>ReLU</strong>’nun türevi sıfıra yakınsamadığı için önceki fonksiyonlarda gördüğümüz <strong>Vanishing Gradient</strong> probleminden etkilenmez. Fakat <strong>ReLU</strong> da mükemmel değildir.</p><p>Grafiğe baktığımızda, fonksiyonun türevinin negatif değerlerde sıfır olduğunu görürüz. Daha önceki fonksiyonlarda da bahsettiğimiz gibi bu durum <strong>Geri Yayılım (Back Propagation)</strong> esnasında parametrelerimizin güncellenmeyeceği, yani öğrenme işleminin olmayacağı anlamına gelir. Bu probleme <strong><em>Dying ReLU</em></strong> adı verilir.</p><p>Bu durumun üstesinden gelebilmek için <strong>ReLU</strong>’nun bazı varyasyonları geliştirilmiş.</p><ul><li><strong>Leaky ReLU</strong></li><li><strong>Parameterized ReLU</strong></li><li><strong>Exponential ReLU</strong></li></ul><p>Şimdi biraz da bunları inceleyelim.</p><h4>5.1. Leaky ReLU</h4><p><strong>Dying ReLU</strong> problemine karşı geliştirilen çözümlerden biri <strong>Leaky</strong> yani <strong>Sızıntı ReLU</strong>. Grafikten de görebileceğiniz gibi <strong>Leaky ReLU</strong>’da negatif değerler sıfıra çok yakındır fakat tam sıfır değildir. Böylece türevinin sıfır olması engellenmiş olur. Bu durum <strong>Back Propagation</strong> esnasında öğrenmenin negatif tarafta da gerçekleşeceği anlamına gelir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*mhq13od_2l-duyhBQBPRhQ.png" /><figcaption>Leaky ReLU ve Türevi</figcaption></figure><h4>5.2 Parameterized ReLU</h4><p><strong>Leaky ReLU</strong> gibi <strong>Dying ReLU</strong> problemi için geliştirilmiş bir başka varyasyondur. Türevi de aynı <strong>Leaky ReLU</strong> gibidir fakat tek fark 0.01 değeri yerine sabit başka bir “a” değeri kullanılır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*FjTDE9cKVX9RE9hTcwb0Bw.png" /><figcaption>PReLU</figcaption></figure><h4>5.3 Exponential Linear Unit</h4><p>Önceki varyasyonlardan farkı negatif tarafta eğimli bir yapıya sahiptir. Önceki varyasyonlarda hala <strong>Dying ReLU</strong> probleminden dolayı bir sıkıntı yaşanıyorsa, bu aktivasyon fonksiyonu denenebilir.</p><pre>        x          ,   x&gt;=0<br>f(x) = <br>        a(e^(x-1)) ,   x&lt;0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*1CZ_1MxD_GKB6fUuXgsZhw.png" /><figcaption>EReLU Grafiği (<a href="https://medium.com/@danqing/a-practical-guide-to-relu-b83ca804f1f7">Kaynak</a>)</figcaption></figure><h4>3.6 Swish</h4><p>Bir diğer aktivasyon fonksiyonumuz da <strong>Google</strong> tarafından geliştirilen <strong>Swish</strong>. Bu fonksiyon <strong>ReLU</strong> gibi efektif ve hatta ondan daha iyi performans gösterebilmekte. <strong>ReLU</strong>’dan en önemli farkı negatif bölgede de yer alıyor olması. Daha derin katmanlı sinir ağlarında tercih edilebilir.</p><pre>f(x) = x*sigmoid(x)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*sOm7UCQS1humoSSpIKra-A.png" /><figcaption>Swish Fonksiyonu (<a href="https://lazyprogrammer.me/wp-content/uploads/2017/10/Screen-Shot-2017-10-18-at-2.39.55-PM.png">Kaynak</a>)</figcaption></figure><p>Grafikten de görüldüğü üzere her noktada türevli ve bu durum model optimizasyon sırasında <strong>ReLU</strong>’dan daha iyi olması demek.</p><p>Fakat <strong>Swish</strong>’in de bir sorunu var. Mesela monoton olmaması gibi. Görüldüğü gibi, <strong>Swish</strong> fonksiyonunun çıktısı, girdinin arttığı zamanlarda düşüşe geçebiliyor.</p><h4>3.7 Softmax</h4><p>Bahsedeceğimiz son aktivasyon fonksiyonu ise <strong>Softmax</strong>. Çoğu zaman çoklu Sigmoid olarak da bilinen bu fonksiyon, çok sınıflı hedef değişkeni içeren sınıflandırma problemleri (multi-class classification) için uygun bir aktivasyon fonksiyonudur. <strong>Softmax</strong>, çıktı olarak her sınıfa ait olasılık sonucu döndürür. Yani <strong>Softmax</strong> ile bir sinir ağı kuruyorsanız, çıktı katmanınızda hedef değişkeniniz kadar nöron olması gerekli. Ne demek istedim? Diyelim ki 3 sınıflı bir tahmin yapıyorsanız, [0.2,0.88,0.45] gibi her bir sınıfa ait olasılığı sonuç olarak döndürür.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*zeSY7-SQdJxoVRHoLdsVYQ.png" /><figcaption>(<a href="https://www.analyticsvidhya.com/blog/2020/01/fundamentals-deep-learning-activation-functions-when-to-use-them/">Kaynak</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*OdbQ43p317RnK1YHJmywig.png" /><figcaption><a href="https://towardsdatascience.com/softmax-activation-function-explained-a7e1bc3ad60">kaynak</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*TPOHi9igDRSaTN1SfwC2OA.png" /><figcaption>Softmax Grafiği</figcaption></figure><h3>Hangi Aktivasyon Fonksiyonunu Seçmeliyiz?</h3><p>İyisiyle kötüsüyle birden fazla aktivasyon fonksiyonu gördük. Peki hangisini, ne zaman kullanmam gerektiğini nasıl bileceğim?</p><p>Aslında bu soru için kesin bir yanıt yok. Herbir fonksiyonun avantajları ve dezavantajları var. Burada iş geçmiş tecrübelere kalıyor.Fakat bazı maddeleri sıralayabiliriz…</p><ul><li>Eğer çok katmanlı bir sinir ağınız varsa, <strong>Vanishing Gradients</strong> probleminden dolayı <strong>Tanh</strong> ve <strong>Sigmoid</strong>’ten kaçınmak yararlı olacaktır.</li><li>Hız bakımından avantajlı olduğu için <strong>ReLU</strong> ile başlamak mantıklı olabilir, yani en azından denenebilir.</li><li>Fakat <strong>ReLU</strong> kullanırken “<strong>Dying ReLU</strong>” problemi baş gösterecektir. Bu problemden kaçınmak için yukarıda bahsettiğim üç farklı varyasyon olan <strong>Leaky, Parameterized, Exponential ReLU</strong> sıkıntınıza çözüm olabilir.</li><li>Eğer çoklu tahmin yapıyorsanız, çıkış katmanınızda <strong>Softmax</strong> ihtiyacınız olan aktivasyon fonksiyonu olabilir.</li></ul><p>Bu yazıda anlatacaklarım buraya kadardı. Buraya kadar zaman ayırıp okuduğunuz için teşekkür ederim. Bu konunun uzmanı olmadığım gibi elbette hatalarım da olabilir. Düzeltmeyi, kaynak belirterek yorumlarda yaparsanız çok memnun olurum, böylece bilgi kirliliğinin önüne geçmiş oluruz.</p><p>İyi çalışmalar dilerim🤙</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3oKIPf3C7HqqYBVcCk%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Freactionseditor-3oKIPf3C7HqqYBVcCk&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZ3RmcHJrN3Z0bjdnNGJ0Y2hqbmE3NGxkZmJtc3NteGNzZXozYWhzeSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3oKIPf3C7HqqYBVcCk%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/8632cc9818be738c255b9ee333a13cea/href">https://medium.com/media/8632cc9818be738c255b9ee333a13cea/href</a></iframe><ul><li><a href="https://medium.com/databulls/open-banking-724f8835b1b">Open Banking</a></li><li><a href="https://medium.com/databulls/open-banking-ii-psd2-7e8f67a6e290">Open Banking II — PSD2</a></li></ul><h4>Referanslar</h4><ul><li>Ding, B., Qian, H., &amp; Zhou, J. (2018). Activation Functions and Their Characteristics in Deep Neural Networks. <em>2018 Chinese Control And Decision Conference (CCDC)</em>. <a href="https://doi.org/10.1109/ccdc.2018.8407425">https://doi.org/10.1109/ccdc.2018.8407425</a></li><li><em>Fundamentals of deep learning — Activation functions and when to use them?</em> (2020, July 19). Analytics Vidhya. <a href="https://www.analyticsvidhya.com/blog/2020/01/fundamentals-deep-learning-activation-functions-when-to-use-them/">https://www.analyticsvidhya.com/blog/2020/01/fundamentals-deep-learning-activation-functions-when-to-use-them/</a></li><li>Jain, V. (2019, December 30). <em>Everything You Need to Know About “Activation functions” in Deep Learning Models</em>. Medium. <a href="https://towardsdatascience.com/everything-you-need-to-know-about-activation-functions-in-deep-learning-models-84ba9f82c253">https://towardsdatascience.com/everything-you-need-to-know-about-activation-functions-in-deep-learning-models-84ba9f82c253</a></li><li>Kumawat, D. (2019, August 22). <em>7 types of activation functions in neural network</em>. Analytics Steps | Learn AI, Machine Learning, Business Analytics, Startups &amp; other Technologies. <a href="https://www.analyticssteps.com/blogs/7-types-activation-functions-neural-network">https://www.analyticssteps.com/blogs/7-types-activation-functions-neural-network</a></li><li>Kızrak, A. (2020, January 7). <em>Derin Öğrenme için Aktivasyon Fonksiyonlarının Karşılaştırılması</em>. Medium. <a href="https://ayyucekizrak.medium.com/derin-%C3%B6%C4%9Frenme-i%C3%A7in-aktivasyon-fonksiyonlar%C4%B1n%C4%B1n-kar%C5%9F%C4%B1la%C5%9Ft%C4%B1r%C4%B1lmas%C4%B1-cee17fd1d9cd">https://ayyucekizrak.medium.com/derin-%C3%B6%C4%9Frenme-i%C3%A7in-aktivasyon-fonksiyonlar%C4%B1n%C4%B1n-kar%C5%9F%C4%B1la%C5%9Ft%C4%B1r%C4%B1lmas%C4%B1-cee17fd1d9cd</a></li><li>Liu, D. (2017, November 30). <em>A Practical Guide to ReLU</em>. Medium. <a href="https://medium.com/@danqing/a-practical-guide-to-relu-b83ca804f1f7">https://medium.com/@danqing/a-practical-guide-to-relu-b83ca804f1f7</a></li><li><em>A Quick Introduction to Artificial Neural Networks (Part 2)</em>. (n.d.). Kris Bolton. <a href="https://krisbolton.com/a-quick-introduction-to-artificial-neural-networks-part-2">https://krisbolton.com/a-quick-introduction-to-artificial-neural-networks-part-2</a></li></ul><p><a href="https://www.linkedin.com/in/alibaris/?originalSubdomain=tr">Ali Barış Ayten - City 29-0-1 Province, İzmir Province, Turkey | Professional Profile | LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11002b8ac522" width="1" height="1" alt=""><hr><p><a href="https://medium.com/databulls/yapay-sinir-a%C4%9Flar%C4%B1nda-aktivasyon-fonksiyonlar%C4%B1-11002b8ac522">Yapay Sinir Ağlarında Aktivasyon Fonksiyonları</a> was originally published in <a href="https://medium.com/databulls">DataBulls</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Activation Functions in Deep Neural Network]]></title>
            <link>https://medium.datadriveninvestor.com/activation-functions-in-deep-neural-network-4d8849b70046?source=rss-75b342b9ae32------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d8849b70046</guid>
            <category><![CDATA[activation-functions]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Barış Ayten]]></dc:creator>
            <pubDate>Thu, 18 Mar 2021 09:58:40 GMT</pubDate>
            <atom:updated>2021-04-11T19:45:53.199Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*kkXBp_LORDSEfT9TwgVwKQ.png" /></figure><p>Hello everyone 🖖,</p><p>Today I will try to explain the activation functions which we use in our artificial neural network models. I am also currently trying to improve myself on Deep Learning algorithms. In the meantime, I will try to explain everything that I have learned here and try to create a source.</p><p>I planned the flow of the article as follows;</p><ol><li><strong>What is the Activation Function?</strong></li><li><strong>What are the characteristics of a good Activation Function?</strong></li><li><strong>Types of Activation Functions</strong></li><li><strong>Which Activation Function should we choose?</strong></li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F64aBXTVfd90zyUH2da%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fabcnetwork-start-the-rookie-lets-begin-64aBXTVfd90zyUH2da&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2F64aBXTVfd90zyUH2da%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/4434863b8678a29e3d929f6b4a901170/href">https://medium.com/media/4434863b8678a29e3d929f6b4a901170/href</a></iframe><h3>1.What Is the Activation Function?</h3><p>If you have touched this area from a distance, you must have heard of the concept of the Activation Function. So what is the Activation <br>Function?</p><p>They are the functions that we use to teach complex real-world data to the artificial neural network model we have trained. An artificial neural network that does not contain activation functions will have difficulties in learning the complex structures in the data, and will often be inadequate. In simple terms, an artificial neural network that does not contain an activation function will be no different than a simple linear regression model.</p><p>Therefore, if we want the artificial neural network to be strong and to draw accurate conclusions from complex data, we need to use an activation function.</p><h3>2.<strong>What are the characteristics of a good Activation Function?</strong></h3><p>So how should a good activation function be? Although it is not mandatory, there is more than one criterion for this. Some of these are;</p><ul><li><strong>Should not be linear</strong></li></ul><p>Artificial Neural Networks built with linear activation functions generally act as single-layer artificial neural networks. So it does not perform well in solving complex problems.</p><ul><li><strong>Should be derivable</strong></li></ul><p>The derivative is our everything. We know that in artificial neural network training, we determine the parameters that give the minimum <strong>Loss </strong>value with <strong>Back Propagation</strong>. If it is not differentiable, there will be no <strong>Back Propagation</strong>, so maybe we will never learn the parameters that will build the perfect model.</p><ul><li><strong>Should have a lower and upper limit</strong></li></ul><p>In some cases, ineffective situations may arise in an unlimited activation function.</p><ul><li><strong>Should be monotonic</strong></li></ul><p>The monotonous increasing and decreasing activation function ensure that the minimum and maximum point is found.</p><ul><li><strong>Convergence to itself at the point of origin</strong></li></ul><p>The convergence of an activation function to itself at the point of origin makes it easy to train a model initiated with random weight values.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl0HlA8usIM1odkjlK%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fsouthparkgifs-l0HlA8usIM1odkjlK&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fl0HlA8usIM1odkjlK%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd8d560fdb009f11c78d301fae627a1e/href">https://medium.com/media/cd8d560fdb009f11c78d301fae627a1e/href</a></iframe><p>Now that we have mentioned the features of a good activation function, let’s examine the most frequently used activation functions.</p><h3>3.<strong>Types of Activation Functions</strong></h3><h4>3.1 Binary Step Function</h4><p>The first function we’ll talk about is Binary Step Function. This function is used in the case of binary classification. It will not work with multiple classifications. Usually used in output layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*4xQA_FqacHTEdAxUx6ebsg.png" /></figure><p>Since the derivative value is zero, the parameters are not updated during Back-Propagation, so there is no learning process. Therefore, it is not preferred in Hidden Layers.</p><h4>3.2 Linear Function</h4><p>Our other function is Linear Function. But the problems we mentioned above continue here as well. During model optimization, the learning process will also be troublesome here as its derivative will be equal to a constant value. Therefore, it is not preferred to use this function except for very simple tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*KTHcVawMdjl-AtICZuKNcQ.png" /></figure><h4>3.3 Sigmoid Function</h4><p>It is one of the most used activation functions. It is the first non-linear function we’ve talked about so far. It is a probabilistic approach to decision making and the range of values is between [0,1]. It gives us a probabilistic value of which class the output belongs to. And the good news is because the Sigmoid function is a <strong>continuous, differentiable function</strong>, the learning process occurs.</p><pre>g(x) = 1/(1+e^(-x))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*FXyC5UElEGMGy3Z39qEKhg.png" /><figcaption>The graph of Sigmoid</figcaption></figure><p>But Sigmoid isn’t perfect either. Because the derivative value, as we can see from the table, converges to zero at the extremes. This problem is called <strong>Vanishing Gradients. </strong>This situation causes learning to stop during Back Propagation. For this reason, it is not recommended for use in multi-layer networks.</p><h4>3.4 Hyperbolic Tangent (tanh)</h4><p>It is quite similar to the Sigmoid function. This function is also used for binary classification. But tanh takes values in the range of [-1,1] and is symmetrical around the origin.</p><pre>tanh(x) = 2sigmoid(2x)-1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*Oyjt-jtKv2LehdlGR3Zhlg.png" /><figcaption>The graph of tanh</figcaption></figure><p>As we can see from the graph, the derivative of tanh converges to zero at the extreme points. So the tanh function also suffers from the Vanishing Gradient problem.</p><p>The number of layers should be taken into account when the model is to be installed, it should not be preferred in multi-layer networks.</p><h4>3.5 Rectified Linear Unit (ReLU)</h4><p>Our other function is the Rectifier Linear Unit. The main advantage of the ReLU function, which is often used in Convolutional Neural Network (CNN) and intermediate layers, is that it does not activate all neurons at the same time. So if a neuron gives a negative value as output, it means it will not be activated.</p><pre>                   x if x&gt;= 0<br>g(x) = max(0,x) =<br>                   0 if x&lt;0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*abqja-rrroNvUkRUto2EIw.png" /><figcaption>The graph of ReLU</figcaption></figure><p>As we can see from the table, neurons that produce negative values take the value zero. This allows ReLU to work more efficiently and faster than the Hyperbolic Tangent and Sigmoid function. For this reason, ReLU is more preferred in multilayer neural networks.</p><p>Since the derivative of ReLU does not converge to zero, it is not affected by the Vanishing Gradient problem we saw in previous functions. But ReLU isn’t perfect either.</p><p>When we look at the graph, we see that the derivative of the function is zero at negative values. As we mentioned in the previous functions, this means that our parameters will not be updated during Back-Propagation, which means there will be no learning process. This problem is called Dying ReLU.</p><p>Some variations of ReLU have been developed to overcome this situation.</p><ul><li><strong>Leaky ReLU</strong></li><li><strong>Parameterized ReLU</strong></li><li><strong>Exponential ReLU</strong></li></ul><p>Let’s look at them a little bit now.</p><h4>3.5.1 Leaky ReLU</h4><p>One of the solutions developed against the Dying ReLU problem is Leaky ReLU. As you can see from the graph, negative values in Leaky ReLU are very close to zero, but not exactly zero. Thus, its derivative is prevented from being zero. This means that learning during Back Propagation will also take place on the negative side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*mhq13od_2l-duyhBQBPRhQ.png" /><figcaption>The graph of Leaky ReLU</figcaption></figure><h4>3.5.2 Parameterized ReLU</h4><p>It is another variation developed for the Dying ReLU problem like Leaky ReLU. Its derivative is the same as Leaky ReLU, but the only difference is that instead of 0.01, another fixed value of “a” is used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*FjTDE9cKVX9RE9hTcwb0Bw.png" /><figcaption>The graph of PReLU</figcaption></figure><h4>3.5.3 Exponential Linear Unit</h4><p>Its difference from previous variations is that it has a slope on the negative side. This activation function can be tried if the previous variations are still experiencing difficulties due to the Dying ReLU problem.</p><pre>        x          if  x&gt;=0<br>f(x) = <br>        a(e^(x-1)) if  x&lt;0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*1CZ_1MxD_GKB6fUuXgsZhw.png" /><figcaption>The graph of EReLU (<a href="https://medium.com/@danqing/a-practical-guide-to-relu-b83ca804f1f7">source</a>)</figcaption></figure><h4>3.6 Swish</h4><p>Another of our activation functions is Swish, developed by Google. This function can perform effectively and even better than ReLU. The most important difference from ReLU is that it is also located in the negative zone. It can be preferred in deeper layered neural networks.</p><pre>f(x) = x*sigmoid(x)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*sOm7UCQS1humoSSpIKra-A.png" /><figcaption>The graph of Swish(<a href="https://lazyprogrammer.me/wp-content/uploads/2017/10/Screen-Shot-2017-10-18-at-2.39.55-PM.png">source</a>)</figcaption></figure><p>As can be seen from the graph, it is different at every point and this means that the model is better than ReLU during optimization.</p><p>But Swish also has a problem. Like it is not monotonous. As you can see from the graph, the output of the Swish function may decline when the input increases.</p><h4>3.7 Softmax</h4><p>The last activation function we will talk about is Softmax. Often known as the Multiple Sigmoid, this function is a suitable function for classification problems involving a multi-class target variable.</p><p>Softmax returns the probability result of each class as output. So if you are building a neural network with Softmax, you need to have as many neurons as your target variable in your output layer.</p><p>What did I mean? Let’s say you are making a 3-class prediction, it returns the probability of each class, such as [0.2,0.88,0.45], as a result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*zeSY7-SQdJxoVRHoLdsVYQ.png" /><figcaption>The formula of Swish (<a href="https://www.analyticsvidhya.com/blog/2020/01/fundamentals-deep-learning-activation-functions-when-to-use-them/">source</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*OdbQ43p317RnK1YHJmywig.png" /><figcaption>Example output (<a href="https://towardsdatascience.com/softmax-activation-function-explained-a7e1bc3ad60">source</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*TPOHi9igDRSaTN1SfwC2OA.png" /><figcaption>The graph of Softmax</figcaption></figure><h3><strong>4. Which Activation Function Should We Choose?</strong></h3><p>We’ve seen more than one activation function. So how do I know which one to use and when?</p><p>Actually, there is no definitive answer to this question. Each function has advantages and disadvantages. But we can list some stuff…</p><ul><li>If you have a multi-layer neural network, it would be useful to avoid <strong>Tanh </strong>and <strong>Sigmoid</strong> due to the <strong>Vanishing Gradients</strong> problem.</li><li>It might make sense to start with ReLU as it is advantageous in terms of speed.</li><li>But when using <strong>ReLU</strong>, the “<strong>Dying ReLU</strong>” problem will arise. To avoid this problem, the three different variations I mentioned above, <strong>Leaky, Parameterized, Exponential ReLU</strong>, can be the solution to your problem.</li><li>If you are making multi-class predictions, <strong>Softmax</strong> may be the activation function you need in your output layer.</li></ul><p>Here is what I will tell in this article. Thank you for taking your time and reading so far.</p><p>As I am not an expert on this subject, of course, I may have mistakes. I would be very glad if you make the correction in the comments by specifying the reference so that we will avoid information pollution.</p><p>Have a good day 🤙</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl49FqlUguNsGDNCGk%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Foskouioskoui-lotr-gifscapade-l49FqlUguNsGDNCGk&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fl49FqlUguNsGDNCGk%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/c26f82b11123c52db05fdc39c61cac0b/href">https://medium.com/media/c26f82b11123c52db05fdc39c61cac0b/href</a></iframe><h3>References</h3><ul><li>Ding, B., Qian, H., &amp; Zhou, J. (2018). Activation Functions and Their Characteristics in Deep Neural Networks. <em>2018 Chinese Control And Decision Conference (CCDC)</em>. <a href="https://doi.org/10.1109/ccdc.2018.8407425">https://doi.org/10.1109/ccdc.2018.8407425</a></li><li><em>Fundamentals of deep learning — Activation functions and when to use them?</em> (2020, July 19). Analytics Vidhya. <a href="https://www.analyticsvidhya.com/blog/2020/01/fundamentals-deep-learning-activation-functions-when-to-use-them/">https://www.analyticsvidhya.com/blog/2020/01/fundamentals-deep-learning-activation-functions-when-to-use-them/</a></li><li>Jain, V. (2019, December 30). <em>Everything You Need to Know About “Activation functions” in Deep Learning Models</em>. Medium. <a href="https://towardsdatascience.com/everything-you-need-to-know-about-activation-functions-in-deep-learning-models-84ba9f82c253">https://towardsdatascience.com/everything-you-need-to-know-about-activation-functions-in-deep-learning-models-84ba9f82c253</a></li><li>Kumawat, D. (2019, August 22). <em>7 types of activation functions in neural network</em>. Analytics Steps | Learn AI, Machine Learning, Business Analytics, Startups &amp; other Technologies. <a href="https://www.analyticssteps.com/blogs/7-types-activation-functions-neural-network">https://www.analyticssteps.com/blogs/7-types-activation-functions-neural-network</a></li><li>Liu, D. (2017, November 30). <em>A Practical Guide to ReLU</em>. Medium. <a href="https://medium.com/@danqing/a-practical-guide-to-relu-b83ca804f1f7">https://medium.com/@danqing/a-practical-guide-to-relu-b83ca804f1f7</a></li><li><em>A Quick Introduction to Artificial Neural Networks (Part 2)</em>. (n.d.). Kris Bolton. <a href="https://krisbolton.com/a-quick-introduction-to-artificial-neural-networks-part-2">https://krisbolton.com/a-quick-introduction-to-artificial-neural-networks-part-2</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d8849b70046" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/activation-functions-in-deep-neural-network-4d8849b70046">Activation Functions in Deep Neural Network</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>