Friday, 23 June 2017

Java Methods

Methods:

A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilizing the method's name. Think of a method as a subprogram that acts on data and often returns a value.

Method definition consists of a method header and a method body. The same is shown in the following syntax −

Syntax:


modifier returnType nameOfMethod (Parameter List) { 
  // method body 
} 
The syntax shown above includes −

modifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters.
Method body − The method body defines what the method does with the statements.


Each method has its own name. When that name is encountered in a program, the execution of the program branches to the body of that method. When the method is finished, execution returns to the area of the program code from which it was called, and the program continues on to the next line of code.

Good programmers write in a modular fashion which allows for several programmers to work independently on separate concepts which can be assembled at a later date to create the entire project. The use of methods will be our first step in the direction of modular programming.

Methods are time savers, in that they allow for the repetition of sections of code without retyping the code. In addition, methods can be saved and utilized again and again in newly developed programs.

You are using methods when you use:


System.out.print( ) and System.out.println( )


void Keyword:

The void keyword allows us to create methods which do not return a value. In case we want to create a method which does not return any value then the return type should be void but not left empty.

Main Method:

This is very important method in a Java application. Any Java application must contain a main() method whose signature looks like this,

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

A Java program needs to start its execution somewhere. A Java program starts by executing the main method of some class. You can choose the name of the class to execute, but not the name of the method. The method must always be called main. Here is how the main method declaration looks when located inside the Java class declaration; 

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

The three keywords public, static and void have a special meaning which is,

public - The main method is called by the JVM to run the method which is outside the scope of the project therefore the access specifier has to be public to permit a call from anywhere outside the application.

static - When the JVM makes a call to the main method there is no object that exists for the class being called therefore it has to have static method to allow invocation from class.

void - Java is a platform independent language, therefore if it returns some value, then the value may have a different meaning between different platforms so unlike C it can not assume a behavior of returning value to the operating system.
After the three keywords you have the method name.

After the method name comes first a left parenthesis, and then a list of parameters. A main method must always take an array of String objects. 

Types of Methods:

There are two basic types of methods:

Built-in: Build-in methods are part of the compiler package, such as System.out.println( ) and System.exit(0).

User-defined: User-defined methods are created by you, the programmer. These methods take-on names that you assign to them and perform tasks that you create.

How to invoke (call) a method (method invocation):

When a method is invoked (called), a request is made to perform some action, such as setting a value, printing statements, returning an answer, etc. The code to invoke the method contains the name of the method to be executed and any needed data that the receiving method requires. The required data for a method are specified in the method's parameter list.



Consider this example:

public class Student {

 static int regNo = 12345;

 public static void getStudentAge(int age) {
  System.out.println("Age: " + age);
 }

 public static void getStudentName() {
  System.out.println("Name: XYZ");
 }

 public static void main(String[] args) {
  getStudentAge(20);
  getStudentName();
 }
}

Output:
Age: 20
Name: XYZ

The method name is getStudentAge() and getStudentName() which are defined in the same class Student. Since we are calling both the methods with their declared name one after one in main method, first getStudentAge() will be executed, when finished getStudentName() starts to execute.


Passing Parameters(arguments):

When a method is expecting any arguments is to be passed, then you must pass those arguments to that method These should be in the same order and same type as their respective parameters in the method specification.

In above example method getStudentAge is expecting a parameter, so the caller must send the parameter to that method when calling, like getStudentAge(20). If in case same method is expecting a String as a parameter than a string value should be sent.


Most importantly we can create 2 types of methods.
  • Static Methods
  • Instance Methods

Static Methods:

Static methods are which have the static modifier in their declarations.

public static void getStudentAge() {
    ....
}

Static method should be invoked with the class name, without the need for creating an instance of the class, as in,

ClassName.methodName(args);

If you observe above example properly we are calling the methods without using the class name Student. But it should have been called like, 

Student.getStudentAge(20);

We have not used the class name because it's in the same class. If a static method is available in the same class or in the super class in case inheritance, then that method can be accessed directly with the method name.

But what if a static method is not in the calling class?


If a static method is not available in the calling class in case you are not extending(inheriting) it should be invoked with the class name, without the need for creating an instance of the class, as in,



ClassName.methodName(args);

Consider below example for this case:

class  Student{

 public static void getStudentAge(int age) {
  System.out.println("Age: " + age);
 }
}

public class School{
 public static void getRegNo() {
  System.out.println("Reg: 12345");
 }

 public static void main(String[] args) {
  getRegNo();
  Student.getStudentAge(20);//Invoking the method using class name as 
                                          //it is located in another class
 }
}
Output:
Age: 20 Reg: 12345


Instance Methods:

If it's not a static method then it's an instance method.
Instance method are methods which require an object of its class to be created before it can be called. To invoke a instance method, we have to create an Object of the class in within which it defined.

Consider the same example above, in case static is not used to declare the methods.


class  Student{

 public  void getStudentAge(int age) {
  System.out.println("Age: " + age);
 }
}

public class School{
 public  void getRegNo() {
  System.out.println("Reg: 12345");
 }

 public static void main(String[] args) {
  //Create object for School class to access it's instance methods
  School school = new School();
  school.getRegNo();
  
  //Create object for Student class to access it's instance methods
  Student student = new Student();
  student.getStudentAge(20);
 }
}
Output:
Age: 20 Reg: 12345

In above example getStudentAge()  is created as an instance method thus we created an object for the class Student in which the method exists and accessed in another class in a main method. 

But if observe properly, we are also accessing the method getRegNo() which is in the same calling class School and we are creating an object for that class in order to access it. 

But in case of static method within the same calling class we were accessing directly with name. It's because we cannot access instance variables or methods in a static method without creating an object of the class in which instance method exists. Here we are trying to access getRegNo() instance method within a static main method, so we have to create an object to access it.

You can access any instance methods directly with it's name without creating an object of it's class only in another instance method of class assuming both are in same class or you are accessing a instance method of a superclass in a subclass instance method.

Summary:
  • If a static method is not available in the calling class in case you are not extending(inheriting) it should be invoked with the class name, without the need for creating an instance of the class.
  • If a static method is available in the same class or in the super class in case inheritance, then that method can be accessed directly with the method name.
  • We cannot access instance variables or methods in a static method without creating an object of the class in which instance method exists
  • You can access any instance methods directly with it's name without creating an object of it's class only in another instance method of class assuming both are in same class or you are accessing a instance method of a superclass in a subclass instance method.
  • You can access any static method in an instance method directly with it's name in case it's available in the same class or superclass. If static method is in another class it should be accessed with it's class name assuming the class is not a superclass.

Characters, Strings & Arrays

Characters:

Most of the time, if you are using a single character value, you will use the primitive char type. For example:

//Single char
char ch = 'a';
// an array of chars 
char[] charArray = { 'a', 'b', 'c', 'd', 'e' }; 

There are times, however, when you need to use a char as an object—for example, as a method argument where an object is expected. The Java programming language provides a wrapper class that "wraps" the char in a Character object for this purpose. An object of type Character contains a single field, whose type is char. This Character class also offers a number of useful class (i.e., static) methods for manipulating characters.

You can create a Character object with the Character constructor:

Character ch = new Character('a');

Useful Methods in the Character class

Escape Sequences:

A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. The following table shows the Java escape sequences:


Escape SequenceDescription
\tInsert a tab in the text at this point.
\bInsert a backspace in the text at this point.
\nInsert a newline in the text at this point.
\rInsert a carriage return in the text at this point.
\fInsert a formfeed in the text at this point.
\'Insert a single quote character in the text at this point.
\"Insert a double quote character in the text at this point.
\\Insert a backslash character in the text at this point.

Strings:

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings:


The most direct way to create a string is to write:

String greeting = "Hello world!";

In this case, "Hello world!" is a string literal—a series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value—in this case, Hello world!.

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has thirteen constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' }; 
String helloString = new String(helloArray); 
System.out.println(helloString);

Output:
hello

String Length:

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. Example below will illustrate this.


public class StringsDemo {

  public static void main(final String[] args) {
    String palindrome = "How are you";
    int len = palindrome.length();
    System.out.println(len);
  }
}

Output:
11



Arrays:

Which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Arrays in Java are also objects. They need to be declared and then created. In order to declare a variable that will hold an array of integers, we use the following syntax:

int[] arr = new int[10];

This will create a new array with the size of 10. We can check the size by printing the array's length:

public class ArraysDemo {

  public static void main(final String[] args) {
    final int[] arr = new int[10];
    System.out.println(arr.length);
    }
}

Output:
10

We can access the array and set values and print them,

public class ArraysDemo {

  public static void main(final String[] args) {
    final int[] arr = new int[5];
    arr[0] = 1;
    arr[1] = 2;
    arr[2] = 3;
    arr[3] = 4;
    arr[4] = 5;
    for (int i = 0; i < arr.length; i++) {
      System.out.println(arr[i]);
    }
    }
}

Output:
1
2
3
4
5

Arrays index starts with 0 but not 1, which means the first element in an array is accessed at index 0 (e.g: arr[0], which accesses the first element). Also, as an example, an array of size 5 will only go up to index 4 due to it being 0 based. What happens if you try to access

We can also create an array with values in the same line:

public class ArraysDemo {

  int[] arr = {1, 2, 3, 4, 5};
    for (int i = 0; i < arr.length; i++) {
      System.out.println(arr[i]);
    }
}

Output:
1
2
3
4
5

Don't try to print the array without a loop, it will print the object code but not the values.

Passing Arrays to Methods:

Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array:

public void processArray(int[] array) {
   ....
}




Decision making statement:

Decision making statement means a condition block need to be executed or not which is decided by condition. If the condition is "true" statement block will be executed, if condition is "false" then statement block will not be executed. In java there are three types of decision making statement.
  • if
  • if-else
  • switch
if-then is most basic statement of Decision making statement. It tells to program to execute a certain part of code only if particular condition is true.

Syntax:
if (condition) {
    Statement(s)
}

Example if statement,

public class Hello {
    int a = 10;
    public static void main(String[] args) {
        if (a < 15) {
            System.out.println("a is less than 15");
        }
    }
}

Output:
a is less than 15

if-else statement:

In general it can be used to execute one block of statement among two blocks, in java language if and else are the keyword in java.
Syntax:

if (condition) {
    Statement(s)
} else {
    Statement(s)
}........

In the above syntax whenever condition is true all the if block statement are executed, remaining statement of the program by neglecting. If the condition is false else block statement executed and neglecting if block statements.
Example if else,


import java.util.Scanner;
public class GreaterOrLess {
    public static void main(String[] args) {
        int no = 10;
        
        if (no > 15) {
            System.out.println("Number is greatger than 15");
        } else {
            System.out.println("Number is less than 15");
        }
    }
}

Output:

Number is less than 15

Switch Statement:

The switch statement in java language is used to execute the code from multiple conditions or case. It is same like if else-if ladder statement.

A switch statement work with byte, short, char and int primitive data type, it also works with enumerated types and string.

Syntax:

switch(expression/variable)
{
 case  value:
 //statements
 // any number of case statements
 break;  //optional
 default: //optional
 //statements
}

Rules for apply switch statement:

With switch statement use only byte, short, int, char data type (float data type is not allowed). You can use any number of case statements within a switch. Value for a case must be same as the variable in switch.

Limitations of switch statement:

Logical operators cannot be used with switch statement. For instance, k>=20: // not allowed

Example of switch case,


import java.util.*;
class switchCase {
    public static void main(String arg[]) {
        int ch;
        System.out.println("Enter any number (1 to 7) :");
        Scanner s = new Scanner(System.in);
        ch = s.nextInt();
        switch (ch) {
            case 1:
                System.out.println("Today is Monday");
                break;
            case 2:
                System.out.println("Today is Tuesday");
                break;
            case 3:
                System.out.println("Today is Wednesday");
                break;
            case 4:
                System.out.println("Today is Thursday");
                break;
            case 5:
                System.out.println("Today is Friday");
                break;
            case 6:
                System.out.println("Today is Saturday");
                break;
            case 7:
                System.out.println("Today is Sunday");
            default:
                System.out.println("Only enter value 1 to 7");
        }
    }
}

Output

Enter any number(1 to 7): 5 Today is Friday

Loop Control statements: 

Loops enable your program to conditionally execute particular blocks of code multiple times.

Looping statements are the statements execute one or more statements repeatedly several number of times. In java programming language there are three types of loops; while, for and do-while.


Why use loop?
When you need to execute a block of code several number of times then you need to use looping concept. 

In java programming language there are three types of loops; 
  • for 
  • while 
  • do-while
for loop:

for loop is a statement which allows code to be repeatedly executed. For loop contains 3 parts Initialization, Condition and Increment or Decrements

Syntax:

for (initialization; condition; increment) {
    statement(s);
}

Initialization: This step is executed first and executed only once when we are entering into the loop first time. This step will allow to declare and initialize any loop control variables.

Condition: This is next step after initialization step, if it is true, the body of the loop is executed, if it is false then the body of the loop does not execute and flow of control goes outside of the for loop.

Increment or Decrements: After completion of Initialization and Condition steps loop body code is executed and then Increment or Decrements steps is execute. This statement allows to update any loop control variables.
  • First initialize the variable
  • In second step check condition
  • In third step control goes inside loop body and execute.
  • At last increase the value of variable
  • Same process is repeat until condition not false.

Example of for loop:

Display any message exactly 5 times.
class Hello {
    public static void main(String args[]) {
        int i;
        for (i = 0: i < 5; i++) {
            System.out.println("Hello Friends !");
        }
    }
}

Output:
Hello Friends!Hello Friends!Hello Friends!Hello Friends!Hello Friends!


For-each loop (Advanced or Enhanced For loop):

The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.

Syntax of for-each loop:


for(data_type variable : array | collection){}

Simple Example of for-each loop for traversing the array elements:

public class ForEachArraysExample{  
  public static void main(String args[]){  
   int arr[]={1, 2, 3, 4, 5};  
  
   for(int i:arr){  
     System.out.println(i);  
   }  
  
 }   
}
Output:
1
2
3
4
5

Simple Example of for-each loop for traversing the ArrayList elements:

import java.util.*;  
public class ForEachListExample{  
  public static void main(String args[]){  
   List<String> list=new ArrayList<>();  
   list.add("foo");  
   list.add("blah");  
   list.add("wow");  
  
   for(String s:list){  
     System.out.println(s);  
   }  
  }   
} 

Output:
foo
blah
wow 


While loop:

In while loop first check the condition if condition is true then control goes inside the loop body otherwise goes outside of the body. while loop will be repeats in clock wise direction.

Syntax:

while (condition) {
    Statement(s) Increment / decrements(++or--);
}

Example while loop,

class whileDemo {
    public static void main(String args[]) {
        int i = 0;
         while (i < 5) {
            System.out.println(+i);
            i++;
         }
    }
}

Output:
1 2 3 4 5

do-while:

A do-while loop is similar to a while loop, except that a do-while loop is execute at least one time.

A do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given condition at the end of the block (in while).

When use do..while loop?
when we need to repeat the statement block at least one time then use do-while loop. In do-while loop post-checking process will be occur, that is after execution of the statement block condition part will be executed.

Syntax:

do {
    Statement(s) increment / decrement(++or--)
} while ();

In below example you can see in this program i=20 and we check condition i is less than 10, that means condition is false but do..while loop execute onec and print Hello world ! at one time.

Example do..while loop,

class dowhileDemo {
    public static void main(String args[]) {
        int i = 20;
        do {
            System.out.println("Hello world !");
            i++;
        } while (i < 10);
    }
}

Output: 
Hello world !


Another example of do..while loop where condition is satisfied,


class dowhileDemo {
    public static void main(String args[]) {
        int i = 0;
        do {
            System.out.println(+i);
            i++;
        } while (i < 5);
    }
}

Output:
    1 2 3 4 5