Tuesday, 6 February 2018

HOW & WHEN "GROUP_CONCAT" GROUP FUNCTION IS USED ? - MYSQL

This article explains various scenarios where GROUP_CONCAT group function should be used.

Scenario: 1

Sometimes, we need some requirements like concatenating two or more rows with a delimiter.

Example:

Following table shows the data of all the customers of a Life Insurance Company, who paid the premiums of their selected policies.

Table_Name: Customer_Payments

Payment_No CustomerCustomer_IdPaymentsPolicy_TypePayment_date
00001Ramesh11000012018-02-01 03:26:30
00002Rajesh210000022018-02-01 03:27:00
00003Ramesh13000022018-02-01 03:30:33
00004Geeta32500012018-02-01 03:28:31

If your requirement is to find total amounts paid by the Customers along with list of policies holding by each & every customer. Here, the list of Policies holding by a Customer is showed with a delimiter comma.

Firstly, we need to group the Customer using Customer_Id

So,

SELECT Customer_Id, SUM(Payments) AS "Total Payment"
FROM Customer_Payments
GROUP BY Customer_Id;

Query Result:

Customer_IdTotal Payment
14000
210000
32500


The above query fetches the consolidated payments done by each Customer.

Now, you use GROUP_CONCAT(Policy_Type) in the SELECT clause to get the comma-separted list of Policies.

So,

SELECT Customer_Id, SUM(Payments) AS "Total Payment", GROUP_CONCAT(Policy_Type) AS "List Of Polices"
FROM Customer_Payments
GROUP BY Customer_Id;

Query Result:


Customer_Id Total PaymentList Of Policies
1400001,02
21000002
3250001

Here, this means, Customer with Id 1, has 2 policies (01, 02) paid a total of 4000, Customer 2 has one policy (02) paid an amount 10000, & Customer 3 has one policy (01) paid an amount of 2500.

Note: By default, comma is the delimiter for GROUP_CONCAT group function. 

You can choose your own delimiter for concatenation. This can be done using a SEPARATOR clause inside the GROUP_CONCAT group function.

Example:

SELECT Customer_Id, SUM(Payments),  
GROUP_CONCAT(Policy_Type SEPARATOR '^^^') AS "List Of Policies"
FROM Customer_Payments 
GROUP BY Customer_Id;

Query Result:

Customer_IdTotal PaymentList Of Policies
1400001^^^02
21000002
3250001

The SEPARATOR should be positioned always last inside the GROUP_CONCAT. Otherwise, you will end up with errors.

Example:

SELECT Customer_Id, SUM(Payments),
GROUP_CONCAT(Policy_Type ORDER BY Policy_Type DESC SEPARATOR '^^^')
FROM Customer_Payments
GROUP BY Customer_Id;

Query Result:


Customer_IdTotal PaymentList Of Policies
1400002^^^01
21000002
3250001

ORDERING WITH GROUP_CONCAT:

Sometimes, we also want list of policies separated by comma-separated in a specfic order. To do that, you have to use ORDER BY clause inside the GROUP_CONCAT group function.

Example:

SELECT Customer_Id, SUM(Payments) AS "Total Payment", 
GROUP_CONCAT(Policy_Type ORDER BY Policy_Type DESC) AS "List Of Polices"
FROM Customer_Payments
GROUP BY Customer_Id;

Now, observe the Query Results:

Customer_IdTotal PaymentList Of Policies
1400002,01
21000002
3250001

For the first customer, having more than one policy, the policy numbers are now listed in DESCENDING order (02,01).

Scenario: 2
 
Lets consider that, we want the consolidated payments sorted by most recent payment: this can be done by sorting the data using Payment_Date

Example:

Table_Name: Customer_Payments

Payment_No CustomerCustomer_IdPaymentsPolicy_TypePayment_date
00001Ramesh11000012018-02-01 03:26:30
00002Rajesh210000022018-02-01 03:27:00
00003Ramesh13000022018-02-01 03:30:33
00004Geeta32500012018-02-01 03:28:31

Please observe how we can build this Query. As we want the consolidated & most recent payers. So, we need to GROUP BY Customer.

So,

SELECT Customer_Id, SUM(Payments) AS "Total Payment", GROUP_CONCAT(Policy_Type) AS "List Of Policies"
FROM Customer_Payments
GROUP BY Customer_Id;

You need to add sorting logic to the query using the Column "Payment_date", but, as "Payment_date" is not in the GROUP BY clause, you can order by using the GROUP_CONCAT function in ORDER BY clause also.

So, before using GROUP_CONCAT with Payment_date column in ORDER_BY clause, lets see, how it fetches the data in SELECT clause.

SELECT Customer_Id, SUM(Payments) AS "Total Payment", GROUP_CONCAT(Policy_Type) AS "List Of Policies",
GROUP_CONCAT(Payment_date) AS "Payment Date"
FROM Customer_Payments
GROUP BY Customer_Id;

Query Results:

Customer_IdTotal PaymentList Of PoliciesPayment Date
1400002,012018-02-01 03:26:30,2018-02-01 03:30:33
21000022018-02-01 03:27:00
3250012018-02-01 03:28:31
 
Now, you use GROUP_CONCAT in ORDER BY Clause:

SELECT Customer_Id, SUM(Payments) AS "Total Payment", GROUP_CONCAT(Policy_Type) AS "List Of Policies",
GROUP_CONCAT(Payment_date) AS "Payment Date"
FROM Customer_Payments
GROUP BY Customer_Id
ORDER BY GROUP_CONCAT(Payment_date ORDER BY Payment_date DESC);

Here, Overall Sorting Order: ASCENDING

Customer_IdTotal PaymentList Of policiesPayment Date
210000022018-02-01 03:27:00
32500012018-02-01 03:28:31
1400002,012018-02-01 03:26:30,2018-02-01 03:30:33

Here, the consolidated data is sorted in ASCENDING order (Overall Query Sorting is in ASCENDING ORDER), Please observe the first Payment Date "2018-02-01 03:27:00". Whereas,  In the group concatenated Payment Date, for instance, last row in result set, 2018-02-01 03:26:30,2018-02-01 03:30:33, out of these two dates,  2018-02-01 03:30:33 is considered, that is because GROUP concatenation done by Payment_dates & sorted in DESCENDING order, while the overall query sorting is in ASCENDING order.

Important Note:

There is much difference in these statements:

ORDER BY GROUP_CONCAT(Payment_date ORDER BY Payment_date DESC) - In the comma-separted list of payment dates 2018-02-01 03:30:33 is considered in the overall sorting.

ORDER BY GROUP_CONCAT(Payment_date ORDER BY Payment_date) - In the comma-separted list of payment dates 2018-02-01 03:26:30 is considered in the overall sorting.

So,

SELECT Customer_Id, SUM(Payments) AS "Total Payment", GROUP_CONCAT(Policy_Type) AS "List Of Policies",
GROUP_CONCAT(Payment_date) AS "Payment Date"
FROM Customer_Payments
GROUP BY Customer_Id
ORDER BY GROUP_CONCAT(Payment_date ORDER BY Payment_date);

Overall Sorting Order: ASCENDING

Observe the Query Results(especially the Payment Date)

Customer_IdTotal PaymentList Of policiesPayment Date
1400002,012018-02-01 03:26:30,2018-02-01 03:30:33
210000022018-02-01 03:27:00
32500012018-02-01 03:28:31

Here, the consolidated data is sorted in ASCENDING order (Overall Query Sorting is in ASCENDING ORDER). Whereas,  In the group concatenated Payment Date, for instance, first row in result set, 2018-02-01 03:26:30,2018-02-01 03:30:33, out of these two dates,  2018-02-01 03:26:30 is considered, that is because GROUP concatenation done by Payment_dates & sorted in ASCENDING order, & the overall query sorting is also in ASCENDING order.

SELECT Customer_Id, SUM(Payments) AS "Total Payment", GROUP_CONCAT(Policy_Type) AS "List Of Policies",
GROUP_CONCAT(Payment_date) AS "Payment Date"
FROM Customer_Payments
GROUP BY Customer_Id
ORDER BY GROUP_CONCAT(Payment_date ORDER BY Payment_date DESC) DESC;

Overall Sorting Order: DESCENDING

Query Results:

Customer_IdTotal PaymentList Of policiesPayment Date
1400002,012018-02-01 03:26:30,2018-02-01 03:30:33
32500012018-02-01 03:28:31
210000022018-02-01 03:27:00

Here, the consolidated data is sorted in DESCENDING order (Overall Query Sorting is in DESCENDING ORDER). Whereas,  In the group concatenated Payment Date, for instance, first row in result set, 2018-02-01 03:26:30,2018-02-01 03:30:33, out of these two dates,  2018-02-01 03:30:33 is considered, that is because GROUP concatenation done by Payment_dates & sorted in DESCENDING order, & the overall query sorting is also in DESCENDING order.

Now, change the Sorting Order in GROUP_CONCAT of Payment_date to ASCENDING without changing the Overall sorting order from DESCENDING.

SELECT Customer_Id, SUM(Payments) AS "Total Payment", GROUP_CONCAT(Policy_Type) AS "List Of Policies",
GROUP_CONCAT(Payment_date) AS "Payment Date"
FROM Customer_Payments
GROUP BY Customer_Id
ORDER BY GROUP_CONCAT(Payment_date ORDER BY Payment_date) DESC;

Overall Sorting Order: DESCENDING

Query Results:

Customer_IdTotal PaymentList Of policiesPayment Date
3250012018-02-01 03:28:31
21000022018-02-01 03:27:00
1400002,012018-02-01 03:26:30,2018-02-01 03:30:33

Tuesday, 28 February 2017

HOW TO INSTALL PLUGINS IN INTELLIJ IDEA IDE?

This article shows the sequential screenshots to download & install the plugins in IntelliJ IDE.

Here, I am showing the JMeter plugin installation:

Step 1:  Go to preferences from menu bar as below: or

Press keyboard shortcut (Command + Comma)  ⌘, on Mac

File -> Settings on Windows & Linux



Step 2: Directly shows all the available plugins in the IDE.


Step 3: First search for the JMeter in the available plugins. You see this screen if its not already installed.


Step 4:  Click Browse repositories button, which loads all the repository plugins


Step 5: Now search for the plugin you would like to install, eg: JMeter. Then right click on the plugin & click "Download and install".


Step 6: Prompts the user whether to begin download & installation process


Step 7: If proceeded with Yes, it automatically downloads & install the plugin:


Step 8: After successful installation, IntelliJ asks for a restart: Just like below



 Step 9: Ensure the plugin downloaded & installed successfully by searching for jmeter plugin in the available plugins again.


                                                     HOPE IT IS HELPFUL ......PLEASE SHARE.........

HOW TO GENERATE GETTERS & SETTERS (Actuators & Mutators) FOR A POJO IN IntelliJ IDEA IDE?

For those, who are new to IntelliJ IDE, this article helps in generating Getters & Setters of any POJO (Plain Old Java Object).

First way: Keyboard Shortcut 

               On Mac ( command + N )
               On Linux & Windows — use (Alt + Insert)

The following screenshots works for Mac. The above keyboard shortcuts still works better on respective OS.

Step 1:

Create a simple POJO with some fields:

package sample;

/**
* Created by dineshdontha on 2/27/17.
*/
public class Person {

    String name;
    String password;
    Integer code;
    String city;

}

Step 2:

Press Command + N to see a context menu like this


Step 3:

You will see a popup as below, for selecting the fields:


Step4:

Select the required fields 



Second Way: 

Use the Menu : Code -> Generate . . .



Once after selecting Generate . . . Menu Item, the a context menu appears, just like in Step 2 as above & then everything is same.

                       HOPE IT IS HELPFUL...PLEASE SHARE THIS

Wednesday, 8 February 2017

GRADLE BASICS - EXAMPLE GRADLE PROJECT FROM TERMINAL - COMPARISON WITH MAVEN

Gradle is a build tool just like Maven.(if you are not familiar with maven check this link)

A build tool generally does provide features like dependency management, compilation, packaging & running the unit test cases during its build phases.

Build Tool Features: 

Dependency Management: Provides all the project dependencies (eg: some external jars)

Compilation: Compiles the source code

Packaging: packages the project in jar / war as you configure in build file

Test Cases Execution: once after successful compilation & before packaging it executes the test cases.
 
Maven uses pom.xml as its build file, where all dependencies of the project & packaging of the project (either jar/war) are declared. Whereas, Gradle uses build.gradle file to declare all the dependencies & plugins required for the project. Maven uses XML as its file format, while gradle uses Groovy code.

Note: But to start a gradle project, we don't need to be an expert in Groovy.

Gradle Installation:

you download the latest Gradle distribution here : Download Gradle

Note: Gradle require JDK / JRE 7 or higher versions (mandatory)

Once after downloading the distribution, add the bin folder path to environment variable "PATH". This makes the binary gradle commands to work any where in the command-line.

In Ubuntu: you can also install using this command

dinesh@dinesh:~$ sudo apt-get install gradle

(by using this above command, you do not need any extra configuration like maintaining PATH environment variable. The binary shell script gradle.sh directly placed under /usr/bin/ path, which is already by default added to PATH environment variable).

In Mac: you can also install using this command

dinesh@dinesh:~$ brew install gradle

I recommend to get the binary distribution directly from gradle site.

Now, you can test the installation using the following gradle command(in command-line)

dinesh@dinesh:~$ gradle -v 

for the successful installation, you will see the following output

------------------------------------------------------------
Gradle 3.3
------------------------------------------------------------

Build time:   2017-01-03 15:31:04 UTC
Revision:     075893a3d0798c0c1f322899b41ceca82e4e134b

Groovy:       2.4.7
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_92 (Oracle Corporation 25.92-b14)
OS:           Linux 3.5.0-61-generic amd64


A Sample Gradle Project:

To create gradle project, you must first need to create build.gradle file

> Create a directory for the project

dinesh@dinesh:~$mkdir gradle_proj

> Switch to project

dinesh@dinesh:~$  cd gradle_proj

> Create a build.gradle file

dinesh@dinesh:~/gradle_proj$ gedit build.gradle

Note: gedit is an editor in ubuntu os, you can use any editor you are comfortable with, like sublime text, notepad++
 


Now, apply a java gradle plugin in the script: 

apply plugin: 'java' 

Note: This is important plugin inorder to resolve the project dependencies. Now, you can check the importance of the above line added in build.gradle file, you execute a gradle command

dinesh@dinesh:~/gradle_proj$ gradle tasks

This command "gradle tasks" shows all the project tasks.

A task is small atomic unit of work which performs our build (a task can be compilation, running tests. For that matter, any build tool feature).

when it is executed, it first search for the build.gradle, it shows all the tasks that are related to java plugin. For example, build & test are some of the tasks added. Some of the important tasks are assemble, build, test & dependencies

I can relate the tasks in gradle to Maven goals. 

when you run "gradle tasks", you may see these:


I recommend, once you execute the same command with empty build.gradle file to notice the tasks added especially by java gradle plugin.

Now, you can add a dependency, all the dependencies are added to dependencies block

dependencies{
    compile("org.springframework.boot:spring-boot-starter-web:1.5.1.RELEASE")
}


To resolve, these dependencies you must also add a repository, where all dependencies are downloaded from.

Add a repository block

repositories{
    mavenCentral()
}


The added dependencies are successfully resolved by just executing this

dinesh@dinesh:~/gradle_proj$ gradle build



Now, this commands downloads all the dependencies from maven central. You can also use other repositories like jcenter().

Create a directory for adding java files:

dinesh@dinesh:~/gradle_proj$ mkdir -p src/main/java/sample

Add Some Source Code: Spring Boot Application

package sample;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@SpringBootApplication
@RestController
public class SampleApp{ 

 public static void main(String[] args) throws Exception {
  SpringApplication.run(SampleApp.class, args);
 }

 @RequestMapping("/home")
 public String getHome(){
  return "I am Home";
 } 
 
}

To execute the spring boot application, I am adding the spring boot gradle plugin to classpath using buildscript block

buildscript{

    repositories{
        mavenCentral()
    }

    dependencies{
        classpath("org.springframework.boot:spring-boot-gradle-plugin

                                                            :1.5.1.RELEASE")
    }


}


To get the dependency to classpath, we need to separately define repositories block in buildscript block also.

And also apply the plugin

apply plugin: 'org.springframework.boot'

Now, execute the command 

dinesh@dinesh:~/gradle_proj$ gradle clean build

This once again builds. Once execute the ls command to see the files & directories (dir for windows). It creates build directory as maven creates a target directory.

dinesh@dinesh:~/gradle_proj$ gradle tasks

you will find a gradle task related to spring boot gradle plugin, bootRun:

 
 Now, you can start the spring boot application by running this gradle task: bootRun

dinesh@dinesh:~/gradle_proj$ gradle bootRun

This starts the spring boot application by searching the java file having main method:

 
  Now, type localhost:8080/home in your browser & it returns "I am Home".

                        Hope it helps :) Please share :)

Sunday, 13 March 2016

HOW TO PRINT ADJACENT ELEMENTS FOR A GIVEN SQUARE MATRIX - A JAVA SOLUTION

This article describes one of the ways to find the adjacent elements for a particular element in a given square Matrix.

For Example:
String[] A = ["10#20#30", "40#50#60", "70#80#90"]

Its a 3x3 matrix whose order is 3.

Eg1: The adjacent or Neighboring Elements of 50 are
 
10 20 30
40 50 60
70 80 90

Here, 50 is surrounded by all other elements.

Eg2: The adjacent or Neighboring Elements of 20 are

 10 20 30
 40 50 60

Eg3: The adjacent or Neighboring Elements of 30 are

 20 30
 50 60

Eg4: The adjacent or Neighboring Elements of 40 are

 10 20
 40 50
 70 80

Based on the element 's position, we consider it as either a starting element (S), a Middle element(M) or an End element (E).

Eg:

10, 70 are starting elements.

20, 40, 50, 60, 80 are Middle elements.

30, 90 are Ending elements.

Following is code for printing adjacent elements of a square matrix. Please execute to understand it.

Need pass two parameters

1st param: Order of the matrix:  eg: input1=3

2nd param: String of Rows, where each element of the array is a row. All elements of a row are delimited by # symbol.

Eg:
     input2=['row1','row2','row3']

row1='10#20#30'  row2='40#50#60' row3='70#80#90'

Download Code: AdjacentElements.java

public class AdjacentElements {
 public static void main(String args[]) {
  int input1=5;
  String[] input2={"12#45#33#27#23", "94#54#23#53#11", "98#59#27#62#12","11#51#63#13#46","17#45#31#78#67"};
  /*
      Few Examples you can try
       String[] input2={"12#45#33#27", "94#54#23#53", "98#59#27#62","11#51#63#13"};
    String[] input2={"12#45#33", "94#54#23", "98#59#27"};
    String[] input2={"12"};
       String[] input2={"12#45", "94#54"};

   * You need pass two parameters 
   * first parameter (input1): Order Of Square Matrix;
   * Second parameter (input2): Arrays of Rows where elements of the each row delimited by a # symbol.
   * Eg: ['row1','row2','row3'...]
   */
  printNeighboringElements(input1, input2);
 }
 public static void printNeighboringElements(int input1, String[] input2){
  if(input1!=1){
   String[] tempRows={};
   for(int i=0;i < input2.length;i++){
    /*
     * Here, It prints adjacent elements of all the elements 
     * of any square matrix of any order.
     * We assume element's position in the matrix as any of these 3 values
     * S or M or E
     * S represents Starting Element
     * M represents Middle Element
     * E represents Ending Element.
     */
    String[] reqRow1Elements=new String[input1];
    String[] reqRow2Elements=new String[input1];
    String[] reqRow3Elements=new String[input1];
    String rowStatus = findRowOrPosStatus(i,input1);
    
    if(rowStatus=="S"){
     tempRows = new String[2];
     tempRows[0]=input2[i];
     tempRows[1]=input2[i+1];
     reqRow1Elements=tempRows[0].split("#");
     reqRow2Elements=tempRows[1].split("#");
    }else if(rowStatus=="M"){
     tempRows = new String[3];
     tempRows[0]=input2[i-1];
     tempRows[1]=input2[i];
     tempRows[2]=input2[i+1];
     reqRow1Elements=tempRows[0].split("#");
     reqRow2Elements=tempRows[1].split("#");
     reqRow3Elements=tempRows[2].split("#");
    }else if(rowStatus=="E"){
     tempRows = new String[2];
     tempRows[0]=input2[i-1];
     tempRows[1]=input2[i];
     reqRow1Elements=tempRows[0].split("#");
     reqRow2Elements=tempRows[1].split("#");
    }
    String[] rowElements = input2[i].split("#");
    for(int e=0;e < rowElements.length;e++){
     System.out.println("Adjacent/Neighboring Elements of "+rowElements[e]);
     System.out.println("***********************************");
    String posStatus=findRowOrPosStatus(e, input1);
     if(posStatus=="S"){
      if(rowStatus=="S" || rowStatus=="E"){
       System.out.println(reqRow1Elements[e]+" "+reqRow1Elements[e+1]);
       System.out.println(reqRow2Elements[e]+" "+reqRow2Elements[e+1]);
      }else if(rowStatus=="M"){
       System.out.println(reqRow1Elements[e]+" "+reqRow1Elements[e+1]);
       System.out.println(reqRow2Elements[e]+" "+reqRow2Elements[e+1]);
       System.out.println(reqRow3Elements[e]+" "+reqRow3Elements[e+1]);
      }
     }else if(posStatus=="M"){
      if(rowStatus=="S" || rowStatus=="E"){
       System.out.println(reqRow1Elements[e-1]+" "+reqRow1Elements[e]+" "+reqRow1Elements[e+1]);
       System.out.println(reqRow2Elements[e-1]+" "+reqRow2Elements[e]+" "+reqRow2Elements[e+1]);
      }else if(rowStatus=="M"){
       System.out.println(reqRow1Elements[e-1]+" "+reqRow1Elements[e]+" "+reqRow1Elements[e+1]);
       System.out.println(reqRow2Elements[e-1]+" "+reqRow2Elements[e]+" "+reqRow2Elements[e+1]);
       System.out.println(reqRow3Elements[e-1]+" "+reqRow3Elements[e]+" "+reqRow3Elements[e+1]);
      }
     }else if(posStatus=="E"){
      if(rowStatus=="S" || rowStatus=="E"){
       System.out.println(reqRow1Elements[e-1]+" "+reqRow1Elements[e]);
       System.out.println(reqRow2Elements[e-1]+" "+reqRow2Elements[e]);
      }else if(rowStatus=="M"){
       System.out.println(reqRow1Elements[e-1]+" "+reqRow1Elements[e]);
       System.out.println(reqRow2Elements[e-1]+" "+reqRow2Elements[e]);
       System.out.println(reqRow3Elements[e-1]+" "+reqRow3Elements[e]);
      }
     }
    }
   }//rows loop
  }else {
   System.out.println("No adjacent elements-Its a 1X1 matrix");
  }//for 1X1 matrix
 }
 private static String findRowOrPosStatus(int rowOrPos,int input1){
  String rowOrPosStatus="";
  if(rowOrPos==0){
   rowOrPosStatus="S";
  }else if(rowOrPos==input1-1){
   rowOrPosStatus="E";
  }else if(rowOrPos < input1-1 && rowOrPos!=0){
   rowOrPosStatus="M";
  }
  return rowOrPosStatus;
 }
} 

The Adjacent Elements of 5x5 matrix are printed as :

String[] input2=
{"12#45#33#27#23",   "94#54#23#53#11",  "98#59#27#62#12",
"11#51#63#13#46",   "17#45#31#78#67"};

Output

Adjacent/Neighboring Elements of 12
***********************************
12 45
94 54
Adjacent/Neighboring Elements of 45
***********************************
12 45 33
94 54 23
Adjacent/Neighboring Elements of 33
***********************************
45 33 27
54 23 53
Adjacent/Neighboring Elements of 27
***********************************
33 27 23
23 53 11
Adjacent/Neighboring Elements of 23
***********************************
27 23
53 11
Adjacent/Neighboring Elements of 94
***********************************
12 45
94 54
98 59
Adjacent/Neighboring Elements of 54
***********************************
12 45 33
94 54 23
98 59 27
Adjacent/Neighboring Elements of 23
***********************************
45 33 27
54 23 53
59 27 62
Adjacent/Neighboring Elements of 53
***********************************
33 27 23
23 53 11
27 62 12
Adjacent/Neighboring Elements of 11
***********************************
27 23
53 11
62 12
Adjacent/Neighboring Elements of 98
***********************************
94 54
98 59
11 51
Adjacent/Neighboring Elements of 59
***********************************
94 54 23
98 59 27
11 51 63
Adjacent/Neighboring Elements of 27
***********************************
54 23 53
59 27 62
51 63 13
Adjacent/Neighboring Elements of 62
***********************************
23 53 11
27 62 12
63 13 46
Adjacent/Neighboring Elements of 12
***********************************
53 11
62 12
13 46
Adjacent/Neighboring Elements of 11
***********************************
98 59
11 51
17 45
Adjacent/Neighboring Elements of 51
***********************************
98 59 27
11 51 63
17 45 31
Adjacent/Neighboring Elements of 63
***********************************
59 27 62
51 63 13
45 31 78
Adjacent/Neighboring Elements of 13
***********************************
27 62 12
63 13 46
31 78 67
Adjacent/Neighboring Elements of 46
***********************************
62 12
13 46
78 67
Adjacent/Neighboring Elements of 17
***********************************
11 51
17 45
Adjacent/Neighboring Elements of 45
***********************************
11 51 63
17 45 31
Adjacent/Neighboring Elements of 31
***********************************
51 63 13
45 31 78
Adjacent/Neighboring Elements of 78
***********************************
63 13 46
31 78 67
Adjacent/Neighboring Elements of 67
***********************************
13 46
78 67

Monday, 5 October 2015

IMPROVEMENTS OF SWITCH STATEMENT IN JAVA 7

This post discuss one of improvements of Switch statement in Java 7. Just before discussing about the improvements, Lets recapitulate the well known Switch statement. How it works.

Typical Syntax:

switch  (expression) {

    case label1:

                     statements;

    case label2:

                     statements;

    case label3:
                     statements;
         . . . 
    default:
                     statements;
}


Initially, the expression is evaluated. If the value of the expression is matched to any of the case labels, from the matched case label - its start executing the statements till the end of the switch statement. For example, if value matches to label2, then it executes all the statements from the case label2 till the end of the switch statement and even the optional default label statements are executed.

If the value of the expression is not matched to any of the case labels then it executes the statements under the optional default label.

Note: But generally, we use switch statement to execute one of many possibilities. so we use break statement to stop all other statements after that matched case. 

Example:
// without break;

 int age = 10;
 switch (age) {
 case 10: // Found the match
  System.out.println("Age 10"); // Execution starts here
 case 20:
  System.out.println("Age 20");
 default:
  System.out.println("AgeLess");
 }

Output:
             Age 10
             Age 20
             AgeLess


The expression must evaluate to a type : byte, short, char, int, enum.

In addition to these types, Java 7 added support for Strings in a SWITCH statement.

Expression : String Type

The expression uses a String type. If the expression is evaluating to a null, then a NullPointerException is thrown. The case labels must be String literals.

You cannot use String variables (non-final variables) in the case labels. Can use constants (final variables) as case labels.

Example:

String company = "alphabet";

 switch (company) {

 case "google":
  System.out.println("google");
  break;
 case "facebook":
  System.out.println("facebook");
  break;
 case "alphabet":
  System.out.println("alphabet");
  break;
 default:
  System.out.println("Company Not Found");
  break;

 }

Output:
            alphabet

(does not execute the default label statements because we have used break statement under matched case "alphabet")

Note: The above code fails to compile before java 1.7.
This feature works properly from java 1.7 and above.

Some variants of switch statements:

>> If expression does not match and expression is evaluating to a type int:
/*
  * expression evaluating to int type 
  * match does not match any case label
  */

 int num = 50;
 switch (num) {
 case 10:
  System.out.println("Ten");
 case 20:
  System.out.println("Twenty");
 default:
  System.out.println("No-match"); /* Execution starts here */
 }

Output:
       
No-match


>>You can place the optional default label any where in order. Its not mandatory to place as a last label. But as a convention, its better to place as a last option.

char currency = '$';
 switch (currency) {
 case '€':
  System.out.println("Euro");
 default:
  System.out.println("No Proper Currency"); 
 case '$': //As match is found
  System.out.println("Dollar"); // Execution starts here
 }

 Output:
        Dollar


/*
  * default label can be anywhere and is optional By convention, 
  * most of developers use as last label
  */

 char currency = '@';
 switch (currency) {
 case '€':
  System.out.println("Euro");
 default: //As No match is found
  System.out.println("No Proper Currency"); // Execution starts here
 case '$':
  System.out.println("Dollar");
 }

Output:
        No Proper Currency
        Dollar



>>When expression evaluating to a byte type. Important to remember the byte type value range is -128 to 127 only.

Possible compile-time errors:


//remember byte data type range is -128 to 127
   
  byte b = 10; 
  
  switch (b) {
  case 5:
   System.out.println("Its five");
  case 50:
   System.out.println("Its fifty");
 /* case 150:  fails : A compile-time error. 150 is greater than 127
   b--; */
     default: 
      System.out.println("Its Zero"); 
     }
Output:
         Its Zero

>>should not use duplicate case labels.
int num = 10;

    switch (num) {
    
    case 10: 
     num++; 
    
    case 10:   // fails: CE: same case label 
     num--; 
    
    default: 
     num =100; 
     } 
Output: 
         compile time error:  Duplicate Case

>>should not use variables in case labels. constants are allowed
/*
  * num2 is not a constant 
  * should not use a variable as case label
  */
 int num1 = 10;
 int num2 = 10;

 switch (num1) {
 case 20:
  System.out.println("num1 is 20");

 case num2: // A Compile-time error.
  System.out.println("num1 is 10");
 }

Output:
       compile time error: case expression must be a constant expressions

>> the expression can use an enum type. Here, the case labels must use unqualified enum values. 

Example:
/*
 * An enum defined with three values
 * This enum has to be given to switch
 * as expression
 */
public enum Facility {
 
 ORDINARY,
 
 SEMI_LUXUCY,
 
 LUXURY

}

public class EnumSwitch {

 public static void main(String[] args) {

  Facility fac = Facility.LUXURY; // passing this input param.

  String facility_code = getFacility(fac);
  System.out.println("Code of Facility.LUXURY is " + 
  facility_code);

 }

 private static String getFacility(Facility facility) {
  String fa_code = "";

  // passing Enum as expression
  switch (facility) {
  /*
   * Cannot use Must use Enum value only 
   * Must not quality with Enum i.e,
   * should not use Facility.ORDINARY in case labels
   */
  case ORDINARY:
   fa_code = "ORD";
   break;
  case SEMI_LUXUCY:
   fa_code = "SEM";
   break;
  case LUXURY:
   fa_code = "LUX";
   break;
  }
  return fa_code;
 }

}

 Output:
         Code of Facility.LUXURY is LUX 

Thanks for reading                         Hope u like it :)                               Please share :)