Wednesday, June 9, 2021

Java Tutorial: Class

Chapters

Java Class

Class is one of the cornerstones of java and it defines the state and behavior of objects. Class is the blueprint/template of an object and object is an instance of class or class instance. Class defines a new data type. Using class, we can create our own object type that we can use to strengthen and enhance our program. Basically, classes is comprised of methods, instance and variables or fields, These are called class members. Class also has constructor. A constructor is a special class member that instantiate(create) a class instance(object). Let's look at this example:
public class SampleClass{
 //fields or instance variables
 public int field1;
 public String field2;
 public double field3;
 
 //constructor
 public SampleClass(){}
 
 //method
 public void classMethod(){
 }
}
A top-level class is a class that is on the very top of other classes and it's not nested to another class. In the example above, SampleClass is a top-level class because it's the very first class to be defined and not nested to any class.

Once we created a class, we can instantiate it by using the new keyword and access its members. Instantiation is a way to create an object(class instance) out of a class.
public class SampleClass{
 //fields or instance variables
 public int field1;
 public String field2;
 public double field3;
 
 //constructor
 public SampleClass(){
   System.out.println("Initializing object using constructor.");
 }
 
 //method
 public void classMethod(){
  System.out.println("SampleClass Method");
 }
 
 public static void main(String[]args){
   SampleClass sc = new SampleClass();
   System.out.println("field1: " + sc.field1);
   sc.classMethod();
 }
}

Result
Initializing object using constructor
field1: 0
SampleClass Method
Take a look at this code:
SampleClass sc = new SampleClass();
We use the new keyword to call a constructor of a class and the constructor creates an object(class instance) out of the class. If we assign class instantiation to a variable with the same type as the class, then once the object is created, its reference of address will be passed to the variable. Thus, we can use that reference to access the created object and its content(members).

If we don't define a constructor in a class, java will implicitly create a constructor with zero parameters. Take a look at this example.
public class SampleClass{
  
  void method(){
    System.out.println("Hello!");
  }
  
  public static void main(String[] args){
    SampleClass sc = new SampleClass();
    sc.method();
  }
}

Result
Hello!
As you can see from the example above, a constructor with zero parameters can be invoked even we didn't define one in our source code.

Take note that if we explicitly create a constructor with parameters or not, java won't implicitly create a constructor with zero parameters. Take a look at this example.
public class SampleClass{
  
  SampleClass(String msg){
    System.out.println(msg);
  }
  
  public static void main(String[] args){
    //will throw an exception
    SampleClass sc = new SampleClass();
  }
}


Depending on access modifier, Some class members can't be accessed.
public class SampleClass{

 public static void main(String[]args){
   Message msg = new Message();
   msg.createMessage();
   msg.sayHi();
 }
}

class Message{
 
 public void sayHi(){
   System.out.println("Hi!");
 }
 
 private void createMessage(){
   System.out.println("Message");
 }
}
This code will throw a compile-time error. methods,variables,etc. that have private access-modifier are only allowed to be accessed in class definition.

Differences Between Constructor and Method

1.) Constructor's task is to instantiate class whereas method's task depends on programmer's implementation.

2.) Constructor doesn't have return type whereas method does.Despite the fact that constructors don't have return type, they still return a value and that value is the reference or address of class instance.

3.)Constructor name must be the same to its class name whereas method name is defined by programmers.

Anonymous Object

Anonymous object is an object that is not assigned to any variable. Anonymous object is short lived.
public class SampleClass{
  
  void message(){
    System.out.println("SampleClass");
  }
  
  public static void main(String[]args){
    new SampleClass().message();
  }
}

The this Keyword

We use the this keyword to refer to a class instance where the keyword is used.
Example

public class SampleClass{

  public static void main(String[]args){
     MyClass mc = new MyClass();
 
     if(mc.getInstance() instanceof MyClass)
       System.out.println("mc is instance of MyClass");
  }
}

class MyClass{

  public MyClass getInstance(){
   System.out.println("Returning MyClass Instance...");
   return this;
  }
}

Result
Returning MyClass instance...
mc is instance of MyClass
We can also use the this keyword to access class instance members and resolve member hiding. Member hiding or shadowing is a phenomenon where local variables,parameters and instance variables have the same name which causes instance variables to be hidden by local variables and parameters.
public class SampleClass{

  public static void main(String[]args){
     MyClass mc = new MyClass();
     mc.setNum(4);
     
     System.out.println("num value: " + mc.getNum());
  }
}

class MyClass{
  private int num;
  
  public void setNum(int num){
    this.num = num;
  }
  
  public int getNum(){ return num; }
}

Result
num value: 4
This code worked fine. Now, remove the this keyword.
 
public void setNum(int num){
  num = num;
}

Result
num value: 0
The value is 0 because the parameter "num" of setNum() hid the "num" instance variable of MyClass. Thus, parameter "num" assigned the value of 4 to itself. To resolve member hiding, we can name instance,local variables and parameters differently to avoid equivalent names or we can use the this keyword.

Using the this keyword is preferrable to solving member hiding. Thinking of unique names is hard especially when building big applications. Though, there are times that naming variables is preferrable. Take a look at this code.
public class SampleClass{
  int num = 10;
  
  void checkDivisibility(int divisible){
    final int num = 5;
    
    class Divisible{
      int num = 20;
      
      void divisibility(){
        if(this.num % divisible == 0)
         System.out.println(this.num + " is "+
                            "divisible by " + divisible);
                            
        if(SampleClass.this.num % divisible == 0)
         System.out.println(SampleClass.this.num + " is "+
                            "divisible by " + divisible);
                            
        if(num % divisible == 0)
         System.out.println(num + " is "+
                            "divisible by " + divisible);
      }
      
    }
    
    new Divisible().divisibility();
  }
  
  public static void main(String[]args){
    new SampleClass().checkDivisibility(5);
  }
}

Result:
20 is divisible by 5
10 is divisible by 5
20 is divisible by 5
As you can see, num in Divisible clas has been accessed two times. To access the local variable num in checkDivisibility() method it's better to change its name. Divisible class in checkDivisibility() method is a local class.

The super Keyword

This topic requires an understanding of inheritance. We can use the super keyword to access visible super class members like constructors, instance variables, etc. Visibility of class members depends on their access modifiers. Let's look at this example.
public class SampleClass{

  public static void main(String[]args){
    Message msg = new Message("Hello!");
    
    msg.sayMessage();
  }
}

class Text{
  private String characters;
  
  Text(String characters){
    this.characters = characters;
  }
  
  String getChars(){ return characters; }
}

class Message extends Text{
  
  Message(String chars){
    super(chars);
  }
  
  public String getChars(){
   String chars = super.getChars();
   
   if(chars.length() > 10)
     return "Too much characters!";
     
   return chars;
  }
  
  public void sayMessage(){
    System.out.println("Message: " + getChars());
  }
}
We can achieve constructor chaining using super keyword and we can access hidden members of super class. Take note that hidden and visible are different, hidden members are visible to a class but some members of the class get in front of them whereas visibility refers to accessibility of members to a class.
public class SampleClass{

  public static void main(String[]args){
    ClassTwo ct = new ClassTwo();
    
    ct.showNum();
  }
}

class ClassOne{
  int num = 1;

}

class ClassTwo extends ClassOne{
  int num = 2;
  
  public void showNum(){
    System.out.println("num in ClassOne: " + super.num);
    System.out.println("num in ClassTwo: " + num);
  }
}

Result
num in ClassOne: 1
num in ClassTwo: 2
This code above is an example of hidden members. As you can see, num in ClassOne is accessible but we need to use super to access it because num in ClassTwo is in front of num in ClassOne. Next, let's look at this example.
public class SampleClass{

  public static void main(String[]args){
    ClassTwo ct = new ClassTwo();
    
    ct.showNum();
  }
}

class ClassOne{
  private int num = 1;

}

class ClassTwo extends ClassOne{
  int num = 2;
  
  public void showNum(){
    System.out.println("num in ClassOne: " + super.num);
    System.out.println("num in ClassTwo: " + num);
  }
}
This code above will throw a compile-time error due to visibility of num in ClassOne. num in ClassOne is not visible to ClassTwo because it has private access modifier. This is an example of visibility.

Constructor Overloading

Constructors can't be overriden but they can be overloaded.
public class SampleClass{

 public static void main(String[]args){
   MessageCreator mc = new MessageCreator();
   mc.sayHi();
   mc.sayBye();
   mc = new MessageCreator("Hi! How are you?","See you later!");
   mc.sayHi();
   mc.sayBye();
 }
}

class MessageCreator{
 private String hi;
 private String bye;
 
 MessageCreator(){
  hi = "Hi!";
  bye = "Bye!";
 }
 
 MessageCreator(String hi,String bye){
   this.hi = hi;
   this.bye = bye;
 }
 
 void sayHi(){
   System.out.println(hi);
 }
 
 void sayBye(){
   System.out.println(bye);
 }
 
}

Result
Hi!
Bye!
Hi! How are you?
See you later!
Like method overloading. Overloaded constructor can't be identical. Their parameters must not be the same.
The this keyword refers to the class in which the keyword is used. In the example above, this keyword refers to SampleClass class. this keyword can resolve member hiding.
Try removing the this keyword in the example above and the result is going to be:
Hi!
Bye!
null
null
When we instantiate SampleClass using the constructor with parameters, the hi and bye parameters assign their values to themselves. It happens because the hi and bye instance variables are not visible in the scope of the constructor with parameters due to identical names between the constructor's parameters and SampleClass instance variables.

Constructor Chaining

The process of calling one constructor from another is called constructor chaining. There are two ways to do constructor chaining: chaining within the same class and chaining using inheritance. Let's try the first method.
public class SampleClass{

  public static void main(String[]args){
    Square sq = new Square(50f,150f,75f,75f);
  }
}

class Square{
 private float posX;
 private float posY;
 private float width;
 private float height;
 
 public Square(float posX, float posY, float width, float height){
   this(posX,posY);
   
   this.width = width;
   this.height = height;
   
   System.out.println("size is set: ");
   System.out.println("Width: " + this.width);
   System.out.println("Height: " + this.height);
 }
 
 private Square(float posX, float posY){
   this.posX = posX;
   this.posY = posY;
   
   System.out.println("Positions are set: ");
   System.out.println("Position X: " + this.posX);
   System.out.println("Position Y: " + this.posY);
 }

}
One of the usage of constructor chaining is to reduce the numbers of statements of some constructors and distribute the other statements in other constructors to make our code more readable. In the example above, I put statements that are related to Square's position in the Square() contructor with two parameters. Then, I put statements that are related to Square's size in the Square() constructor with four parameters. Constructors can be chained in any order.

There are rules that we need to follow when implementing constructor chaining within class:
1.) this statement must be the first statement in constructor.
2.) There must be one constructor in a chain that doesn't have this statement.
Java will throw compile-time errors if we don't follow the rules above.

Next, let's try the second method of constructor chaining. This method requires an understanding of inheritance.

import java.awt.geom.Point2D;

public class SampleClass{

  public static void main(String[]args){
    Point2D[] points = {new Point2D.Float(50f,100f), 
                        new Point2D.Float(100f,100f),
                        new Point2D.Float(100f,150f),
                        new Point2D.Float(50f,150f) };
    Rectangle rec = new Rectangle(points);
  }
}

class Shape{
  private String name;
  
  Shape(String name){
    this.name = name;
    System.out.println("Shape name is set.");
    System.out.println("Shape name is: " + name);
  }
}

class Polygon extends Shape{
  private Point2D[] nPoints;
  
  Polygon(String name,Point2D nPoints[]){
    super(name);
    this.nPoints = nPoints;
    
    System.out.println("Points are set.");
  }
  
}

class Rectangle extends Polygon{
 
 public Rectangle(Point2D[] p){
   super("Rectangle",p);
   System.out.println("Rectangle is set and ready to use!");
 }

}
super statement can call any constructors of a super class as long as those constructors are visible. The visibility of constructors or any class members depend on their access modifiers.

Point2D is a pre-defined abstract class in java that holds x and y coordinates. Point2D.float is a static nested class of Point2D.

Note: this and super statement can't exist at the same time in a constructor. These two need to be the first statement in the constructor.

Initializer Block

We can use initializer or init block as an alternative to constructor. Unlike constructors, init block can't take any parameters and they are initialized before constructors are initialized. Though, initializing variable using assignment operator comes first before the initializer block.
public class SampleClass{
  int num;
  
  //correct way of initializing variable
  //in class block using assignment operator
  String name = "SampleClass";
  //can't do this assignment directly in class
  //or interface block
  //name = sample //compile-time error
  
  double decimal;
  
  //init block
  {
    System.out.println("name: " + name);
    System.out.println("initializing init block");
    num = 2;
    decimal = 3.5;
  }
  
  public SampleClass(){
    System.out.println("initializing constructor");
  }
  
  public void showValues(){
    System.out.println(num);
    System.out.println(name);
    System.out.println(decimal);
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    
    sc.showValues();
  }
}
Everytime we create an instance of a class, init block will be automatically initialized.We can have multiple initializer blocks and place them anywhere in the class block.
public class SampleClass{
  int num;
  String name;
  double decimal;
  
  //init block1
  {
    System.out.println("initializing init block1");
    num = 2;
    name = "SampleClass";
  }
  
  public SampleClass(){
    System.out.println("initializing constructor");
  }
  
  public void showValues(){
    System.out.println(num);
    System.out.println(name);
    System.out.println(decimal);
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    
    sc.showValues();
  }
  
  //init block2
  {
    System.out.println("initializing init block2");
    decimal = 3.5;
  }
}
We can use multiple blocks if we wanna reduce an amount of statements of some blocks and distribute the other statements to other blocks. Java evaluates initializer blocks from top to botoom of a class. We put the initializer block that we wanna be evaluated first at the top of a class. Try putting init block2 on top of init block1 and init block2 will be initialized first before init block1.

Static Block

We can use static block to initialize static members of a class. This block is like the initializer block but for static class members.
public class SampleClass{
  static int num;
  static String name;
  static double decimal;
  
  static{
    System.out.println("Initializing static block1");
    num = 3;
    name = "SampleClass";
  }
  
  static{
    System.out.println("Initializing static block2");
    decimal = 3.5f;
  }
  
  public static void main(String[]args){
    System.out.println("num: " + SampleClass.num);
    System.out.println("name: " + SampleClass.name);
    System.out.println("decimal: " + SampleClass.decimal);
  }
}
Just like init block, we can use multiple static blocks to reduce an amount of statements of some static blocks and distribute those statatements to other static blocks. Java also evaluates static blocks from top to bottom of a class. static blocks are initialized once the class is loaded to JVM.

You might suggest to make a class constructor static instead of using static block. The thing is, we can't make a constructor static. It's not allowed in java to have static constructors. Take a look at this example:
public class SampleClass{

  static SampleClass(){
  }
}
This code will throw a compile-time error. You might wonder why it's not allowed to have a static constructor. You need to have an understanding of inheritance and static keyword to understand the answer. Alright, the answer is simple.

1.) static class members belong to the class itself. The thing is, constructor initializes class instance and if we make the constructor static then we can't create a class instance because class instance has non-static components.

2.) static constructor may break inheritance concept. We know that we can call a constructor of a parent class by using the super keyword. If a constructor can be static then the call to static constructor is erroneous because class instance has non-static components and static constructor, like static block, isn't allowed to access those non-static components which leads to a broken class instance. thus, breaking inheritance.

Abstract Class

You need to have an understanding of inheritance and method overriding to understand this topic. Abstract class is a class that can't be instantiated. a class that has abstract keyword in its class definition is an abstract class. Abstract class can have abstract methods and abstract class preferrable use is to be a parent(super) class.
public class SampleClass{

  public static void main(String[]args){
    Car car = new Car();
    car.engineStart();
    car.engineStop();
  }
}

class Car extends Engine{

  @Override
  public void engineStart(){
    System.out.println("Engine is starting...");
    System.out.println("Engine has started.");
  }
  
  @Override
  public void engineStop(){
    System.out.println("Engine is stopping...");
    System.out.println("Engine has stopped.");
  }
}

//abstract class
abstract class Engine{
  abstract void engineStart();
  abstract void engineStop();
}
In the example above, Car class extended Engine class which is an abstract class. Abstract class and interface can achieve abstraction. Abstract class can still have regular(concrete) methods, fields and constructor.
public class SampleClass{

  public static void main(String[]args){
    Car car = new Car();
    car.engineStart();
    car.engineStop();
    System.out.println(car.getEngineName());
  }
}

class Car extends Engine{
  
  Car(Sring name){
    super(name);
  }
  
  @Override
  public void engineStart(){
    System.out.println("Engine is starting...");
    System.out.println("Engine has started.");
  }
  
  @Override
  public void engineStop(){
    System.out.println("Engine is stopping...");
    System.out.println("Engine has stopped.");
  }
}

//abstract class
abstract class Engine{
  private String engineName;
  
  Engine(){
    engineName = "default";
  }
  
  Engine(String engineName){
    this.engineName = engineName;
  }
  
  abstract void engineStart();
  abstract void engineStop();
  public String getEngineName(){ return engineName; }
}
Even though Engine class can have constructors, Those constructors can only be used by the subclass of the Engine class which is the Car class. Due to the fact that abstract class can have regular(concrete) methods, abstract class can achieve partial abstraction.

In the example above, Engine class achieved partial abstraction. In the first example before the example above, Engine class achieved full abstraction because it only has abstract methods.

Abstract class can extend another abstract class.
import java.awt.geom.Point2D;

public class SampleClass{

  public static void main(String[]args){
   Point2D[] p = {new Point2D.Float(100f,150f),
                  new Point2D.Float(150f,50f),
                  new Point2D.Float(200f,150f)};
                  
   Triangle tri = null;
   if(p.length == 3)
     tri = new Triangle(p);
   else System.out.println("Number of points doesn't"
                           +" represent a triangle");
  }
}

abstract class Shape{

 protected abstract void initShape();
 abstract void translate();
 abstract void rotate();
}

abstract class Polygon extends Shape{
  protected Point2D[] nPoints;
  
  Polygon(){
    initShape();
  }
  
  @Override
  protected void initShape(){
   System.out.println("Initializing Shape...");
  }
  
  protected abstract void initPolygon(Point2D[] nPoints);
  
  //Empty implementations
  @Override
  void translate(){}
  void rotate(){}
}

class Triangle extends Polygon{
  
  Triangle(Point2D[] nPoints){
    System.out.println("Initializing Triangle's components...");
    initPolygon(nPoints);
    System.out.println("Initializing Triangle...");
    System.out.println("Triangle is initialized and ready to use!");
  }
  
  @Override
  protected void initPolygon(Point2D[] nPoints){
    this.nPoints = nPoints;
    System.out.println("Initializing Polygon with " + 
                       nPoints.length
                       +"points");
  }
  
  @Override
  void translate(){
   System.out.println("Translating triangle...");
   System.out.println("Translation Complete!");
  }
}
One of the good things about extending an abstract class to another abstract class is that, we can override abstract methods of a parent abstract class in its abstract sub class with empty implementation and then optionally override those abstract methods in their concrete subclass.

In the example above, Polygon overrides Shape's translate() and rotate() abstract methods then the Triangle class can optionally override translate() or rotate() if needed. Try removing the empty implementation of rotate() from Polygon class and the compiler will throw an error which is requiring to override rotate() in Polygon or Triangle class.

Nested Class

Reference: The Java™ Tutorials
Nested class is a class that is defined inside a class block. Nested class is divided into two types: non-static nested class which is also called inner class and static nested class which is also called static nested class.

Inner Class

Inner class is a non-static class that is nested in another class.
public class SampleClass{
  
  public static void main(String[]args){
  
    Message msg = new Message();
    System.out.println("Is there a message? " + msg.messageExist());
    
    Message.MessageReceiver mr = msg.new MessageReceiver();
    Message.MessageSender ms = msg.new MessageSender();
    mr.receive("Hello Everybody!");
    System.out.println("Is there a message? " + msg.messageExist());
    System.out.println("Here's the message: " + ms.send());
  }
}

class Message{
  private String rawMsg;
  
  private String filteredMessage(){
    String msg = null;
    
    if(!rawMsg.equals("bad"))
      msg = rawMsg;
    else msg = "Message can't"+
               " be displayed.";
    return msg;
  }
  
  public boolean messageExist(){
  
    if(rawMsg != null) return true;
    else return false;
    
  }
  
  class MessageSender{
    
    String send(){
      String msg = null;
      
      if(rawMsg != null){
        msg = filteredMessage();
        rawMsg = null;
      }
      else
       msg = "No message received.";
       
      return msg;
    }
  }
  
  class MessageReceiver{
    
    void receive(String rawMsg){
      System.out.println("Receiving message...");
      Message.this.rawMsg = rawMsg;
      System.out.println("Message received!");
    }
  }
}
There are lots of interesting things going on in the example above. Take a look at these codes:
Message msg = new Message();
Message.MessageReceiver mr = msg.new MessageReceiver();
Message.MessageSender ms = msg.new MessageSender();

First, we need to instantiate Message class then we can instantiate its inner classes like MessageReceiver and MessageSender. First, we need to declare a variable with the inner class type, to do that we need to write the outer class name, in this case is the Message class then use dot and then write the inner class name and then the variable name.

To instantiate an inner class, we need to call its constructor. To do that write the reference of the instance of outer class, In this case, msg holds the reference instance of Message class which is the outer class of the inner classes. Then, call the inner class constructor. We can also see in the example that inner classes can have access to outer class members regardless of access-modifier.

Take a look at this another interesting syntax:
Message.this.rawMsg = rawMsg;
I already explained member hiding or shadowing in the this keyword topic. In the receive() method, rawMsg in receive() and rawMsg in Message class have the same name, Thus, shadowing occurs. For class methods and constructor we resolve shadowing by writing this expression: this.field-name.

When it comes to inner class enclosing scope or block, we need to include the outer class name first before writing the this keyword and the field name. Try removing the outer class name in this statement: Message.this.rawMsg = rawMsg; in the example above and you will encounter a "cannot find symbol" error. That error indicates that rawMsg can't be found in MessageReceiver() class.

Inner class can't have static members because inner classes are associated with class instance.
public class SampleClass{

  class InnerOne{
    //compile-time error
    static int num;
  }
}
If you look at the directory where you compiled the example above, you will see these generated .class files:
Message$MessageReceiver.class
Message$MessageSender.class
These files are the inner classes that we defined in the example above. Java strongly discouraged the serialization of inner, local and anonymous classes because those classes create synthetic constructs: constructs that don't correspond to the source code construct.
This is the code construct of MessageReceiver inner class that has been decompiled.
class MessageReceiver
{
    MessageReceiver(final Message this$0) {
        this.this$0 = this$0;
    }
    
    void receive(final String rawMsg) {
        System.out.println("Receiving message...");
        this.this$0.rawMsg = rawMsg;
        System.out.println("Message received!");
    }
}
As you can see, the code construct is kinda unusual.

This is the code construct of MessageReceiver static nested class that has been decompiled.
static class MessageReceiver
{
    void receive(final Message message, final String rawMsg) {
        System.out.println("Receiving message...");
        message.rawMsg = rawMsg;
        System.out.println("Message received!");
    }
}
As you can see, Static nested class code construct is pretty normal.

Static Nested Class

Static nested class is a static class that is nested in another class.
public class SampleClass{
  
  public static void main(String[]args){
  
    Message msg = new Message();
    System.out.println("Is there a message? " + msg.messageExist());
    
    Message.MessageReceiver mr = new Message.MessageReceiver();
    Message.MessageSender ms = new Message.MessageSender();
    mr.receive(msg,"Hello Everybody!");
    System.out.println("Is there a message? " + msg.messageExist());
    System.out.println("Here's the message: " + ms.send(msg));
  }
}

class Message{
  String rawMsg;
  
  private String filteredMessage(){
    String msg = null;
    
    if(!rawMsg.equals("bad"))
      msg = rawMsg;
    else msg = "Message can't"+
               " be displayed.";
    return msg;
  }
  
  public boolean messageExist(){
  
    if(rawMsg != null) return true;
    else return false;
    
  }
  
  static class MessageSender{
    
    String send(Message message){
      String msg = null;
      
      //static inner class can't directly access
      //non-static members of outer class
      //This syntax will cause error
      //msg = rawMsg; 
      
      if(message.rawMsg != null){
        msg = message.filteredMessage();
        message.rawMsg = null;
      }
      else
       msg = "No message received.";
       
      return msg;
    }
  }
  
  static class MessageReceiver{
    
    void receive(Message message,String rawMsg){
      System.out.println("Receiving message...");
      message.rawMsg = rawMsg;
      System.out.println("Message received!");
    }
  }
}
This example is similar to the inner class example with slight changes. Take a look at this comment first:
//static inner class can't directly access
//non-static members of outer class
//This syntax will cause error
//msg = rawMsg;
Static nested class can't directly access non-static members of outer class, as the comment says. Though, it can indirectly access non-static members (public or non-public) of its outer class by using the reference of its outer class. That's why I changed the send() and receive() parameters and include the instance reference of Message class.

Static nested class behaves like outer class even though they're nested in an outer class.Its behavior is one of the reasons why it can't access non-static members of its outer class. Static nested classes are nested in an outer class for package convinience.



We can also instantiate an outer class in a nested class or a nested class in another nested class.
public class SampleClass{
  
  void message(){
    System.out.println("SampleClass");
  }
  
  private class InnerOne{
    SampleClass sc = new SampleClass();
   
    void message(){
      System.out.println("InnerOne");
    }
  }
  
  class InnerTwo{
    InnerOne io = new InnerOne();
    
    InnerTwo(){
      io.sc.message();
      io.message();
      message();
    }
    
    void message(){
      System.out.println("InnerTwo");
    }
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    SampleClass.InnerTwo it = sc.new InnerTwo();
    
  }
}

Local Class

Reference: The Java™ Tutorials
Local class is a class that is defined in a block like method block. Remember, When a non-static class is nested in a top-level(outer) class then that class is an inner class. If it's nested in a block like method block then that class is a local class.
public class SampleClass{
  int num = 10;
  
  void checkDivisibility(int divisible){
    final int number = 5;
    //effectively-final variable is a variable
    //that is initialized once and never change
    //since.
    // Valid in JDK 8 and later
    int numbers = 25;
    
    //uncomment this statement and an error will occur
    //due to the state change of numbers from effectively-final
    //to not final variable
    // Valid in JDK 8 and later
    //numbers = 35;
    
    class Divisible{
      int num = 20;
      
      void divisibility(){
        if(num % divisible == 0)
         System.out.println(num + " is "+
                            "divisible by " + divisible);
                            
        if(SampleClass.this.num % divisible == 0)
         System.out.println(SampleClass.this.num + " is "+
                            "divisible by " + divisible);
                            
        if(number % divisible == 0)
         System.out.println(number + " is "+
                            "divisible by " + divisible);
                            
        if(numbers % divisible == 0)
         System.out.println(numbers + " is "+
                            "divisible by " + divisible);
      }
      
    }
    
    new Divisible().divisibility();
  }
  
  public static void main(String[]args){
    new SampleClass().checkDivisibility(5);
  }
}
As we can see from the example above. Local class can access the members of its enclosing class, local variables, parameters and of course, its own members.Local class captures local variables and parameters of an enclosing block when accessing them. Those captures are known as captured variables. Local variables must be final or effectively-final in order to be accessed by the local class. Try uncommenting this statement: numbers = 35; and you will encounter an error regarding the effectively-final.

Local class is similar to inner class. Just like inner class, local class has shadowing(member hiding) effect. In the example above, num in Divisible class hides num in SampleClass. The shadowing effect in the example above can be solved by using this keyword. Also, local class can't have static initializers or member interfaces. Though, local class can have static members but they must be constants.
public class SampleClass{

  void method(){
  
    class Local{
     static final int num = 5;
    }
  }
}
Remove the final keyword in the constant variable declaration and the compiler will throw a compile-time error.

Anonymous Class

Reference: The Java™ Tutorials
This topic requires an understanding of interface and local class. Anonymous class is the way of defining class in a form of expression. It has similarities to local class and it doesn't have a name. Take a look at this example.
interface Divisible{

  void divisibility();
}

public class SampleClass{
  int num = 10;
  
  void checkDivisibility(int divisible){
    final int number = 5;
    //effectively-final variable is a variable
    //that is initialized once and never change
    //since.
    // Valid in JDK 8 and later
    int numbers = 25;
    
    //uncomment this statement and an error will occur
    //due to the state change of numbers from effectively-final
    //to not final variable
    // Valid in JDK 8 and later
    //numbers = 35;
    
    //Anonymous Class
    Divisible d = new Divisible(){
      int num = 20;
      
      @Override
      public void divisibility(){
        if(num % divisible == 0)
         System.out.println(num + " is "+
                            "divisible by " + divisible);
                            
        if(SampleClass.this.num % divisible == 0)
         System.out.println(SampleClass.this.num + " is "+
                            "divisible by " + divisible);
                            
        if(number % divisible == 0)
         System.out.println(number + " is "+
                            "divisible by " + divisible);
                            
        if(numbers % divisible == 0)
         System.out.println(numbers + " is "+
                            "divisible by " + divisible);
      }
      
    };
    d.divisibility();
  }
  
  public static void main(String[]args){
    new SampleClass().checkDivisibility(5);
  }
}
You might ask: "Why we can instantiate Divisible interface? Interface can't be instantiated right?".
In this example, we didn't instantiate Divisible interface but we instantiated an "anonymous class" that implicitly implements Divisible interface.

Just like local class, anonymous class can acess members of its enclosing class, local variable that is final or effectively-final and method parameters.

Anonymous class also has shadowing effect. Local class and anonymous class have the same restrictions. We can add fields, extra methods, instance initializers but constructor is not allowed and local classes in anonymous class block.

Anonymous class is very much used in java. Most of the time, they're used in conjunction with interface. Here are some excerpts.
Example #1

Thread thread = new Thread(new Runnable(){

  @Override
  public void run(){
   System.out.println("Thread is running");
  }
});

Example #2

addActionListener(new ActionListener(){

  @Override
  public void actionPerformed(ActionEvent e){
    System.out.println("Button Pressed.");
  }
});
The syntax of anonymous class is confusing sometimes but we can break it down to understand it better. Let's start by not putting codes in anonymous class block.
addActionListener(new ActionListener(){//put codes here} );
Then combine the right brace with the right parenthesis, make space and put codes in the block.
addActionListener(new ActionListener(){

  @Override
  public void actionPerformed(ActionEvent e){
    System.out.println("Button Pressed.");
  }
  
});

Saturday, June 5, 2021

Java Tutorial: Methods

Chapters

Java Methods

Method(or method definition) is a block element in java that groups a collection of statements to perform a specific task. Java offers a myriad of pre-defined methods some of them are the print(),println(),etc. Although, we can't always rely on pre-defined methods, thus we need to create our own method to suit our needs.
General Form:
access-modifier return-type method-name(parameters)
{//code to execute}

Example:

public class SampleClass{

  public void displayMessage(String txt1){
    System.out.println("The message is: " + txt1);
  }
  
 public static void main(String[]args){
   SampleClass sc = new SampleClass();
   sc.displayMessage("I like programming!");
 }
}

Result:
The message is: I like programming!
Method definition must be a member of a class or interface. Method definition can only be nested in class or interface block. Now let's examine the form of java's method definition.

access-modifier: This part specifies the method's accessibility to other classes. There are different types of access modifiers and we're gonna stick with the "public" modifier for now. "public" modifier grants access to all classes that are part of our project.

return-type: Methods can return a value based on the type of this "return-type" once the program encounters the "return" keyword. In the example above the return type is void. void return type means that the method doesn't return any value.We will learn more about return types later.

method-name name of the method. Refer to this link:Java Naming Convention to folow naming convention.

parameters: These are variables that hold the imported values from the outside part of the method call. You can put multiple parameters in the parentheses by using comma to separate them.

Method Call

Methods have two forms: Method Definition and Method Call. We know method definition, let's discuss method call.
General Form: class-reference.method-name(arguments);

class-reference: Reference of a class that owns a method. In the method example above, we call displayMessage() method in the SampleClass class like this:
sc.displayMessage("I like programming!");
"sc" is the variable name that holds the reference of the instance of SampleClass. If a class is static and we wanna call one of its methods, we call it like this:
MyStaticClass.displayMessage("Message");
There are multiple ways to call a method like System.out.println() but for now, let's stick with the class instance.

method-name: name of the method that is defined in the method definition. In the method example above, I defined a method and named it "displayMessage". Then, I used its name as part of the method call in order to specifically call that method.

arguments: values that we wanna include when the program starts processing the method call. Number,type and order of arguments must match the number,type and order of parameters. In the method example above, displayMessage() has one parameter which is a String type. When I called displayMessage() I only put one argument which is also a String type.

Methods can be called in method definition block, constructor block, etc. We can't directly call methods in class or interface blocks.
Example 

public class SampleClass{

 public void myMethod(){
   System.out.println("My Method");
 }
 
 //error
 myMethod();
}

Return type and The return Keyword

Methods can return any value of any type. There's one special kind of return type and that is the "void" keyword. void is a special return type that returns nothing. Normally, method definition requires the return keyword.
In the example in chapter 1, we didn't put any return keyword in the method definition that's because we use void as the return type. Method definition with a "return-type" except for void needs to use the return keyword.

Though, we can still use the return keyword even a method definition has void return type.
Example:

public class SampleClass{

  public void displayMessage(String txt1){
    if(txt1.equals("bad")){
       System.out.println("Message can't be displayed.");
       return;
    }
    System.out.println("The message is: " + txt1);
  }
  
 public static void main(String[]args){
   SampleClass sc = new SampleClass();
   sc.displayMessage("bad");
   System.out.println("Done");
 }
}

Result:
Message can't be displayed.
Done
Remove the return keyword and the result is going to be:
Message can't be displayed.
The message is: bad
Done

return keyword makes the program to exit out of the method call and return the execution to the method caller. Lets review the example above. In most java application, program execution starts at the main method, once the main method encounters the method call, main method will give the execution to the method call.

Then, the execution encounters the return keyword in the method call, thus the execution exits out of the method call and return to the main method which is the method where displayMessage() is called. Then, the program will continue to execute codes next to the method call in the main method.

Now, let's try a different return type
Example:

public class SampleClass{

  public String removeSpaces(String txt1){
    return txt1.replace(" ","");
  }
  
 public static void main(String[]args){
   SampleClass sc = new SampleClass();
   String noSpaceTxt = sc.removeSpaces("I do not need space");
   System.out.println(noSpaceTxt);
 }
}

Result:
Idonotneedspace
In the example above, the return keyword has a value next to it which is a method that returns a String value. replace is a method in the String class. The first argument is the character to be replaced and the second argument is the character that replaces the character in the first argument.

So, let's breakdown the example above. First, The execution starts at the main() method then SampleClass is instantiated, then the program assigns a value to noSpaceText but the value that is to be assigned is a value that is to be returned by removeSpaces() method.

So, the main() method gives the execution to removeSpaces() then the execution encounters the return keyword and ready to return to the main() but before the execution returns to main() it needs to bring a value and that value is the value that is to be returned by the replace() method.

So, removeSpaces() gives the execution to replace().Once the execution is done with replace()(or it encounters the return keyword) it returns back to removeSpaces() with the value it needed and once the execution is done with removeSpaces() it returns back to the main() with the value it needed and then that value is assigned to noSpaceTxt then noSpaceTxt passes a copy of its value to println() and println() displays the value on the command prompt(or terminal).

As you can see, program execution took a long journey just to print a message on the command prompt(or terminal). I didn't breakdown its full journey in the println() and replace() method.

If the example above confuses you, let me give you an easier one.
Example:

public class SampleClass{

  public String goodOrBad(String txt1){
    String result = null;
    
    switch(txt1){
    
     case "good":
     result = "The word is good.";
     break;
    
     case "bad":
     result = "The word is bad.";
     break;
     
     default:
     result = "No Match!";
     break;
    
    }
    
    return result;
  }
  
 public static void main(String[]args){
   SampleClass sc = new SampleClass();
   System.out.println(sc.goodOrBad("good"));
 }
}

Result:
The word is good.
In the above example, I used the return keyword once. Don't use the return keyword too much 'cause using the return keyword too much may lead us to a bad code design.
Example:

public String goodOrBad(String txt1){
    
    switch(txt1){
    
     case "good":
     return "The word is good.";
    
     case "bad":
     return "The word is bad.";
     
     default:
     return "No Match!";
    
    }
  }
This syntax is legal but it's a bad code design 'cause of too much use of return keyword. In complex method definition, too much use of return keyword can make your method definition unreadable. If possible, only use one return keyword as an exit point.

When placing return keyword in an if statement, we still need to put another return keyword in the method block.
Example:

public String checkStr(String txt1){
  
  if(txt1.equals("String"))
    return txt1;
    
  return null;
}
Try removing the return outside if statement and you will encounter a compile-time error. The error happens because if the if statement fails then the return inside that if statement won't be executed and now the execution is stuck in the method call because it can't find an exit point. Let's try changing the return type to void.
Example:

public void checkStr(String txt1){
  
  if(txt1.equals("String")){
    System.out.println(txt1);
    return;
  }
    
}
This code doesn't throw any compile-time error because the return type is void. Unlilke other return types, the compiler doesn't expect a return keyword from method definition with void return type.

When placing return keyword in if-else statement both statements should have an exit point.
Example:

public String checkStr(String txt1){
  
  if(txt1.equals("String"))
    return txt1;
  else return "Not String";
}
For if-else-if, it's better to use one return type.
public String checkStr(String txt1){
  String result = null;
  
  if(txt1.equals("small"))
    result = "small string";
  else if(txt1.equals("medium"))
    result = "medium string";
  else if(txt1.equals("large"))
    result = "large string";
  
  return result;
}
We can't put codes next to return keyword. If we do, we will encounter an "unreachable" error
public void myMethod(){
  return;
  System.out.println("myMethod");
}
This code will throw "unreachable" error. Java can't execute codes next to return keyword. When the execution encounters the return keyword, it will exit the method immediately. Thus, the codes next to return keyword are "unreachable".

Parameterless Method

Methods can have no parameters
public void noParam(){
 System.out.println("This method doesn't have parameters!");
}

Method Overloading

There are times that we want to have two methods that share the same name but have similar or different function. We can do that in java by using method overloading. Method overloading is part of OOPs(Object-Oriented Programming System) concept. Method overloading resides in static polymorphism which is part of OOPs concept and does static binding. Binding is a way of connecting a method call to a method body. Overloaded methods must not be identical.
Example:

public class SampleClass{
  
  public int findMax(int[] n){
    int max = 0;
    for(int num : n)
      if(num > max)
        max = num;
    
    return max;
  }
  
  public int findMax(int n1, int n2){
    
    if(n1 > n2)
       return n1;
    else return n2; //n1 < n2 or n1 == n2
  }
  
 public static void main(String[]args){
   SampleClass sc = new SampleClass();
   int[] numbers = {3,1,22,2,6,15,10};
   
   String str = "Find the maximum value"+
                " of these numbers: ";
                
   for(int i = 0; i < numbers.length;i++){
     if(i != numbers.length-1)
     
       str = str + numbers[i] + ", ";
     else str = str + numbers[i];
   }
   
   System.out.println(str+"\n"+"Max value: "+
                      sc.findMax(numbers));
   System.out.println();
   System.out.println("Find the maximum value"+
                      " between 10 and 4 "+
                      "\nMax Value: "+
                      sc.findMax(10,4));
 }
}

Result
Find the maximum value of these numbers: 3, 1, 22, 2, 6, 15, 10
Max value: 22

Find the maximum between 10 and 4
Max value: 10
In the example above, we have two overloaded methods: findMax(int[] n), findMax(int n1,int n2)
These overloaded methods are not identical because they have different number of parameters. Let's try overloaded methods with different return types.
public class SampleClass{
  
 public int add(int n1, int n2){
  return n1 + n2;
 }
 
 public void add(int n1, int n2){
  System.out.println("Add "+n1+" to "+n2+" = "+(n1+n2));
 }
  
 public static void main(String[]args){
   SampleClass sc = new SampleClass();
   System.out.println("Adding 3 to 5 = "+
                      sc.add(3,5));
   sc.add(5,5);
 }
}
This code will have a compile time error. They might have different return types but their parameters have the same count and type and Java considers these methods identical. Let's try overloaded methods with the same amount of parameters but the type of their parameters are different.
public class SampleClass{
  
 public void add(int n1, int n2){
  System.out.println("Add int: "+n1+" + "+n2+" = "+(n1+n2));
 }
 
 public void add(long n1, long n2){
  System.out.println("Add long: "+n1+" + "+n2+" = "+(n1+n2));
 }
  
 public static void main(String[]args){
   SampleClass sc = new SampleClass();
   System.out.println("int addtion");
   sc.add(8,3);
   System.out.println("long addtion");
   sc.add(5,5);
 }
}

Result
int addition
Add int: 8 + 3 = 11
long addition
Add int: 5 + 5 = 10
This code will be compiled successfully. Although, the result looks incorrect. The add() method with integer parameters has been called two times instead of calling the add() method with long type parameters.

This happens because when we write a number in our code, for example "5", that number is an integer literal by default. Thus, add() with integer parameters is always called. This also happens to floating-point numbers. When we write "5.5" in our code then java considers that number as double by default. To solve this problem above, add "L" suffix in the second method call. Adding the suffix "L" means that the number is long type.
 public static void main(String[]args){
   SampleClass sc = new SampleClass();
   System.out.println("int addtion");
   sc.add(8,3);
   System.out.println("long addtion");
   sc.add(5L,5L);
 }
 
Result
int addition
Add int: 8 + 3 = 11
long addition
Add long: 5 + 5 = 10
Just like return type, access modifiers don't matter in method overloading.
 void add(int n1, int n2){
  System.out.println("Add int: "+n1+" + "+n2+" = "+(n1+n2));
 }
 
 public void add(long n1, long n2){
  System.out.println("Add long: "+n1+" + "+n2+" = "+(n1+n2));
 }
The code above will be compiled fine. The first add() has default modifier. default modifier grants access to all classes that are part of a package where the class or class member that has default modifier resides. The second add() has public modifier.

Let's try overloading static and non-static methods.
 public static void add(int n1, int n2){
  System.out.println("Add int: "+n1+" + "+n2+" = "+(n1+n2));
 }
 
 public void add(long n1, long n2){
  System.out.println("Add long: "+n1+" + "+n2+" = "+(n1+n2));
 }
This code will be compiled without errors. Just like return type and access modifiers, static keyword doesn't matter in method overloading. If you wanna know more then check out these links: are static and non static overloads each other and 8.4.9. Overloading

If an overloaded method has a primitive parameter and another overloaded method has wrapper class, the method with primitive parameter is going to be called.
public class SampleClass{
  
  void display(int i){
    System.out.println(i + " is int.");
  }
  
  void display(Integer i){
    System.out.println(i + " is Integer.");
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    sc.display(10);
  }
}
If an overloaded method has a parameter and another overloaded method has Variable Arguments parameter, the method with the parameter that is not varargs is going to be called.
public class SampleClass{

  void display(int i){
    System.out.println(i + " is int.");
  }
  
  void display(Integer... i){
    for(Integer integer : i)
       System.out.println(integer + " is Integer.");
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    sc.display(10);
  }
}

Method Overriding

Method Overriding is similar to method overloading but method overriding works with class inheritance. Understanding of inheritance is required to understand this topic. Method overriding is part of OOPs(Object-Oriented Programming System) concept.It resides in dynamic polymorphism which is part of OOPs concept and does dynamic binding. Binding is a way of connecting a method call to a method body. Overriding method(method in sub class) must have close similarities to Overriden method(method in super class).
Example

public class SampleClass extends SuperClass{
  
  @Override
  public void createMessage(){
    System.out.println("Message from SampleClass class");
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    SuperClass supC = new SuperClass();
    sc.createMessage();
    supC.createMessage();
  }
}

class SuperClass{

  public void createMessage(){
    System.out.println("Message from SuperClass class");
  }
}

Result
Message from SampleClass class
Message from SuperClass class
As you can see, each class has different implementation of createMessage(). Use @Override annotation to specify that the method overrides the method in the super class. Using annotations improves the readability of your code.

If we want to call a member(visible to sub class) of super class in sub class then we can use the super keyword.
Example

public class SampleClass extends SuperClass{
  
  @Override
  public void createMessage(){
    System.out.println("Message from SampleClass class");
    super.createMessage();
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    sc.createMessage();
  }
}

class SuperClass{

  public void createMessage(){
    System.out.println("Message from SuperClass class");
  }
}

Result
Message from SampleClass class
Message from SuperClass class
Here are some rules for method overriding

1.) If an overriden method has parameters then the overriding method must match the the number,type and order of overriden method parameters. Parameter names in overriding method can be different from parameter names in overriden method.

2.) Unlike in method overloading, access modifier does matter in method overriding. The access modifier of overriding method must be equal or less restrictive than the overriden method.
Example

public class SampleClass extends SuperClass{
  
  //Overriding Method
  @Override
  void createMessage(){
    System.out.println("Message from SampleClass class");
    super.createMessage();
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    sc.createMessage();
  }
}

class SuperClass{
  
  //Overriden Method
  public void createMessage(){
    System.out.println("Message from SuperClass class");
  }
}
This code will throw a compile-time error because the overriding method has access modifier that is more restrictive than the overriden method. default access modifier is more restrictive than public access modifier.

3.) we cannot override methods with static, private or final keyword. Those methods belong to their respective classes. static methods belong to the class itself and can't be overriden because the compiler implements static binding to static methods; private methods belong to the class instance and can't be inherited by sub classes; and final methods can't be overriden.

4.) Overriding method can only throw unchecked exceptions if overriden method doesn't throw any exception.
public class SampleClass{

  public static void main(String[]args){
  }
}

class Message{

  void displayMessage(){
    System.out.println("This is my Message!");
  }
  
  void sendMessage(String message){
    System.out.println("Message: " + message);
    System.out.println("Message sent!");
  }
}

class Messenger extends Message{
  
  //no error
  @Override
  public void displayMessage(){
    System.out.println("Message In Messenger");
  }
  
  //error
  /*
  @Override
  public void sendMessage(String message) throws Exception{
    System.out.println("Send Message: " + message);
    System.out.println("Message Sent!");
  }
  */
  
}
5.) If the overriden method throws an exception then, the overriding method can only throw the same exception or related(sub class) exceptions.
public class SampleClass{

  public static void main(String[]args){
  }
}

class Message{

  void displayMessage() throws Exception{
    System.out.println("This is my Message!");
  }
  
  void sendMessage(String message) throws RuntimeException{
    System.out.println("Message: " + message);
    System.out.println("Message sent!");
  }
}

class Messenger extends Message{
  
  //no error because RuntimeException is a sub class of
  //Exception
  @Override
  public void displayMessage() throws RuntimeException{
    System.out.println("Message In Messenger");
  }
  
  //error because Exception is not a RuntimeException and
  //not a sub class of RuntimeException
  /*
  @Override
  public void sendMessage(String message) throws Exception{
    System.out.println("Send Message: " + message);
    System.out.println("Message Sent!");
  }
  */
  
}
6.) Overriding methods, with the same name and parameter-list but with different return types in one class, throws a compile time error that is related to method overloading.
public class SampleClass{

  public static void main(String[]args){
  }
}

abstract class Message{

  abstract void message();
}

abstract class Greetings extends Message{

  String message(){
    return "Greetings";
  }
}

class Messenger extends Greetings{
  
  //error: method message() is already
  //defined...
  @Override
  public void message(){}
  @Override
  public String message(){ return ""; }
}
If we add a parameter in one of the message() methods then the code above will compile successfully.
public class SampleClass{

  public static void main(String[]args){
  }
}

abstract class Message{

  abstract void message();
}

abstract class Greetings extends Message{

  //add one parameter to make the two message()
  //not identical
  String message(String message){
    return "Greetings! " + message;
  }
}

class Messenger extends Greetings{
  
  //error: method message() is already
  //defined...
  @Override
  public void message(){}
  @Override
  public String message(String message){
    return "Greetings From Messenger! " + message;
  }
}
Covariant Return Type

You need to have an understanding of inheritance to understand this topic. We can change the return type of the overriding method as long as that return type is a subtype of the overriden return type. Prior to java5, overriding method must have the same return type as the overriden method. Thus, their return types are invariant. However, since java5, overriding methods can change their return type. Though, this only works with non-primitive types.
public class SampleClass{

  public static void main(String[]args){
  
    Case penCase = new Case();
  	penCase.getPen().displayName();
  	Metal metalcase = new Metal();
  	metalcase.getPen().displayName();
  }
}

class Pen{
  private String name = "Pen";
  
  public void displayName(){
    System.out.println(name);
  }
  
}
class Ballpoint extends Pen{
  private String name = "Ballpoint Pen";
  
  public void displayName(){
    System.out.println(name);
  }
  
}

class Case{

  public Pen getPen(){
    return new Pen();
  }
}

class Metal extends Case{

  @Override
  public Ballpoint getPen(){
   return new Ballpoint();
  }
}
The code above will be compiled fine. Ballpoint class is a subclass of Pen class. Therefore, Ballpoint class is a subtype of Pen class. Now, invert the overriding method in metal and the overriden method in Case:
class Case{
  
  public Ballpoint getPen(){
   return new Ballpoint();
  }
}

class Metal extends Case{

  @Override
  public Pen getPen(){
    return new Pen();
  }
}
This code throws a compile-time error regarding incompatibility because Pen class is the parent class of Ballpoint. Therefore, Pen class is the supertype of Ballpoint. Covariant return type only works with overriding method that has a return type that is a subtype.

Abstract Method

Abstract methods are similar to method definition but they don't have method body. You will see abstract methods in abstract class and interface. If a class extends or implements an abstract class or interface with abstract methods then the class is required to override and define those abstract methods.
General Form: access-modifier abstract return-type method-name(parameters);

Example
public class SampleClass extends AbstractClass{

  //Override createMessage()
  @Override
  public void createMessage(){
    System.out.println("Message from SampleClass");
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    sc.createMessage();
  }
}

abstract class AbstractClass{
public abstract void createMessage();
}
This code will be compiled without errors. try removing the createMessage() in SampleClass and you will encounter a compile-time error.

Java pass-by-value

When we assign a value to a variable, we're doing pass-by-value. Let's say a variable is an address and is pointing at a value.
int a = 5;
the "a" variable here is an address and that address is pointing at value "5". Now, let's try two variables.
int a = 5;
int b = 10;
int a = b;

Let's focus on int a = b;.When we print "a" on cmd the result is 10. When we do this kind of assignment, we're passing a copy of the value of b to a. Pretty easy right? Now, let's try passing values to a method call.
public class SampleClass{
  
  public void changeVal(int a){
    a += 5;
    System.out.println("\"a\" value in changeVal: " + a);
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    int a = 5;
    System.out.println("\"a\" value before changeVal: " + a);
    sc.changeVal(a);
    System.out.println("\"a\" value after changeVal: " + a);
  }
}

Result
"a" value before changeVal: 5
"a" value in changeVal: 10
"a" value after changeVal: 5
As you can see, the value of int a is still 5 after the program completed changeVal() execution. When we put "a" in changeVal() java only assigned the value of variable "a" of main() to "a" variable of changeVal(). Now, let's try objects.
public class SampleClass{
  
  public void changeVal(StringBuilder a){
    a.append("cd");
    System.out.println("\"a\" value in changeVal: " 
                       + a.toString());
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    StringBuilder a = new StringBuilder("ab");
    System.out.println("\"a\" value before changeVal: "
                       + a.toString());
    sc.changeVal(a);
    System.out.println("\"a\" value after changeVal: "
                       + a.toString());
  }
}

Result
"a" value before changeVal: ab
"a" value in changeVal: abcd
"a" value after changeVal: abcd
Now, "a" value has changed after the program completed changeVal() execution. With this result, you might consider that java is not pass-by-value at all. Let me explain the code above first.

Take a look at this code: StringBuilder a = new StringBuilder("ab");
When we assign an object to a variable, java assigns the address of the object, in other words, the reference of the object to the variable. Now, we have two adresses, the address of the variable and that address is pointing at the address of the object and that address is pointing at the real object in the heap.

When we pass the value of "a" in changeVal(), we're passing the reference of the object in the "a" variable in changeVal(). Now, the variable "a" in main() and the variable "a" in changeVal() are now pointing at the same object reference. Thus, any changes in "a" variable in changeVal() will be reflected to "a" variable in main().

Now, let's tweak the example above.
public class SampleClass{
  
  public void changeVal(StringBuilder a){
    a = new StringBuilder("abcd");
    a.append("ef");
    System.out.println("\"a\" value in changeVal: "
                       + a.toString());
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    StringBuilder a = new StringBuilder("ab");
    System.out.println("\"a\" value before changeVal: "
                       + a.toString());
    sc.changeVal(a);
    System.out.println("\"a\" value after changeVal: "
                       + a.toString());
  }
}

Result
"a" value before changeVal: ab
"a" value in changeVal: abcdef
"a" value after changeVal: ab
The value of "a" in main didn't change after the program completed changeVal() execution. Let's examine the code. So, we put "a" of main() in changeVal(). Now, "a" in main and "a" in changeVal() point at the same object reference. Now, take a look at this code
a = new StringBuilder("abcd");
This code created a new StringBuilder with "abcd" String and assigned the reference to "a" in changeVal(). Thus, "a" in main and "a" in changeVal are not pointing at the same object reference anymore. Thus, Any changes in "a" in changeVal() won't be reflected to "a" in main().

Arrays are considered as objects. So, when we pass an array in a method, we're passing the array's reference. Thus, we can modify arrays that are passed in methods.
public class SampleClass{
  
  public void changeVal(String[] a){
    a[0] = "String0";
    a = new String[]{"StringA"};
    System.out.println("\"a\" value in changeVal: " + a[0]);
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    String[] a = new String[]{"MyString"};
    System.out.println("\"a\" value before changeVal: " + a[0]);
    sc.changeVal(a);
    System.out.println("\"a\" value after changeVal: " + a[0]);
  }
}

Result
"a" value before changeVal: MyString
"a" value in changeVal: StringA
"a" value after changeVal: String0
Let's test other object types like String and some wrapper classes.
public class SampleClass{
  
  public void changeVal(String a){
    a += "cd";
    System.out.println("\"a\" value in changeVal: " + a);
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    String a = "ab";
    
    System.out.println("\"a\" value before changeVal: " + a);
    sc.changeVal(a);
    System.out.println("\"a\" value after changeVal: " + a);
  }
}

Result
"a" value before changeVal: ab
"a" value in changeVal: abcd
"a" value after changeVal: ab
Take a look at this code: a += "cd";
this code is equivalent to this: a = new String(a + "cd");
Note: When talking about memory storage, the expression "cd" and new String(a + "cd") store string objects in different memory sections. Refer to my "Java Tutorial: Exploring The String Class" blogpost.

Now, Let's try wrapper class. Wrapper classes are classified as value-based classes.
public class SampleClass{
  
  public void changeVal(Integer a){
    a += 4;
    System.out.println("\"a\" value in changeVal: " + a);
  }
  
  public static void main(String[]args){
    SampleClass sc = new SampleClass();
    Integer a = 3;
    
    System.out.println("\"a\" value before changeVal: " + a);
    sc.changeVal(a);
    System.out.println("\"a\" value after changeVal: " + a);
  }
}

Result
"a" value before changeVal: 3
"a" value in changeVal: 7
"a" value after changeVal: 3
Take a look at this code: a += 4;
this code is equivalent to this: a = Integer.valueOf(a + 4);

Actually, there are two types of value passing mechanism, if you will. These are: pass-by-value and pass-by-reference. Java is often specified as pass-by-value and pass-by-reference. Go to this article: Is Java “pass-by-reference” or “pass-by-value”? to clear the confusion between pass-by-value and pass-by-reference.

Method Chaining

This topic requires you to have a basic understanding of class and class instance.
When we wanna call multiple methods in one line we can use method chaining. Before that, let's call methods like we usually do.
public class SampleClass{
 private int num;
 
 public void setNum(int n){
   num = n;
   System.out.println("num is set to " + num);
 }
 
 public void add(int n){
   int result = num + n;
   System.out.println(num + " + " + n + " = " + result);
   num = result;
 }
 
 public void square(){
  int result = num * num;
  System.out.println(num + "^2" + " = " + result);
  num = result;
 }
 
 public int getNum(){ return num; }
 
 public static void main(String[]args){
   SampleClass sc = new SampleClass();
   sc.add(3);
   sc.square();
   sc.add(2);
   sc.add(4);
   sc.square();
   
   System.out.println("num value is: " + sc.getNum());
 }
 
}
As you can see, calling multiple methods is pretty lengthy. Now, let's try method chaining.
public class SampleClass{
 private int num;
 
 public SampleClass setNum(int n){
   num = n;
   System.out.println("num is set to " + num);
   return this;
 }
 
 public SampleClass add(int n){
   int result = num + n;
   System.out.println(num + " + " + n + " = " + result);
   num = result;
   return this;
 }
 
 public SampleClass square(){
  int result = num * num;
  System.out.println(num + "^2" + " = " + result);
  num = result;
  return this;
 }
 
 public int getNum(){ return num; }
 
 public static void main(String[]args){
   SampleClass sc = new SampleClass();
   int num = sc.add(3).square().add(2).add(4).square().getNum();
   System.out.println("num value is: " + num);
 }
 
}
As you can see, I only write "sc" once. Before I explain the code above let me introduce the this keyword. this keyword refers to a class instance in which it's used. return this; means we're returning the reference of an instance class. In the example above, this keyword returns the instance of SampleClass() that has been assigned to sc.

First we called sc.add(3), sc held a class instance of SampleClass. Then, add() returned the class instance that was assigned to sc. Now, the program called square(). This time, the return value of previous call to add(3) was used to call square(). The program called add(2) again, this time the return value of previous call to square() was used to call add(2) and so on.

Then, the last method in the chain which was getNum() returned an int value and since there were no more methods to call the return value of getNum() was assigned to num. Try removing getNum() and you will encounter an error.

Variable Arguments(Varargs)

Varargs was introduced in JDK5 and its usage is to simplify the parameter structure of a method. Varargs can take indefinite amount of arguments when a method that use varargs is called. Prior to JDK5, we can use an array type as a parameter to send a collection of data to a method or we overload a method to accept varying argument list. We can still utilize those techniques or we can use varargs.
public class SampleClass{
  
  //varargs
  void displayNames(String... names){
  
    for(int i = 0; i < names.length; i++)
      System.out.println(names[i]);
  }
  
  public static void main(String[]args){
  
    SampleClass sc = new SampleClass();
    System.out.println("name set #1");
    sc.displayNames("Dave","Crow","Ben","Wolf");
    System.out.println();
    System.out.println("name set #2");
    sc.displayNames("Owen","Sid");
    
  }
}
Take a look at this syntax: void displayNames(String... names)
The ... indicates that this parameter will take a variable number of arguments. The data type before ... indicates the type of arguments that this varargs parameter accepts. names is the parameter name.

As you can see in the displayNames() method body, varargs parameter is treated as an array. We can get the varargs parameter length by using the length field. You might wonder: "What if we put an array as an argument?". Well, let's try.
public class SampleClass{
  
  //varargs
  void displayNames(String... names){
  
    for(int i = 0; i < names.length; i++)
      System.out.println(names[i]);
  }
  
  public static void main(String[]args){
  
    SampleClass sc = new SampleClass();
    System.out.println("name set #1");
    String[] names = {"Dave","Crow","Ben","Wolf"};
    sc.displayNames(names);
    System.out.println();
    System.out.println("name set #2");
    sc.displayNames(new String[]{"Owen","Sid"});
    
  }
}
As you can see, an array as argument in a varargs parameter is acceptable because varargs is treated like an array.

We can also write a varargs parameter that takes arrays as an argument and it will be treated as a two-dimensional array.
public class SampleClass{
  
  //varargs
  void displayNames(String[]... names){
  
    for(int i = 0; i < names.length; i++)
      for(int j = 0; j < names[i].length;j++)
          System.out.println(names[i][j]);
  }
  
  public static void main(String[]args){
  
    SampleClass sc = new SampleClass();
    System.out.println("name set #1");
    sc.displayNames(new String[]{"Owen","Sid"},
                    new String[]{"Kay","Clover"});
    
  }
}
Before we use varargs, we need to follow some rules.
1.) When adding a varargs parameter on a parameter list with multiple parameters, varargs parameter must be the last parameter entry on the list.
public class SampleClass{
  
  //error: varargs parameter must be the last parameter
  /*
  void displayNames(String... names,String setName,int setNo){
    
    System.out.println("Set Name: " + setName);
    System.out.println("Set Number: " + setNo);
    for(int i = 0; i < names.length; i++)
      System.out.println(names[i]);
  }
  */
  
  void displayNames(String setName,int setNo,String... names){
    
    System.out.println("Set Name: " + setName);
    System.out.println("Set Number: " + setNo);
    for(int i = 0; i < names.length; i++)
      System.out.println(names[i]);
  }
  
  public static void main(String[]args){
  
    SampleClass sc = new SampleClass();
    sc.displayNames("C Set",1,"Civ","Crow","Cromwell","Crux");
    System.out.println();
    sc.displayNames("S Set",2,"Steve","Sid");
    
  }
}
2.) two or more varargs parameters in a parameter list are not allowed.
public class SampleClass{
  
  //compile-time error
  void displayNames(int... numbers,String... names){
  }
  public static void main(String[]args){}
}
When we call a method with varargs as its last parameter, we can omit the last argument in the method call and java won't complain.
public class SampleClass{

  public static void main(String[] args){
    SampleClass sc = new SampleClass();
    sc.displayNames("C Set",1);
  }
  
  void displayNames(String setName,int setNo,String... names){
    
    System.out.println("Set Name: " + setName);
    System.out.println("Set Number: " + setNo);
    System.out.println("names length: " + names.length);
    for(int i = 0; i < names.length; i++)
      System.out.println(names[i]);
  }
}

Tuesday, June 1, 2021

Java Tutorial: for, for-each, do-while and while loop statements

Chapters

Hello Everybody! This is brainy ghosts and today we're gonna discuss the loop statements. Java has different types of loops. In this blog we're going to discuss for,for-each,while and do-while loop statements.

for Loop Statement

Alright! Let's start with the for loop. You're going to use this loop a lot of times because of its usability when looping a collection or arrays.
General Form: for(statement1,statement2,statement3){//code to execute}
Example:
public static void main(String[]args){

  for(int i = 1; i <= 5; i++){
    System.out.print(i + " ");
  }
}

Result
1 2 3 4 5
Statement1: I would like to call this the initializer. We put a variable that we want to loop and assign a value to set the starting point of a loop.
Statement2: I would like to call this the conditional. If a condition that is related with the initializer variable becomes false, the loop ends.
Statement3: I would like to call this the value changer, if you will. This is where we increase/decrease the value of the initializer variable.

for-each Loop Statement

This loop statement simply loops a collection or array from the first element up to the last.
General Form: for(expression1 : expression2){//code to execute}
Example:
public static void main(String[]args){

int[] numbers = {1,2,3,4,5};

  for(int num : numbers){
    System.out.print(num + " ");
  }
}
Result
1 2 3 4 5
expression1: contains a variable that will hold each array/collection element per loop. The variable must have the same data type as the collection that you wanna loop.
expression2: contains an/a array/collection that is going to be iterated.

The syntax of this statement is much simplier than for loop but for loop is still more flexible. So, when to use for-each and for loop?

1.) If you want arbitrary access to array/collection elements then use for loop.
Example:
public static void main(String[]args){

int numbers[] = {2,3,5,6,8};

  for(int i = numbers.length-1; i >= 0; i--){
    System.out.print(numbers[i] + " ");
  }
}

Result
8 6 5 3 2
In the example above, I use for loop to iterate the array from the last index to first. You can't do that in for-each loop.

2.) If you need to know the index of each element in an/a array/collection, for loop is the man for the job.
Example:
public static void main(String[]args){

int numbers[] = {1,2,3,4,5};

  for(int i = 0; i < numbers.length; i++){
    if(i == 0)
      System.out.println("We're at the first element: " + numbers[i]);
    else if(i == numbers.length-1)
      System.out.println("We're at the last element: " + numbers[i]);
    else System.out.println(numbers[i]);
  }
}

Result
"We're at the first element: " 1
2
3
4
"We're at the last element: " 5
3.) If you just want to iterate array/collection in sequential manner then use for-each loop.
Example:
public static void main(String[]args){

String[] str = {"I","Love","Earth!"};

  for(String s : str){
    System.out.print(s + " ");
  }

}

Result
I Love Earth!
do-while Loop Statement

This statement is used when you want to loop a task and end it based on certain condition.
General Form: do{//code to execute}while(condition);
Example:
public static void main(String[]args){

  String str = "";
  System.out.println("Task: add letter \"s\" to str until it reaches"
  					+" a certain length");
  do{
    str += "s";
  }while(str.length() < 5);
  System.out.println("result: " + str);
}

Result
sssss
while Loop Statement

This is very similar to do-while but without the "do" part.
General Form: while(condition){//code to execute};
Example:
public static void main(String[]args){

  String str = "";
  System.out.println("Task: add letter \"s\" to str until it reaches"
  					+" a certain length");
                    
  while(str.length() < 5){
    str += "s";
  }
  System.out.println("result: " + str);
}

Result
sssss
We can put an initializing expression in the while parentheses while formulating a condition.
public static void main(String[]args){

  int num = 0;
  
  while((num = ++num) < 5)
    System.out.println(num);
}
Don't forget to put the initializing expression in the parentheses.

So, What's the difference between do-while and while apart from the compacity of while loop? do-while loop executes its block first before evaluating the condition whereas while loop evaluates the condition first before executing its block.
Example:
public static void main(String[]args){

   String str = null;
   String placeholder = "";
   System.out.println("Task: add letters \"s\" to str until it reaches"
                      +" a certain length");
   System.out.println();
   System.out.println("do-while loop");
   //do-while loop
   do{
      placeholder += "s";
      str = new String(placeholder);
   }
   while(str.length() < 5);
   System.out.println("result: " + str);
   System.out.println();
   System.out.println("while loop");
   //while loop
   str = null;
   placeholder = "";
   while(str.length() < 5){
      placeholder += "s";
      str = new String(placeholder);
   }
   System.out.println("result: " + str);
}
You will encounter a NullPointerException when the program starts executing the while loop 'cause str is null and the length() method of String class will throw NullPointerException if you're trying the get the length of a null string.

In do-while loop, do is executed first where a new string is created that's why the length() doesn't throw NullPointerException.

break and continue keywords

We already saw the break keyword being used in the switch statement. It can be used in loops too.
Example:
public static void main(String[]args){
  String str[] = {"doll","puppet","figurine"};
  
  System.out.println("Find puppet");
  for(int i = 0; i < str.length; i++){
    if(str[i].equals("puppet")){
      System.out.println("Found puppet in index: " + i);
      break;
    }
    System.out.println(str[i] + " is not a puppet.");
  }
}

Result:
doll is not a puppet.
Found puppet in index: 1
break keyword stops the execution of loops. In this example, "figurine" string is not displayed on the result because the loop stopped at the "puppet" string.

continue keyword interrupts the execution in the loop's body.
Example:
public static void main(String[]args){
  String str[] = {"doll","puppet","figurine"};
  
  System.out.println("Find puppet");
  for(int i = 0; i < str.length; i++){
    if(str[i].equals("puppet")){
      System.out.println("Found puppet in index: " + i);
      continue;
    }
    System.out.println(str[i] + " is not a puppet.");
  }
}

Result:
doll is not a puppet.
Found puppet in index: 1
figurine is not a puppet.
In the example above, continue keyword interrupted the loop when it found "puppet" that's why the println() below didn't execute. You can see in this example that the loop didn't completely stop, unlike in break. That's why "figurine" is displayed on the result. Try removing the continue and the result is going to be:
Result:
doll is not a puppet.
Found puppet in index: 1
puppet is not a puppet.
figurine is not a puppet.


We can't put codes next to break and continue keywords. If we do, we will encounter an "unreachable" error.
public class SampleClass{

 public static void main(String[]args){
   
   for(int i = 0; i < 4; i++){
	   break; //same result if we use continue
	   System.out.println(i);
   }
 }
}
This code will throw an "unreachable" error. Java can't execute codes next to break because if the execution encounters break or continue, it will exit the loop or move to the next iteration. Thus, the codes next to break or continue are "unreachable".

Infinite loops

Note: if you unintentionally stuck in a loop just close the terminal or command prompt(or ctrl+c in Windows). If you're using IDE find a button that will make your program to stop.
We can create a loop that never stops by using these syntaxes:
//do-while infinite loop
do{}while(true);
//for infinite loop
for(;;){//code to execute}
//while infinite loop
while(true){//code to execute}
Use the break keyword to stop these loops programatically.
In practical programming, you will see the while infinite loop most of the time 'cause it's simple and more readable than its counterparts. You will see infinite loops in game loop, timer, monitoring, etc.

Using floating-point numbers in loops

We can use floating-point numbers in loops.
Example:
public static void main(String[]args){
  
  for(double i = 0; i <= 0.6; i+=.15){
    System.out.println(i);
  }
}

Result
0.0
0.15
0.3
0.44999999999999996
0.6
The example above works fine but it's not recommended due to floating-point nature that may cause errors. I recommend you to read this topic about floating-point numbers in this link:Is floating point math broken? Alternative way is to compute the floating-point inside the loop.
Example:
public static void main(String[]args){
  
  double d = 0;
  for(int i = 0; i <= 4; i++){
    d = 0.15 * i;
    System.out.println(d);
  }
}

Result
0.0
0.15
0.3
0.44999999999999996
0.6
The example above only works if you know how many iterations you need. In the example, I use i <= 4 because I want to iterate .15 five times(Starting from 0).

Now, pay attention to this result: 0.44999999999999996
that must be .45 but the program displayed 0.44999999999999996
As you can see, floating-point numbers are sometimes innacurate and this inaccuracy may lead to nerve-racking errors. Consider this example.
Example:
public static void main(String[]args){
  double d = 0;
  
  while(true){
    System.out.println(d);
    d += 0.15;
    if(d == 0.5) break;
  }
}
The example above will cause an infinite loop due to the floating-point artifact.

Omitting some tokens and keywords in loop statement

If you read my if statement tutorial some conditions that I'm going to show here are the same as the conditions in that tutorial.

1.) Braces can be removed if there's only one statement in the body of a loop statement.
Example:
public static void main(String[]args){
  for(int i = 1; i <= 5; i++)
    System.out.print(i + " ");
  System.out.println();
    
  String str = "";
  System.out.println("Task: add letter \"s\" to str until it reaches"
                       +" a certain length");
  do
   str += "s";
  while(str.length() < 5);
	
  System.out.println("result: " + str);
}
2.) We are not required to compare a boolean variable or a method that returns boolean value to the "true" and "false" keywords. This only applies to loop statements that have condition statement like for,do-while and while loop.
Example:
public static void main(String[]args){

  String str = "";
  
  do{
    str += "s";
  }while(!str.equals("sssss"));
  System.out.println("result: " + str);
}
3.) In for loop, we can omit any statement in the parentheses.
Example:
public static void main(String[]args){

  for(int i = 0;;i++){
    System.out.print(i + " ");
    if(i >= 5) break;
  }
  System.out.println();
  
  for(int i = 0;;){
    System.out.print(i + " ");
    i++;
    if(i >= 5) break;
  }
  System.out.println();
  
  int i = 1;
  for(;i <= 5;){
    System.out.print(i + " ");
    i++;
  }
}
Nested loops

Like other statements, loop statements can be nested. Here's an example.
Example:
public static void main(String[]args){

   String[] str = {"Puppet","Trumpet","Veteran"};
	  
   for(String s : str){
       System.out.println("Word: " + s);
	   
       boolean isP = false;
       for(int i = 0; i < s.length(); i++){
         if(s.charAt(i) == 'p' || s.charAt(i) == 'P' ){
            isP = true;
            break;
         }
         System.out.println(" " + s.charAt(i) + " at index: " + i);
       }
       if(isP) System.out.println("There's a \"P\" in " + s); 
       else System.out.println("There's no \"P\" in " + s);
       System.out.println();
   }
}

Result
Word: Puppet
There's a "P" in Puppet
         
Word: Trumpet
 T at index: 0
 r at index: 1
 u at index: 2
 m at index: 3
There's a "P" in Trumpet

Word: Veteran
 V at index: 0
 e at index: 1
 t at index: 2
 e at index: 3
 r at index: 4
 a at index: 5
 n at index: 6
There's no "P" in Veteran
Notice that break didn't stop the for-each loop. It only stopped the for loop. That's because break and continue only affect loops where they reside. Now, try to nest loops yourself and try to include while or do-while loop.

Loop Using Labels

We can use labels to specifically redirect an iteration of a loop. break and continue keywords use labels to redirect iteration to a specified scope. Take a look at this example.
public class SampleClass{

 public static void main(String[]args){
   
   main_loop: 
     for(int i = 0; i < 5; i++){
       System.out.println("main: " + i);
       sub_loop:
         for(int j = i; j < 5; j++){
           System.out.println("sub: " + j);
           if(j <= 1){
             System.out.println
             ("continue sub_loop");
             continue sub_loop;
           }
           for(int k = 0; k < 2;k++){
             System.out.println
             ("inner: " + k);
             
             if(j > 3){
             System.out.println
             ("break main_loop");
             break main_loop;
             }
           }
        }
     }
 }
}

Result
main: 0
sub: 0
continue sub_loop
sub: 1
continue sub_loop
sub: 2
inner: 0
inner: 1
sub: 3
inner: 0
inner: 1
sub: 4
inner: 0
break main_loop
The name of labels must follow the naming syntax of variables.

Java Tutorial: if-then, if-then-else and switch statements

Chapters

if-then Statement

Hello Everybody! This is brainy ghosts and today we're gonna discuss the if-then, if-then-else and switch statement which are parts of the java control flow statement. If-then statement is the most basic component of the control flow statement.
General Form: if(cond){//code to execute}

Example:
public static void main(String[]args){
  boolean condition = true;
      
  if(condition == true){
     System.out.println("condition is true");
  }
}

Try changing the value of condition variable to false and the program won't execute the println() in the if-then(or just if) statement.

we can put initializing expression in the if parentheses while formulating a condition. This will also work in switch and else-if parentheses.
public static void main(String[]args){

  int num = 3;
  
  //(num = ++num) is the initializing
  //expression
  if((num = ++num) > 3)
    System.out.println("num("+num+") is greater than 3!");
  else
    System.out.println("num("+num+") is less than 3!");
}

if-then-else Statement

This statement is very similar to if-then but with additional else block. This block will execute if the condition in if block is not true.
General Form:
if(cond){
  //code to execute
}
else{
  //code to execute
}
Example:
public static void main(String[]args){
  boolean condition = false;
      
  if(condition == true){
     System.out.println("condition is true");
  }
  else{
    System.out.println("condition is false");
  }
}
if-else-if Statement

Use this statement if you need to test multiple conditions. We have additional block here which is the else if() block.
General Form:
if(cond){
  //code to execute
}
else if(cond){
  //code to execute
}
else{
  //code to execute
}
The else block is optional. You can omit that block. If all conditions are false then code in else block will be executed, if there's one.
Example:
public static void main(String[]args){
  String foo = "small";
  String bar = "large";
  
  if(foo.equals("large") == true && 
     bar.equals("small") == true){
     System.out.println("foo is large and bar is small");
  }
  else if(foo.equals("small") == true &&
          bar.equals("large") == true){
  	 System.out.println("foo is small and bar is large");
  }
  else if(foo.equals("small") == true &&
          bar.equals("small") == false){
  	 System.out.println("foo is small but bar is not small");
  }
  else{
    System.out.println("All conditions are false.");
  }
}
This statement is evaluated from top to bottom, starting at if() block. if one of the conditions is true then other conditions below it won't be evaluated.

The equals() method is a pre-defined method in String class that compares the values of two strings. It returns true if two strings are equal, false otherwise. We will learn about methods in future tutorial.

Switch Statement

This statement is very similar to if statement with new syntax. Use this statement if you want to evaluate multiple possible values of a variable.
General Form:
switch(value){

    case value1:
    //code to execute
    break;
    ...
    
    default:
    //code to execute
    break;

}
"..." means you can put any number of possible values in the statement. default is optional and has the same purpose as the else statement in if-else-if: it will be executed if the value of the "value" variable doesn't match any possible values that we put in the switch statement. default will be also executed if a break before it is omitted. We will learn about omitting the break keyword in the switch statement later.
Example:
public static void main(String[]args){
 String bar = "large";
 
switch(bar){
   case "small":
   System.out.println("bar is small");
   break;
   
   case "medium":
   System.out.println("bar is medium");
   break;
   
   case "large":
   System.out.println("bar is large");
   break;
   
   default:
   System.out.println("No Possible Match!");
   break;
 }
}
break can be omitted if we want to. The purpose of break is to stop the execution in the switch block once a match is found. Omitting break makes the execution in the switch statement continue even a match is found.
Example:
public static void main(String[]args){
 String cat = "large";
 
   switch(cat){
     case "small":
     System.out.println("cat is small");
     cat = "cute";
			
     case "cute":
     System.out.println("cat is cute");
     break;
   
     case "large":
     System.out.println("cat is large");
     cat = "fluffy";
			
     case "fluffy":
     System.out.println("cat is fluffy");
     break;
			
     default:
     System.out.println("No Possible Match!");
     break;
   }
}
Result
cat is large
cat is fluffy

Differences between if and switch statement

We already know that if statement is preferrable when dealing with conditions whereas switch statement is preferrable when dealing with matching criteria. Other differences are:

1.) switch doesn't accept boolean values whereas if statement does.
Example:
public static void main(String[]args){
  boolean condition = true;
 
   switch(condition){
     case true:
     System.out.println("condition is true");
     break;
     
     case false:
     System.out.println("condition is true");
     break;
   }
}
You will encounter an error if you compile this code above. We already know if statement accepts boolean values.

2.) switch doesn't accept null value whereas if statement does.
Example:
public static void main(String[]args){
  String cat = null;
 
   switch(cat){
     case "small":
     System.out.println("cat is small");
     break;
     
     case "big":
     System.out.println("cat is big");
     break;
   }
}
You will encounter an error if you compile this code above. Let's try null value in the if statement.
Example:
public static void main(String[]args){
  String cat = null;
 
   if(cat == null){
     System.out.println("Oh! Ow! cat doesn't exist!");
   }
}
This code above will be compiled without errors.

Omitting some keywords and tokens in if statement

We can remove some tokens like braces in if statement if we meet these conditions:
1.) Braces can be removed if there's only one statement in the body of if,else if and else block
Example:
public static void main(String[]args){
  String cat = "small";
 
   if(cat.equals("small") == true)
     System.out.println("cat is small");
   else if(cat.equals("large") == true)
     System.out.println("cat is large");
   else
     System.out.println("No Match");
     
}
Note: if-else and if-else-if statements behave like a single statement. So this syntax is legal.
if(true)
  if(true)
  else
However, I don't recommend the syntax above to be used 'cause it can make your code messy and confusing that may cause unexpected results. When creating a complex branching statement please add braces.

Tip: if you use if-else or if-else-if statement and, for example, else or else if statement is a block, then the statement above should be a block too.
Example:
public static void main(String[]args){
  String cat = "small";
 
   if(cat.equals("small") == true){
     System.out.println("cat is small");
   }
   else{
     System.out.println("Cat is not small");
     System.out.println("But I still love my cat");
   }
}
This code above is alright and more readable.

2.) We are not required to compare a boolean variable or a method that returns boolean value to the "true" and "false" keywords.
Example:
public static void main(String[]args){
  String cat = "small";
  boolean condition = true;
 
   if(cat.equals("small"))
     System.out.println("cat is small");
   else if(!cat.equals("small"))
     System.out.println("cat is not small");
     
   if(condition)
     System.out.println("condition is true");
   else if(!condition)
     System.out.println("condition is false");
}
This syntax might be confusing for beginners but this will make your code more tidy.

Nested if and switch statement

if and switch statement, like other statements, can be nested. Here's an example.
Example:
public static void main(String[]args){
  String catSize = "small";
  int catAge = 4;
 
   switch(catSize){
   
     case "small":
     System.out.println("cat is small");
     
     if(catAge >= 1 && catAge <= 3)
       System.out.println("cat is young.");
     else if(catAge >= 4 && catAge <= 5)
       System.out.println("cat is growing up.");
     else 
       System.out.println("cat is small and more than 5 yrs old.");
     break;
     
     case "large":
     System.out.println("cat is large");
     
     if(catAge >= 5 && catAge <= 10)
       System.out.println("cat is getting old.");
     else if(catAge >= 11)
       System.out.println("cat is immortal.");
     else 
       System.out.println("cat is large and less than 5 yrs old.");
     break;
   
   }
     
}