Monday, 22 December 2014

STATIC METHODS & DEFAULT METHODS IN AN INTERFACE - JAVA 8 EXICITING FEATURES

Static Methods in interfaces

Prior to Java 8, we have many utility classes with static methods which are commonly used.

For Example, for Collection interface, we have utility class Collections


likewise,

path - Paths

Executor - Executors

So, To reduce the utility classes, java designers introduced static methods
in interfaces.

Note:

. A static method contains a static modifier.

. They are implicitly public.

. Have implementation logic within the interface.

 
Example:

public interface Blog {

    int  followers_count  = 0;

    void comment();

    //A static convenience method

   public static  void subscribe(){

          //implementation logic

        System.out.println("you have successfully subscribed");

   }

}


DEFAULT METHODS in an interface 

From Java 8,  you can also declare DEFAULT methods in interface.


DEFAULT METHODS is new feature added in Java 8.


To understand the concept of default methods and its purpose, lets consider that
I have designed a library which is having the above declared interface Blog.

Lets take an assumption that, those who want to make blog must implement my interface Blog.

So I have distributed the interface to all the interested people who want to blog.

 Now, the many of my bloggers are satisfied with the methods available in the 
interface.

But, If one of the bloggers wants to add his/her own methods to the interface, like say adding a new method share().

So They would have to request me to add the method share() method and again I would distribute the library to all the bloggers.

Now, If the bloggers try to use the this new library - the old code breaks because 
share() method must be implemented by all the bloggers.

In java 8, this problem is alleviated by introducing DEFAULT methods in the interface.

default methods have a default modifier and an implementation logic in the interface itself.

So, If I make share() as a default method in the interface - old code breaking problem will be solved.

Thanks to Default methods.

Note:

. Must have a default modifier

. have an implementation logic within the interface.


Example:


public interface Blog {

    int  followers_count  = 0;

    void comment();

    //A static convenience method

   public static  void subscribe(){
        
          System.out.println("you have successfully subscribed");

   }

  default String share(){
         
             System.out.println("You have shared your blog"); 

             return "Success";

  }

}



 Hope this is helpful.                                                     
   
 If you like this, please share.

Sunday, 21 December 2014

USING UNDERSCORES IN NUMERIC LITERALS -JAVA 7 FEATURE

Since Java 7, you can use underscores in the numeric literals.

Example:

// declaring a float value

float acc_balance = 5_000L;

Here, the value of the variable is 5000.0

 
Underscores in numeric literals are mainly used to separate the
significant parts of number.


For instance, lets consider 10-digit mobile number in india.


In a 10-digit mobile number, we have two significant parts:

. First four numbers XXXX represents the network operator.

. the last numbers NNNNNN represents the subscriber number.

XXXX-NNNNN

Example:

int phoneNumber = 9849_751031;

This new feature is intended to improve the code readability.


Some examples where you need this feature- to represent:

 . Debit Card Number
 . Credit Card Number
 . Social Security Number


This feature is only a developer convenience.

Note: Compiler will ignore underscores in number literals.  

Example:

 public class Java7Literals {

    public static void main(String args[]){

        long debitCard = 5555_3333_7777_9999L;

        System.out.println("debit card number: "+ debitCard);
      
        }

   }


output:

 debit card number: 5555333377779999

 Here compiler ignored the underscores.

As I said it is a developer convenience.


Some example declarations:

long ssNumber = 999_89_9999L;

printed as: 999899999

float pi = 3.14_15F;

printed as: 3.1415


Rules:
---------

places where not to place the underscores in numeric literals.


. At the beginning and at the end of the numbers


ILLEGAL

 long x3 = _77L;

int x5 = 55_;


. Adjacent to decimal point in a floating point literal

ILLEGAL

float pi =  3._14_15F;


LEGAL

float pi = 3.14_15F;


 .Prior to D or L or F suffix

ILLEGAL

float pi  = 3.14_5_F;

.In positions where strings of digits is exepcted

ILLEGAL

int x5 =  0_x52

// cannot put underscore in the 0x radix prefix

int x6 = 0x_52

//cannot put the underscore at the beginning of the number


LEGAL


int x7  = 0x5_2;


Note: 

For illegal usage of the underscores as described above may yield an error

error: illegal underscore.

This feature can be applied to primitive data types in any supported 
base - octal, hexadecimal, binary  or decimal. 


the underscores in hexadecimal and binary are used in identifying the
parts of commands

Example:

int commandInHex = 0xE_25D5_8C_7;
int commandInBinary = 0b1110_0011111111010101_10001100_0111;


  Hope this is helpful

 If you like this, please share.

Thursday, 4 December 2014

FunctionalInterface ANNOTATION TYPE - USAGE OF @FunctionalInterface

FunctionalInterface

An interface with one abstract method declaration is known as Functional Interface.

eg:

public interface ExampleIfc {

    void showExample();

}

An interface with more than one abstract methods are not considered as functional
interfaces.

eg:

Not a functional interface

public interface ExampleIfc {

 void showExample();

 boolean executeExample();

}

. FunctionalInterface Annotation type:

FunctionalInterface annotation type (@FunctionalInterface) is a marker interface.

Note: A marker interface is one which indicates or hints the compiler.

using this annotation type on an interface makes the compiler verify whether
the declared interface contains one and only one abstract method.

Note:  you must not use this annotation type on

CLASSES 

ANNOTATION TYPES

ENUMS

If used, yields a compile-time error.

. Can be used only on the interfaces with one abstract method.


LEGAL :


@FunctionalInterface
public interface Runner {
          void run();
}

This compiles fine.


ILLEGAL:


@FunctionalInterface
public interface ExampleIfc {

     void showExample();

     boolean executeExample();

}

Compile-time error : because two abstract methods.


ILLEGAL

 @FunctionalInterface
public class XyzClass {
    public void xyzMethod() {
           ....
     }
}

 Compile-time error : because annotation type cannot be applied on classes.



Note: The concept of the Functional interface is very important to learn about the Java 8 lambda expressions.

 Hope this is helpful

 If you like this, please share.

Wednesday, 3 December 2014

GLASSFISH APPLICATION SERVER - COMMAND LINE INTERFACE (CLI) COMMANDS


Glassfish Application Server is a Java EE 7 compliant Application Server.


We can deploy the Java Application archives (jar, war, ear) manually two ways:

. Using  Glassfish Admin Console using its URL

Default URL: http://localhost:4848

The other new way is 

. Using Command Line Interface (CLI) - "asadmin"

"asadmin" - is a command line tool available in the glassfish server installation folder
under the domain directory

Example:

In Windows

c:/glassfish/domain/domain1/

In Linux

/home/dinesh/glassfish/domain/domain1/

Functions of asadmin:

. we can perform all the functions that are available through a glassfish server admin
console

. Inorder to do operations on application server, first we need to start the domain
 using the command  ----> start-domain

asadmin> start-domain

We will see the following message if the domain is started successfully:

 Waiting for domain1 to start .............................................
 Successfully started the domain : domain1
domain  Location: /home/dinesh/Downloads/JavaDownloads/GlassFish_Server/glassfish/domains/domain1
Log File: /home/dinesh/Downloads/JavaDownloads/GlassFish_Server/glassfish/domains/domain1/logs/server.log
Admin Port: 4848
Command start-domain executed successfully.





Some of useful commands of asadmin:

To start and stop the glassfish application server  domain:

. <start-domain>
. <stop-domain>

To deploy and undeploy an application archive - jar, war, ear.
 
. <deploy>
. <undeploy>

eg:
         asadmin> deploy /home/dinesh/example.jar

         asadmin> undeploy /home/dinesh/example.war


To see the list of the already deployed applications.

. <list-components>

eg:

        asadmin> list-components



To create jdbc connection pool

. <create-jdbc-connection-pool>

eg:

asadmin> create-jdbc-connection-pool 
--datasourceclassname com.mysql.jdbc.jdbc2.optional.MysqlDataSource  
--restype javax.sql.DataSource
 --property portNumber=3306:user=root:password=root:
serverName=localhost:databaseName=mydatabase   sample_mysql_pool

Command create-jdbc-connection-pool executed successfully.

 To test the created jdbc connection pool use:
 

. <ping-connection-pool>

eg:

asadmin> ping-connection-pool sample_mysql_pool

Command ping-connection-pool executed successfully.

To create jdbc resource using the above created jdbc connection pool.

. <create-jdbc-resource>

 eg:

asadmin> create-jdbc-resource --connectionpoolid sample_mysql_pool jdbc/SampleDS 

Command create-jdbc-resource executed successfully.

 asadmin is also used to create jms resources, java mail resources and many more commands are used in real-time.

. <create-jms-host>
. <create-jms-resource>
. <create-jmsdest>
. <create-jndi-resource>

Note:

Glassfish is a reference implementation, created by JCP Team.
 Please refer to glassfish reference manual for more concepts:

useful links: glassfish reference - > asadmin commands

VARIABLE ARGUMENTS - VARARGS -JAVA 5 FEATURE

VARIABLE ARGUMENTS:

It is a feature introduced in Java version 5. It is very handy feature in some situation where you don't know the exact number of arguments for methods.


It is generally known as VARARGS. It is represented by a symbol
ellipsis(...)

Example:
class CountMarks{

//create a static method inorder to access in the main method

static void add(int... params){
          int result=0;
          for(int i:params){
             result=result+i;
          }
          System.out.println("sum of marks: "+result);
      }
    public static void main(String args[]){
        m(10);
        m(10,20,30,23,23,23,23,23);
    }
    }


Output:

sum of numbers: 10
sum of numbers: 175



Rules for varargs:


  1.  There should be only one variable argument in a method.
  2.  The variable argument must be the last argument.
Violating these rules leads to COMPILE TIME ERRORS;

Examples: 

Legal:

void sumUp(int... x) {}
//expects from 0 to many ints as parameters

void sumUp(char chr,int... x) {}
//expects first a char, then 0 to many ints

void sumUp(Salary... sal) {}
//expects 0 to many salary objects

ILLEGAL:

void sumUp(int x...) { }
 //Bad syntax

void sumUp(int... x,char... y) {}
 //too many varargs - rule 1 violated

void sumUp(String... s,char b){} 
// var-arg must be last argument-rule 2 
//violated


Note:  In the above example, We can pass as many numbers as we need, to do the same thing earlier we used to do method overloading. 


ENUM TYPE - DECLARATION ERROR

ENUM is a data type - using which can create a fixed set of constants.

Example:

package enum.example;

class EnumExample { 

  public static void main(String args[]){
     

     //Declaring ENUM here yields compile time error

     public enum Days { MON, TUE, SAT}
     

     for(Days d:Days.values()){
         System.out.println(d);
     }
  }

}


Output:

Compile time error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    The member enum Days can only be defined inside a top-level class or interface
    Days cannot be resolved to a type
    Days cannot be resolved

 
Because we should include enum declaration inside a method

It's declaration should be inside a top-level class or interface.

so move the enum declaration to class level


package enum.example;

class EnumExample {  


    //Class-level declaration is correct

    public enum Days { MON, TUE, SAT}

    public static void main(String args[]){


     for(Days d:Days.values()){


         System.out.println(d);


     }


 }


}


Output:

MON
TUE
SAT

JAVA STATIC IMPORT - JAVA5 Feature

JAVA STATIC IMPORT

static import is used to access static members of a class without which you have to access static members using the class name.


Example:(without static import)


public class A {

public static void main(String[] args){

System.out.println("one");
System.out.println("two");
System.out.println("three");
System.out.println("four");
System.out.println("five");
System.out.println("six");


}


Example:(with static import)

import static java.lang.System.out; 

public class A {

public static void main(String[] args){

out.println("one");

out.println("two");

out.println("three");

out.println("four");

out.println("five");

out.println("six");

}
}



Output:

one
two
three
four
five
six

Here, output remains same but, we are accessing and printing Strings with preceding class name for static variable out


ADV: Reduces amount of code

CONDITIONAL OPERATOR IN JAVA - TERNARY OPERATOR - JAVA5 Feature

TERNARY OPERATOR

The conditional operator is a ternary operator (it has 3 operands) & used to evaluate Boolean expressions, much like an if statement.

Based on its condition -  it assigns a value to a variable.


Syntax:

X= (Boolean Expression)  ?   value1  :  value2

It assigns value1 if the Expressions evaluates to true, otherwise assigns value2.

Example:
public class Salary{

public static void main(String[] args){

int age=45;

String pension=(age>=50)?"Eligible for pension":"Not eligible for Pension";

System.out.println("Your are: "+pension);

}

}




Output:

Your are: Not eligible for Pension