Learning Java: While Loops

Years ago when I wanted to use use a while loop I never thought about its categories, I just used because sometimes it easier to manage larges iterations, but it good to know more about it, and in which situation use it.

While Loops are loops that can execute a block of code as long as the specified condition is meet.

There are two types of repetitions control categories for the while loops; count-controlled repetitions and sentinel-controlled repetitions

Count-Controlled repetitions is the one that executes and after do it an amount of times it terminates and example of this is the method below:

 public static void counterControlled(int input) {
        /*
         * The CounterControlled is programmed to end after it is executed a fixed
         * amount of times for example Challenge: Print all the even numbers from 1-10
         * Count-controlled while loop Must have
         */

        // stating point
        int num = 1;
        // ending condition
        while (num <= input) {
            if (num % 2 == 0) {
                System.out.print("[" +num + "]" + " ");
                // a process to go from
            }
            // begining to ending
            num = num + 1;

        }
        System.out.println("-------------------");

    }

Sentinel-Controlled repetitions terminates its execution after a designate value is called in the code below we could see an example of this:

Scanner myObjectInput = new Scanner(System.in);

        System.out.println("Enter stop to finish");

        String stopingLoop = "";

        while ((!(stopingLoop = myObjectInput.nextLine()).equalsIgnoreCase("stop"))) {
            System.out.println("Say Whaaaat ?");

        }
        System.out.println("You " + stopingLoop + "ped the loop");
        myObjectInput.close();

In the code we could see that if we want to get out the while loop we just have to type the word “stop” because it is the designated value to terminate it.

When we are dealing with While loops it is very important to set a closing statement to terminate it because if not we are going to be falling in a infinite loop and we don’t want that , this is called (OBOE) which stands for “off-by-one-error”, we could appreciate an example of this in the code below:

     int count = 0;
        while(count != 20){
            count =  count + 3;     
            System.out.println(count);

        }

The code above won’t stop running because it will never reach it closing statement to terminate it, that’s what we should make sure we set a limit to our loop , for example to fix the code above we use the expression <= 20 so whenever it reach to 20 it will stop.

An useful tool when it comes to math operations it is use these

Learning Java: Interview Questions

When we are searching for jobs, it is really appropriated to start preparing ourselves for incoming interviews. We have to remember to be honest and express our thought while we are responding with precision.

Sometimes recruiters can be so polite when they interview you, and it is easy to think there’s no opportunity to pass it, but relax, don’t get intimidated by that, it is just a way to see if you get nervous.

Here we have some some Java interview Question that you may encounter in an interview:

Why is Java platform independent ?

Java have the principle of write once and run anywhere, but how ? A Java program it is compile into byte code which then run into any other JVM(Java Virtual Machine) and made it possible to run on different operating system.

Can you change the contents of a final array ?

Even if it is set as final, you can change what it is inside of an array in Java ,the contents in the array are allocate in a particular location in the memory which can’t be changed.

What is the difference between abstract class and interfaces?

Abstract class and interfaces are the great example of principle of inheritance. They both can be accessed by using key words: extends and implements. Unfortunately you can only extends one abstract class but can inherit as many interfaces as you can. Abstract class unlike interfaces can hold abstract and non-abstract methods where interfaces only can have abstract methods.

You can see more about about this in my previous abstract vs interfaces post

What is polymorphism?

Polymorphism could be translate as “many forms “. In Java polymorphism is the principle of adapting many form which means that allow you to use resources from other classes without needing to know which class is using it. An example of polymorphism are override and overload.

What is the difference between constructor and class method?

Constructors is a method that initialize objects of a class and doesn’t provide return statement. Also Constructors can’t be abstract nor final because the access it is need it. Unlike constructors, methods can have behaviors, have return statements or not and can be set as others access modifiers besides public.

Can main method be overloaded ?

You can see these and more questions like these here

Learning Java: Abstracts vs Interfaces

In the past every time I heard about abstract class and interfaces I had this feeling of something kind of useless because I rarely used it or didn’t know the meaning of using it. Now that I know how useful can be both, it is changing my perspective about them

Let’s talk about abstract class, we already knows it is a class that is declared as abstract but what does it means? What are the differences between them and Interfaces? and How to get access to them?

Abstract class are known for its diversity of holding abstract and non-abstract methods. It can have constructors and it methods can be overridden.

As we can see in the example below an abstract class called human is created. This class holds one abstract method called “Action” and two non-abstract methods called “age” and “clothing” which takes parameters and have behavior.

abstract class human {
    public abstract void Action();

    String studentName;
    int actualYear = 2019;

    public int age(int yearOfBorn) {
        System.out.println(studentName + " is " + (actualYear - yearOfBorn) + " years old");
        return actualYear - yearOfBorn;
    }

    public String clothing(String Day) {
        String result = "";
        if ((Day.equals("Monday") || Day.equals("Tuesday") || Day.equals("Wednesday") || Day.equals("Thursday"))) {
            result = studentName + " is wearing button shirt";
        } else if (Day.equals("Friday")) {
            result = studentName + " is wearing T-shirt";
        } else {
            result = studentName + " is on weekend mood";
        }
        System.out.println(result);
        return result;
    }
}

Unlike abstract classes, interfaces only can hold abstract methods, it doesn’t provide access modifiers; which means everything is public.

interface Human_Behavior {
    public abstract void happy();
    public abstract void Dance(String what);
}

Abstract class can be accessed from others classes if and only if the class extends to the abstract class, as well the interfaces have to be implemented to gain access, we can see that in the code below.

    class Student extends human implements Human_Behavior {
        int yearOfBorn;

        @Override
        public void Action() {
            System.out.println(studentName + " is Coding");
        }
        // Create a constructor
        public Student(String studentName) {
            this.studentName = studentName;
        }
        // The method MUST be called in this class
        @Override
        public void happy() {
            System.out.println(studentName + " is feeling happy.");
        }
        @Override
        public void Dance(String what) {
            System.out.println(studentName + " is dancing " + what);
        }
    }
    public class AbstractDemo { 
        public static void main(String[] args) {
            Student donelys = new Student("Donelys");
            donelys.Action();
            donelys.age(1994);
            donelys.clothing("Friday");
            donelys.happy();
            donelys.Dance("Bachata");
        }
    }
This image shows the result of the code below

As we see above, unlike method from abstract classes, method from interfaces MUST be in the class that is implemented, you can override them and add some behavior and then instanciate an object from the class to gain control over such behaviors.

After a research about abstracts classes and interfaces, I could notice how organized could looks our code when we are using them, it is like having a skeleton class from where you summon methods which make our coding life much simple.

If you want to know more about abstract class or interfaces check these sources: Abstract class , Interfaces, Abstract vs Interface

Learning Java: Attributes

The first time I heard about Attributes in Java I really thought it was a mistake, since I saw attributes as elements from CSS (Cascading Style Sheets). I thought It was something new on Java but apparently I was wrong, I used all the time and referred to it as “Variables”

Now lest talk about attributes, They are public constant or public variable that can be accessed directly, another word to refer to an attribute is “field”. As you can see in the example below “age” and “MY_AGE” are both attributes type int.

public class AttributeClass{
    int age;
    final int MY_AGE = 2019 - 1994;  

Attributes also can be modify. As we can see in the code below I instantiated the object “someone” and the object “donelys” from AttributeClass, Then I assigned the value 50 to attribute age.

    public static void main(String[] args) 
    {
        AttributeClass someone = new AttributeClass();
        AttributeClass donelys = new AttributeClass();
        someone.age = 50;
        System.out.println("someone age is: " + someone.age + " years old.");
        System.out.println("Donelys age is: " + donelys.MY_AGE + " years old.");

When a variable is set as final, it means that this variable become immutable and cannot be changed. As you can see in the code below I commented the change that I made to “MY_AGE” attribute because ill will return an error.

Also there are other classes that allows you to use their attribute as example in the code below we use “.length” attribute to retrieve the data of the array create.

        // donelys.MY_AGE = 12;
        // System.out.println("Donelys age is: " + Donelys.myAge );
        String[] array = {"hola","hello","bonjour", "klk"};
        System.out.println("Array length is: "+ array.length);
    }

}

Attribute, definitely are very useful when you need data from other classes, that is the magic that comes with a programming language that is object-oriented which makes coding mush easier and dynamically practical.

You can learn more about attributes here

Design a site like this with WordPress.com
Get started