Search Logic Blocks

Friday, January 31, 2020

Java: for-each loop

We have already learned about variations of for loop. There is one more variation for-each loop. for-each loop is used only for arrays and collections (A collection is a container that has multiple elements into one single unit and is used to store, retrieve, manipulate and communicate data). That's why I introduce this after introducing arraysfor-each loop is also called enhanced for loop and was introduced in Java1.5 (JDK 5).

NOTE: Collections are a set of classes that implement various data structures like lists, vectors, sets and maps. We will discuss about other kind of collections later in future posts.

The for-each loop enables the java program to traverse through the array elements sequentially without using the index variable. You also don't need to use array's length property. The general form for for-each loop is:

for(type variable: array) { }

Here type is data type same as or compatible to the array's data type, variable is an iteration variable which recieves the value of array element. With each iteration of the loop, the next element is passed to the variable. The loop repeats till the end of the array. Let's take last post arrays example once again and try to convert for loop into for-each loop.
for(int i = 0; i < nums.length; i++) {
    System.out.println("nums[" + i + "]:" + nums[i]);
}
Here, we replace the simple for loop with enhanced for loop (for-each loop) -
for(int num: nums) {
    System.out.println(num);
}
And the result is:

11
3
7
8
20
16

As the output shows, the for-each loop automatically cycles through an array in the sequence ordering from lowest index to the highest index. The for-each loop is useful when you need to examine whole array from start to finish like computing the sum of all the values or searching for a value etc. Let's write a program to sum of all the elements in an integer array.

Class ArrTest (ArrTest.java)
public class ArrTest {
    public static void main(String args[]) {
        int nums[] = {11, 3, 7, 8, 20, 16};
        int sum = 0;

        for(int num: nums) {
            sum = sum + num;
        }

        System.out.println("Sum is " + sum);
    }
}
Here is the output

Sum is 65

Although for-each loop is run from "start to end", it can be stopped in between using the break statement we discussed earlier. And one more important point is to be noted, as we are not using index to access the element of an array, we can not change the value of contents of the array in for-each loop, as you can do with traditional for loop.

Thursday, January 30, 2020

Java: Arrays

Arrays are containers of multiple values of same kind of data type (int, String, long, double, char and also objects of any class) and referred by a common name. An array is an object and can have fixed length of values in one variable. As I said, array is an object, we use new operator to create an array object. To declare an array, we use the square brackets and below is the general form -
int nums[];
And to create an array object, we use new operator, here is the syntax -
nums = new int[6];
We can integrate both statements into one statement -
int nums[] = new int[6];
The number in the square bracket represents the size / length of an array. The memory allocated for only number of elements, that array can hold, as determined by size. Then the reference to that memory is assigned to the array variable / object. So, an array is also called as a reference variable. Here below is the array of 6 int data type variables.

Index 0 1 2 3 4 5
nums[] 11 3 7 8 20 16

Each item is in array is called an element. And each element is accessed by numerical index starting from 0. Like in above example, to access the 5th element, you need to use the index number 4 in the square bracket like nums[4] and it will return its value as 15. As I mentioned earlier, array is an object. It has one data member / property length which tells the size of the array (total number of elements in an array) - nums.length

NOTE: Arrays start with index 0, means 1st element is - nums[0]

Arrays are used to store same kind of data in one variable and can be accessed by a common name. To assign values to an array, there are two ways. Either you assign values to each element separately like below -
int nums[] = new int[6];
nums[0] = 11;
nums[1] = 3;
nums[2] = 7;
nums[3] = 8;
nums[4] = 20;
nums[5] = 16;
Or you can assign the values in one line. The below statement automatically assigns the index to an array element and will be the same result as above.
int nums[] = {11, 3, 7, 8, 20, 16};
You can access an element of an array individually using directly the index number in square brackets.
System.out.println("nums[0]:" + nums[0]);
System.out.println("nums[1]:" + nums[1]);
System.out.println("nums[2]:" + nums[2]);
System.out.println("nums[3]:" + nums[3]);
System.out.println("nums[4]:" + nums[4]);
System.out.println("nums[5]:" + nums[5]);
Or you can access all the elements going through an array using the for loop and array's size - length property (specifies how many times loop is going to run).
for(int i = 0; i < nums.length; i++) {
    System.out.println("nums[" + i + "]:" + nums[i]);
}
The result will be same like as below:

nums[0]:11
nums[1]:3
nums[2]:7
nums[3]:8
nums[4]:20
nums[5]:16

NOTE: I have already covered for loops in my earlier posts. In above for loop, when printing I use i as an index and while printing I put + sign in println statement - it's called string concatenation. I will talk about it more later when discussing String class.

Wednesday, January 29, 2020

Java: Static Methods

Static methods / class methods are those methods which are a part of the class, but they don't need any object to be created. In each program, we have used a static method main(). So, being static, we don't need to create any object to call main method. It takes only one String argument.
public static void main(String args[])
So, why we need static methods. Sometimes, we have to add common functionality to the class but is not related to data fields. As static method belongs to a class, not to the object, it can access only static variables. And static methods can call only static methods. Let's see an example of static method.

Class StaticDemo (StaticDemo.java)
public class StaticDemo {
    static String hello = "Hello";
    public static void main(String args[]) {
        sayHello1();
        StaticDemo sd = new StaticDemo();
        sd.sayHello2();
    }

    static void sayHello1 () {
        System.out.println("Say " + hello);
    }

    void sayHello2 () {
        System.out.println("Say " + hello);
    }
}
In above program, we have two methods in addition to main method - sayHello1 (static) and sayHello2 (non-static). You can see that the methods are called from main method which is a static method. Static method sayHello1 is called directly as it is static method and we don't need to create an object. But to call non-static method, we created an object of class StaticDemo and then call the method. Here is the output!!

Say Hello

Say Hello

As I mentioned above static methods are called class methods and non-static methods are called instance methods. Class methods vs Instance methods -
  • Instance methods can access both static / non-static methods and variables directly. But static methods can access only static (class) methods and static (class) variables directly.
  • Static methods don't use this keyword. As static method belongs to the class, not an object, it doesn't have any reference of an object to use this keyword.

Tuesday, January 28, 2020

Java: Static Variables

In last post Classes and Objects, we discussed how to create an instance of class and how to access its variables and methods. But sometimes, you need a variable (data field) that is common to all the objects created. To achieve that, the static keyword is used to declare the variable. The variables declared as static are called static variables. Static variables are allocated memory only once and retain their values.

Class Student (Student.java)
public class Student {
    String name;
    int age;
    static int total = 0;

    Student(String name, int age) {
        this.name = name;
        this.age = age;
        total++;
    }
}
In above program, we have created a class named as Student. There are three variables - name, age and total (number of students). The variable total is declared as static and initialized with 0. Whenever a new object is created (constructor is called), the two variables name and age, are initialized and also the value of the variable total is incremented. 

Class StudentTest (StudentTest.java)
public class StudentTest {
    public static void main(String args[]) {
        Student s1 = new Student("John", 6);
        System.out.println("Student1 -");
        System.out.print("Name  : " + s1.name + ", ");
        System.out.print("age   : " + s1.age + ", ");
        System.out.println("Total : " + s1.total);
        System.out.println("");
        Student s2 = new Student("Adam", 9);
        Student s3 = new Student("Alex", 7);

        System.out.println("Student1 -");
        System.out.print("Name  : " + s1.name + ", ");
        System.out.print("age   : " + s1.age + ", ");
        System.out.println("Total : " + s1.total);
        System.out.println("");

        System.out.println("Student2 -");
        System.out.print("Name  : " + s2.name + ", ");
        System.out.print("age   : " + s2.age + ", ");
        System.out.println("Total : " + s2.total);
        System.out.println("");

        System.out.println("Student3 -");
        System.out.print("Name  : " + s3.name + ", ");
        System.out.print("age   : " + s3.age + ", ");
        System.out.println("Total : " + s3.total);
        System.out.println("");

        System.out.println("Student Total -");
        System.out.println(Student.total);
    }
}
In StudentTest class, we are creating 3 objects (instances) of class Student. When we print details, name and age are different for each student, but the value of the variable total is always 3, it doesn't matter which object is accessing it. The total variable is common to all the objects created. Here is the result of above program -

Student1 -
Name  : John, age   : 6, Total : 1

Student1 -
Name  : John, age   : 6, Total : 3

Student2 -
Name  : Adam, age   : 9, Total : 3

Student3 -
Name  : Alex, age   : 7, Total : 3

Student Total -
3

Please note the last statement of the program. We have used the class name directly to access the variable total. The result is same when you are accessing static variable using class name or object. Static variables can be accessed using class name, that's why these variables are also called class variables. Other variables are called instance variables.

Monday, January 27, 2020

Java: Classes and Objects

We already know about Object Oriented Programming and Packages, and also know how to use Scanner class form java.util package for getting inputs. And also have used System.out.println() method to print output. Java's API (Application Programming Interface) is a library of several packages, classes and interfaces etc. Let's explore more about classes and objects -

How to create own classes?
I have already explained in Object Oriented Programming, what is a class and what is an object. A class contains data and methods which act on the data. We have already seen how to create a class in Simple Program in JavaClass name can be any valid identifier. We have same restrictions on class names as the variables I mentioned in post Variable, Literals and Constants. CamelCase (first letter capital and other letters lowercase in each word used in name) method is used as a standard for naming classes.

Here is an example of a class Dog - 

Class Dog (Dog.java)
import java.awt.*;

public class Dog {
    int age;
    int size;
    Color color;
    String colorName;

    Dog(int age, int size, Color color) {
        this.age = age;
        this.size = size;
        this.color = color;
    }

    public int getAge() {
        return this.age;
    }

    public void bark() {
        System.out.println("Bark - woof, woof");
    }

    public Color getColor() {
        return this.color;
    }
}
In first line of the code, we have imported a package named java.awt, and we have used Color class from the package. We have created the class public, anyone can reuse this class. age, size, color and colorName - all variables are the data members of the class Dog. Dog(), getAge(), bark(), getColor() are method members of the class Dog

NOTE: In the class definition a keyword this is used to represents the reference of the current object (The object which invokes the method using the dot operator). As class variables and parameters have same name, using this keyword the program can differentiate between class variables and method parameters as both are accessible in the method.

So, we can take above program as template and can simplify the form of the class definition - 
import package;

public class [ClassName] {
    type var1;
    type var2;
    type var3;
    type var4;
    .......

    ClassName(parameters) {
       // body of method    }

    type method1(parameters) {
        return var;
    }

    type method2(parameters) {
    return var;
    }

    type method3(parameters) {
    return var;
    }
    .....
}
A class definition is just a prototype. And the variables and methods that constitute a class are called members of the class. You can see there is one method in above example which has same name as ClassName (Dog). That one is special method and is called as constructor method.

What are the methods?
A method consists the common code or functionality, to which the program can pass data through its parameters and can get some data in return. NOTE: When you pass a variable to a method, that is called an argument. But when a method receives a variable through calling, the variable is called parameter. The methods can be reused several times with different data. (there is no limit) You can pass any number of arguments (parameters) to a method from 0 too ..... any number. And but a method returns only one variable or no data. It can not return more than one variable. Suppose we have to get sum of two integer numbers -
public int sum(int a, int b) {
    int c = a + b;
    return c;
}
And if there are three numbers, you can define one more method with same name with three parameters. It is called method overloading. (NOTE: We will discuss overloading in more detail later.)
public int sum(int a, int b, int c) {
    int d = a + b + c;
    return d;
}
What are the Constructors?
Constructor methods are special methods. A constructor initializes an object when it is created. They have the same name as the class name. There is no need to specify return type for the constructor, as it always returns an instance of the class - an object. A class can have 0 or many constructors. When there is no constructor in the class definition, Java automatically provides a default constructor. Constructors also can be overloaded.

How to create an object?
To create an object from a class - you need to use the new operator with the constructor method. The new operator dynamically allocates (run time) memory for an object and returns a reference to it. To create an object, the general syntax is -
ClassName obj1 = new ClassName(parameter values);
Here is the example of creating an object of the class Dog. The 3 parameters are passed as per the class definition given above (age, size and Color). Calling this constructor sets or initializes the values of 3 class variables age, size and color. -
Dog dog1 = new Dog(3, 4, Color.WHITE);
How to access class variables and methods?
To access class variables and methods the . (dot) operator is used. Like to access age and size of dog1, we should assign the class variable values to same data type as the variable is of.

int a = dog1.age;
int b = dog1.size;

System.out.println("Dog's age: " + a);
System.out.println("Dog's size: " + b);
And to access methods of dog1, we should assign method to the variable of return data type. If there is none return data type (void) then you don't need to assign, just call the method using . (dot) operator.

a = dog1.getAge();

System.out.println("Dog's age: " + a);

dog1.bark();
Whole program will look like this - 
// Class definition Dog.java
import java.awt.*;

public class Dog {
    int age;
    int size;
    Color color;
    String colorName;

    Dog(int age, int size, Color color) {
        this.age = age;
        this.size = size;
        this.color = color;
    }

    public int getAge() {
        return this.age;
    }

    public void bark() {
        System.out.println("Bark - woof, woof");
    }

    public Color getColor() {
        return this.color;
    }
}
/* To test class Dog - DogTest.java (entry point is main method as we have discussed before in our earlier posts */
public class DogTest {
    public static void main(String args[]) {
        Dog dog1 = new Dog(3, 4, Color.WHITE);

        int a = dog1.age;
        int b = dog1.size;

        System.out.println("Dog's age: " + a);
        System.out.println("Dog's size: " + b);

        a = dog1.getAge();

        System.out.println("Dog's age: " + a);

        dog1.bark();
    }
}

Saturday, January 25, 2020

Java: Let's practice - multiplication table

Problem : Write a Java program to print the multiplication table for user entered number.

Solution:

Class Multiplication (Multiplication.java)
import java.util.Scanner;

public class Multiplication {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number for multiplication table");
        int num = sc.nextInt();
        int mul = 0;
        for(int i = 1; i <= 10; i++) {
            mul = num * i;
            System.out.println(num + "  *  " + i + "  =  " + mul);
        }
    }
}

Enter the number for multiplication table
19
19  *  1  =  19
19  *  2  =  38
19  *  3  =  57
19  *  4  =  76
19  *  5  =  95
19  *  6  =  114
19  *  7  =  133
19  *  8  =  152
19  *  9  =  171
19  *  10  =  190

Java: Let's Solve some problems

Problem : Write a program in which user enters a number. Through while / do-while loop, count by 1 starting from 0 till the entered number and get sum of all the consecutive numbers. 

Class WhileSum (WhileSum.java)
import java.util.Scanner;

public class WhileSum {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number you want sum till");
        int number = sc.nextInt();
        int i = 1, sum = 0;
        while(i <= number) {
            sum += i;
            System.out.print(i + " ");
            i++;
        }
        System.out.println();
        System.out.println("Sum = " + sum);
    }
}
Problem : What will be the output of the following program?

Class BreakContinue (BreakContinue.java)
public class BreakContinue {
    public static void main(String args[]) {
        int sum = 0;
loop1:  for (int j = 10; j >= 1; j--) {
loop2:      for (int i = 1; i < 10; i++) {
                if (i == 2*j) {
                    System.out.println(i + " : " + j);
                    System.out.print("Continue");
                    System.out.println();
                    continue;
                }
                if (i == 4*j) {
                    System.out.println(i + " : " + j);
                    System.out.print("Break");
                    System.out.println();
                    break loop1;
                }
            }
        }
    }
}
Solution : 
8 : 4
Continue
6 : 3
Continue
4 : 2
Continue
8 : 2
Break

Exercise: What will be the correct result of following expression?
6 + 5 * 2 + 3 == 9 * 3 / 2 + 6 || false

Solution : 
6 + 5 * 2 + 3 == 9 * 3 / 2 + 6 || false =>
((6 + (5 * 2) + 3) == (((9 * 3) / 2) + 6)) || false =>
((6 + 10 + 3) == ((27 / 2) + 6)) || false =>
(19 == (13 + 6)) || false =>
(19 == 19) || false =>
true || false =>
true

Exercise: Are following variable names are legal / illegal?
  1. word123
  2. 23five.     X
  3. _next.      
  4. &6next_five.  X

Friday, January 24, 2020

Java: Comments

When you work on bigger projects, more than one programmers might be needed and other projects also can reuse the classes / packages / methods etc. in their projects. Always the code is not obvious. To make it readable and understandable, comments are added in between the code, wherever explanation is required. The compiler ignores the comments altogether. There are 3 kinds of comments -

Single Line Comment - It starts with // and only line is ignored.
// This is pi value used in all math programs.
final double pi = 3.14;
Multi Line / Block Comment - It starts with /* and ends with */ and between those symbols - all text is ignored.

/* This code is commented
System.out.println("Done"); 
*/
Javadoc Comment - It starts with /** and ends with */ and each line will start with *. Javadoc is a tool with JDK that generates HTML documentation from comments written in source code.

/**
 * This comment goes to javadoc
 */
NOTE: We will talk about java doc implementation more later.

Thursday, January 23, 2020

Java: Variables / Literals / Constants

In all the programs we have written, we used variables and literal values. So, what are the variables? 

Variable
A variable is a named storage, which can be manipulated by the programs. As we know through our earlier post, what are the binary values. The data is stored in memory in the form of binary values. In the program, we declare the variables of specific type, and variable holds memory (in no of bits) according to the data type, as each data type can have different memory size and their representation in bits.

We also learnt about the data types. To specify the data type for a variable is called a variable declaration. And when you give a value to the variable, that is called initialization (when it is done first time) or assignment (replacing old value with new value). Here is the syntax -
int i = 5;
int j;
j = 10;
Every data type variable has default values if not initialized. There are some rules for naming the variables to be followed -
  • Variable names should start with a letter (a to z / A to Z), currency character $ or an underscore.
  • Variable names can have combinations of any kind of characters (alphabets, numbers or special characters).
  • Variable names can not be key words in Java given in the following table.
  • Variable names are case-sensitive.

The Java keywords

abstract assert boolean break byte case catch
class const continue default do double else
enum exports extends final finally float for
goto if implements import instanceof int interface
long goto module native new open opens
package private protected provides public requires return
short static strictfp super switch synchronized this
throw throws to transient transitive try uses
void volatile while with null true false


Literals
The constant values given to or assigned to the variables are called literals. Like in above example - number 5 and 10 are literal values.

Constants
When you want a variable to hold a value which should not be changed in the program or outside the program (accessing from other programs) by any means, declare the variable as final. So when you declare the variable as final, it is called as constant variable and will remain unchanged. 
final double pi = 3.14;

Wednesday, January 22, 2020

Java: Precedence of operators

We have learnt about all the operators - Arithmetic OperatorsAssignment OperatorsRelational OperatorsLogical OperatorsBitwise Operators and Conditional Operator in my earlier posts. But when there are more than one operator in one expression, there is some precedence. Whoever has studied mathematics, I think they know BODMAS (Brackets first,  Orders 'Powers or Square Roots', Division and Multiplication, Addition and Subtraction) rule to solve the equations. Same thing applies here. Here is the list of precedence of operators in Java -

CategoryOperatorAssociativity
Postfixexpression++ expression--Left to right
Unary++expression –-expression +expression –expression ~ !Right to left
Multiplicative* / %Left to right
Additive+ -Left to right
Shift<< >> >>>Left to right
Relational< > <= >= instanceofLeft to right
Equality== !=Left to right
Bitwise AND&Left to right
Bitwise XOR^Left to right
Bitwise OR|Left to right
Logical AND&&Left to right
Logical OR||Left to right
Conditional?:Right to left
Assignment= += -= *= /= %= ^= |= <<= >>= >>>=Right to left
Here is an example below -

8 - 2 * 3 = 6 * 3 = 18 X Wrong

8 - 2 * 3 = 8 - 6 = 2   √ Right

Here is another example -

false && true == false => false == false => true    X Wrong

false && true == false => false && false => false  √ Right

NOTE: instanceof operator is related to classes and objects. We will talk about it later.

Tuesday, January 21, 2020

Java: Break and Continue

We saw in last posts, how for, while and do-while loops control the program flow and how the program exits after the condition is met. But there are two more statements, which can skip statements as needed and allow the program to come out of the loop without meeting condition criteria.

Break Statement break;
One is the break statement, which we have already used in switch-case statements. If you don't use break statement in switch-case statement, the program will keep executing other case statements, as program doesn't know where to stop. We can use break statements with for, while and do-while loops too. In the loop, break statement allows the program to come out from the immediate loop and executes next statement after loop.

Suppose we have to add all the numbers starting from 1 till the sum becomes 100. We will write a program with for loop adding all the numbers, and as soon as the sum reaches 100, the program will exit from the for loop with the help of break statement.

Class BreakExample1 (BreakExample1.java)
public class BreakExample1 {
    public static void main(String args[]) {
        int sum = 0;
        for(int i = 1; i < 20; i++) {
            sum = sum + i;
            if(sum >= 100) break;
            System.out.print(i + " ");
        }
    }
}
And here is the result:

1 2 3 4 5 6 7 8 9 10 11 12 13

The program came out from the for loop as soon as the value of variable sum is greater than 100, it didn't completed all the possible iterations (i < 20).

Suppose we have asked the user to enter only single digit numbers, as soon as he enters 0 or more than 1 digit number, the program comes out from the loop and prints the last entered number. We have used here break statement with the while loop.

Class BreakExample2 (BreakExample2.java)
import java.util.Scanner;

public class BreakExample2 {
    public static void main(String args[]) {
        int i, last = -1;
        System.out.println("Please enter single digit numbers only");
        Scanner sc = new Scanner(System.in);
        do {
            i = sc.nextInt();
            if((i == 0) || (i >= 10)) {
                System.out.println("Stop");
                break;
            }
            last = i;
        } while(true);
        if(last == -1) System.out.println("Last entered number is none");
        else System.out.println("Last entered number is " + last);
    }
}
And here is the result:

Please enter single digit numbers only
4
3
2
9
11
Stop

Last entered number is 9

There is one more form of break statement - break statement with label. This kind of break statement is used when there are nested loops (loop in a loop). So, you can label all the loops, and when you specified the label with break statement, the program will come out from the specified loop or only the innermost loop if not specified. It's syntax is -

break label;

Here in the example, I have created two labels for two different for loops. And I have used break statement with label name. The program exits from the outer loop.

Class BreakExample3 (BreakExample3.java)
public class BreakExample3 {
    public static void main(String args[]) {
        int sum = 0;
loop1:  for (int j = 10; j >= 1; j--) {
loop2:      for (int i = 1; i < 10; i++) {
                if (i == 2*j) {
                    System.out.println(i + " : " + j);
                    System.out.print("Done");
                    System.out.println();
                    break loop1;
                }
            }
        }
    }
}
Result is:

8 : 4 Done

But, if I remove the label from the break statement, different results will come. Here you can see the difference.

Class BreakExample4 (BreakExample4.java)
public class BreakExample4 {
    public static void main(String args[]) {
        int sum = 0;
loop1:  for (int j = 10; j >= 1; j--) {
loop2:      for (int i = 1; i < 10; i++) {
                if (i == 2*j) {
                    System.out.println(i + " : " + j);
                    System.out.print("Done");
                    System.out.println();
                    break;
                }
            }
        }
    }
}
Result is:

8 : 4
Done
6 : 3
Done
4 : 2
Done
2 : 1
Done

And if we write label after for statement but before opening braces {, the different result will come. So, you have to be careful where to put labels. And break statement can only break the labeled loop if it is enclosed by same label.

Class BreakExample5 (BreakExample5.java)
public class BreakExample5 {
    public static void main(String args[]) {
        int sum = 0;
  for (int j = 10; j >= 1; j--) loop1: {
loop2:      for (int i = 1; i < 10; i++) {
                if (i == 2*j) {
                    System.out.println(i + " : " + j);
                    System.out.print("Done");
                    System.out.println();
                    break loop1;
                }
            }
        }
    }
}
Result is same here:

8 : 4
Done
6 : 3
Done
4 : 2
Done
2 : 1
Done

Continue Statement continue;
Continue statements allow the program to skip remaining statement after it and goes to next iteration / condition expression of the loop. Th program doesn't come out from the loop until the condition is false or there is a break statement.

I got one question in 4th grade math book. I tried to write a program to solve the question using continue statement. Q: What is the least multiple of 9 that is greater than 150?

Class ContinueExample (ContinueExample.java)
public class ContinueExample {
    public static void main(String args[]) {
        for(int i = 1; i <= 20; i++) {
            if(9*i < 150) continue;
            System.out.print(9*i + " ");
        }
    }
}
And the results is showing all the possible multiples after 150. So, the least multiple is the smallest number - 153.

153 162 171 180