Saturday, 14 January 2017

Jshell: java9 Interpreter

Java9 come up with new interactive shell called jshell, it is a simple, interactive computer programming environment that takes single user inputs evaluates them, and returns the result to the user.  It is very useful to the new comers of Java programming environment.

Jshell is a command line interpreter, it is presented in bin directory of java9 installation.

How to open jshell?
Open command prompt and type ‘jshell’.
C:\Users\Krishna>jshell
|  Welcome to JShell -- Version 9-ea
|  For an introduction type: /help intro

jshell>

Get the help of all the commands available in jshell
Type /help in the jshell terminal, it gives list of the commands that are available in jshell.
jshell> /help
|  Type a Java language expression, statement, or declaration.
|  Or type one of the following commands:
|
|  /list [<name or id>|-all|-start]
|       list the source you have typed
|  /edit <name or id>
|       edit a source entry referenced by name or id
|  /drop <name or id>
|       delete a source entry referenced by name or id
|  /save [-all|-history|-start] <file>
|       Save snippet source to a file.
|  /open <file>
|       open a file as source input
|  /vars [<name or id>|-all|-start]
|       list the declared variables and their values
|  /methods [<name or id>|-all|-start]
|       list the declared methods and their signatures
|  /types [<name or id>|-all|-start]
|       list the declared types
|  /imports
|       list the imported items
|  /exit
|       exit jshell
|  /reset
|       reset jshell
|  /reload [-restore] [-quiet]
|       reset and replay relevant history -- current or previous (-restore)
|  /classpath <path>
|       add a path to the classpath
|  /history
|       history of what you have typed
|  /help [<command>|<subject>]
|       get information about jshell
|  /set editor|start|feedback|mode|prompt|truncation|format ...
|       set jshell configuration information
|  /? [<command>|<subject>]
|       get information about jshell
|  /!
|       re-run last snippet
|  /<id>
|       re-run snippet by id
|  /-<n>
|       re-run n-th previous snippet
|
|  For more information type '/help' followed by the name of a
|  command or a subject.
|  For example '/help /list' or '/help intro'.  Subjects:
|
|  intro
|       an introduction to the jshell tool
|  shortcuts
|       a description of shortcuts



Evaluating Expressions
You can evaluate any java valid expressions in jshell.
jshell> 10 + 20
$1 ==> 30

jshell> 10 - 20
$2 ==> -10

jshell> true && false
$3 ==> false

jshell> 2 >> 5
$4 ==> 0

jshell> 2 << 5
$5 ==> 64

Defining variables in jshell
You can define variables and use them.
jshell> int principle = 10000;
principle ==> 10000

jshell> int time = 5;
time ==> 5

jshell> double rateOfIntrest = 1.5;
rateOfIntrest ==> 1.5

jshell> double intrest = (principle * time * rateOfIntrest)/100
intrest ==> 750.0

Print the value of variable
Just type the variable name and press enter, you can see the value associated with the variable.
jshell> int counter = 10
counter ==> 10

jshell> counter
counter ==> 10

Notify above statements, ‘;’ is not compulsory at the end of the statements.

Defining Methods
You can define the methods in jshell and use them.

Example
int fact(int n) {if(n==0) return 1; return n * fact(n-1);}

jshell> int fact(int n) {if(n==0) return 1; return n * fact(n-1);}
|  created method fact(int)

jshell> fact(10)
$14 ==> 3628800

jshell> fact(5)
$15 ==> 120

It is not necessary to define the methods in same line, you can define the method across multiple lines.
jshell> int fact(int n){
   ...>    if(n == 0){
   ...>       return 1;
   ...>    }
   ...>    return n * fact(n-1);
   ...> }
|  modified method fact(int)

As you see the output, it is returning ‘modified method fact(int)’, that means you can redefine already defined methods.
jshell> fact(5)
$17 ==> 120

jshell> fact(6)
$18 ==> 720

Jshell Commands summary

/imports : list the imported items
jshell> /imports
|    import java.io.*
|    import java.math.*
|    import java.net.*
|    import java.nio.file.*
|    import java.util.*
|    import java.util.concurrent.*
|    import java.util.function.*
|    import java.util.prefs.*
|    import java.util.regex.*
|    import java.util.stream.*

/list : list the source you have typed
jshell> /list

   1 : 10 + 20
   2 : 10 - 20
   3 : true && false
   4 : 2 >> 5
   5 : 2 << 5
   6 : int principle = 10000;
   7 : int time = 5;
   8 : double rateOfIntrest = 1.5;
   9 : double intrest = (principle * time * rateOfIntrest)/100;
  10 : intrest
  11 : int counter = 10;
  12 : counter
  14 : fact(10)
  15 : fact(5)
  16 : int fact(int n){
          if(n == 0){
             return 1;
          }
          return n * fact(n-1);
       }
  17 : fact(5)
  18 : fact(6)

/edit <name or id>: Edit a source entry referenced by name or id in the jshell Edit Pad.
Type ‘/edit fact’ in the jshell terminal, it opens the fact method definition in jshell edit pad.
jshell> /edit fact


/drop <name or id> : delete a source entry referenced by name or id
Get all the sources that you typed using /list command.
jshell> /list

   1 : 10 + 20
   2 : 10 - 20
   3 : true && false
   4 : 2 >> 5
   5 : 2 << 5
   6 : int principle = 10000;
   7 : int time = 5;
   8 : double rateOfIntrest = 1.5;
   9 : double intrest = (principle * time * rateOfIntrest)/100;
  10 : intrest
  11 : int counter = 10;
  12 : counter
  14 : fact(10)
  15 : fact(5)
  16 : int fact(int n){
          if(n == 0){
             return 1;
          }
          return n * fact(n-1);
       }
  17 : fact(5)
  18 : fact(6)

Remove the variable counter.
jshell> /drop counter
|  dropped variable counter

Now get all the sources that you typed using /list command.
jshell> /list

   1 : 10 + 20
   2 : 10 - 20
   3 : true && false
   4 : 2 >> 5
   5 : 2 << 5
   6 : int principle = 10000;
   7 : int time = 5;
   8 : double rateOfIntrest = 1.5;
   9 : double intrest = (principle * time * rateOfIntrest)/100;
  10 : intrest
  12 : counter
  14 : fact(10)
  15 : fact(5)
  16 : int fact(int n){
          if(n == 0){
             return 1;
          }
          return n * fact(n-1);
       }
  17 : fact(5)
  18 : fact(6)

Notify above snippet, the variable ‘counter’ is removed.

/save [-all|-history|-start] <file> : Save snippet source to a file.
jshell> /save -all commands.txt

/open <file> : open a file as source input
jshell> /open commands.txt

/vars [<name or id>|-all|-start]: list the declared variables and their values
jshell> /vars
|    int $1 = 30
|    int $2 = -10
|    boolean $3 = false
|    int $4 = 0
|    int $5 = 64
|    int $14 = 3628800
|    int $15 = 120
|    int $17 = 120
|    int $18 = 720
|    int $29 = 30
|    int $30 = -10
|    boolean $31 = false
|    int $32 = 0
|    int $33 = 64
|    int principle = 10000
|    int time = 5
|    double rateOfIntrest = 1.5
|    double intrest = 750.0
|    int counter = 10
|    int $42 = 3628800
|    int $43 = 120
|    int $45 = 120
|    int $46 = 720

jshell> /vars principle
|    int principle = 10000

jshell> /vars 15
|    int $15 = 120

/methods [<name or id>|-all|-start] : list the declared methods and their signatures
jshell> /methods
|    fact (int)int


/types [<name or id>|-all|-start]list the declared types
jshell> class Box{}
|  created class Box

jshell> class Employee{ String firstName; String lastName;}
|  created class Employee

jshell> /types
|    class Box
|    class Employee


/history : history of what you have typed
jshell> /history

/help
10 = 20
10 + 20
10 - 20
true && false
2 >> 5
2 << 5
int principle = 10000;
int time = 5;
int rateOfIntrest = 1.5;
double rateOfIntrest = 1.5;
double intrest = (principle * time * rateOfIntrest)/100
intrest
int counter = 10
counter
int fact(n) = {if(n==0) return 1; return n * fact(n-1)}
int fact(n) = {if(n==0) return 1; return n * fact(n-1)}
int fact(n){
if(n == 0){
int fact(n) {if(n==0) return 1; return n * fact(n-1)}
int fact(int n) {if(n==0) return 1; return n * fact(n-1)}
int fact(int n) {if(n==0) return 1; return n * fact(n-1);}
fact(10)
fact(5)
int fact(int n){
   if(n == 0){
      return 1;
   }
   return n * fact(n-1);
}
fact(5)
fact(6)
/imports
/list
/edti fact
/edit fact
/edit fact
/list
/drop counter
/list
/save -all commands.txt
/open commands.txt
/vars
/vars principle
/vars 15
/methods
/types
class Box{}
class Employee{ String firstName; String lastName;}
/types
/history

/? [<command>|<subject>] : Get information about jshell commands
jshell> /? /list
|
|  /list
|
|  Show the source of snippets, prefaced with the snippet id.
|
|  /list
|       List the currently active snippets of code that you typed or read with /open
|
|  /list -start
|       List the automatically evaluated start-up snippets
|
|  /list -all
|       List all snippets including failed, overwritten, dropped, and start-up
|
|  /list <name>
|       List snippets with the specified name (preference for active snippets)
|
|  /list <id>
|       List the snippet with the specified snippet id

jshell> /? /vars
|
|  /vars
|
|  List the type, name, and value of jshell variables.
|
|  /vars
|       List the type, name, and value of the current active jshell variables
|
|  /vars <name>
|       List jshell variables with the specified name (preference for active variables)
|
|  /vars <id>
|       List the jshell variable with the specified snippet id
|
|  /vars -start
|       List the automatically added start-up jshell variables
|
|  /vars -all
|       List all jshell variables including failed, overwritten, dropped, and start-up

/! : re-run last snippet
jshell> /!
class Employee{ String firstName; String lastName;}
|  modified class Employee

/-<n> : re-run n-th previous snippet
jshell> /-4
class Employee{ String firstName; String lastName;}
|  modified class Employee

jshell> /-10
int fact(int n){
   if(n == 0){
      return 1;
   }
   return n * fact(n-1);
}
|  modified method fact(int)

/help /shortcuts : a description of shortcuts


/reset : reset jshell
jshell> /list

   1 : 10 + 20
   2 : 10 - 20
   3 : true && false
   4 : 2 >> 5
   5 : 2 << 5
  10 : intrest
  12 : counter
  14 : fact(10)
  15 : fact(5)
  17 : fact(5)
  18 : fact(6)
  19 : import java.io.*;
  20 : import java.math.*;
  21 : import java.net.*;
  22 : import java.nio.file.*;
  23 : import java.util.*;
  24 : import java.util.concurrent.*;
  25 : import java.util.function.*;
  26 : import java.util.prefs.*;
  27 : import java.util.regex.*;
  28 : import java.util.stream.*;
  29 : 10 + 20
  30 : 10 - 20
  31 : true && false
  32 : 2 >> 5
  33 : 2 << 5
  34 : int principle = 10000;
  35 : int time = 5;
  36 : double rateOfIntrest = 1.5;
  37 : double intrest = (principle * time * rateOfIntrest)/100;
  38 : intrest
  39 : int counter = 10;
  40 : counter
  42 : fact(10)
  43 : fact(5)
  45 : fact(5)
  46 : fact(6)
  47 : class Box{}
  54 : int fact(int n){
          if(n == 0){
             return 1;
          }
          return n * fact(n-1);
       }
  55 : class Employee{ String firstName; String lastName;}

Now reset the jshell, all the variable, methods that are defined previously are cleared.
jshell> /reset
|  Resetting state.

jshell> /list

jshell> /methods

jshell> /vars

/exit : Exit from jshell
jshell> /exit
|  Goodbye



Previous                                                 Next                                                 Home

Java9: Diamond operator for anonymous classes

Java9 allow diamond with anonymous classes if the argument type of the inferred type is denotable. Prior to Java9, we need to specify the type argument to anonymous class.

public class ContainerFactory {

 <T> Container<T> createBox(T content) {
  
  // Prior to Java9, we have to put the 'T' here :(
  return new Container<T>(content) {
  };
 }

 public class Container<T> {
  private Container(T content) {

  }
 }
}

From java9 onwards, we no need to keep the type argument inside <>, Java automatically infer the types to anonymous class.

 <T> Container<T> createBox(T content) {
  
  // From java9, we no need to specify the type argument :)
  return new Container<>(content) {
  };
 }


public class ContainerFactory {

 <T> Container<T> createBox(T content) {
  
  // From java9, we no need to specify the type argument :)
  return new Container<>(content) {
  };
 }

 public class Container<T> {
  private Container(T content) {

  }
 }
}


Above application compiles on Java9. But when you try to compile above application on Java8, you will end up in following error.

$javac ContainerFactory.java
ContainerFactory.java:6: error: cannot infer type arguments for ContainerFactory.Container<T>
                return new Container<>(content) {
                                    ^
  reason: cannot use '<>' with anonymous inner classes
  where T is a type-variable:
    T extends Object declared in class ContainerFactory.Container
1 error



Previous                                                 Next                                                 Home

Java9: try with resource enhancement

The try-with-resources statement is introduced in java7, it ensures that each resource is closed at the end of the statement.

Syntax
try( resource1;
         resource2;
         …...
         resurce N ) {
}

Prior to Java9, try-with-resources can only manage resources that are declared in the statement.

 public static void writeDataToFile(FileOutputStream fout){

  /* in Java 8, try-with-resources can only manage resources that are declared for the statement */
  try(FileOutputStream out = fout){
   for(int i = 97; i < 110; i++)
    out.write(i);
  }catch(Exception e){
   System.out.println(e.getMessage());
  }
 }

As you see above snippet, I defined the variable ‘out’ inside try-with-resource statement.


From Java9 on wards, if the resource is referenced by a final or effectively final variable, a try-with-resources statement can manage the resource without a new variable being declared.

 public static void writeDataToFile(final FileOutputStream fout){
  try(fout){
   for(int i = 97; i < 110; i++)
    fout.write(i);
  }catch(Exception e){
   System.out.println(e.getMessage());
  }
 }

Test.java

import java.io.FileOutputStream;

public class Test {

 public static void writeDataToFile(final FileOutputStream fout){
  try(fout){
   for(int i = 97; i < 110; i++)
    fout.write(i);
  }catch(Exception e){
   System.out.println(e.getMessage());
  }
 }

}

If you compile the above application in Java9, it runs fine, since the argument to the method writeDataToFile is declared as final, whereas if you try to compile the same application in Java8, you will end up in following error.

$javac Test.java
Test.java:6: error: <identifier> expected
                try(fout){
                        ^
Test.java:6: error: ')' expected
                try(fout){
                         ^
Test.java:6: error: '{' expected
                try(fout){
                          ^
Test.java:7: error: ')' expected
                        for(int i = 97; i < 110; i++)
                                 ^
Test.java:7: error: not a statement
                        for(int i = 97; i < 110; i++)
                           ^
Test.java:7: error: illegal start of type
                        for(int i = 97; i < 110; i++)
                                            ^
Test.java:7: error: not a statement
                        for(int i = 97; i < 110; i++)
                                          ^
Test.java:7: error: ';' expected
                        for(int i = 97; i < 110; i++)
                                                    ^
8 errors



Previous                                                 Next                                                 Home

Java9 : private methods in interfaces

From Java9 onwards, interfaces allow private method definitions. Prior to Java7, interfaces are very simple, they contain only abstract methods. Java8 changes this behaviour by providing default implementation for interface methods and also provides the support for static methods in interfaces.

Now Java9 takes this one step forward by allowing the private methods in interfaces to achieve code reusability.

Factorial.java
public interface Factorial{

 public default int factorial(int n){
  if (n < 0){
   throw new IllegalArgumentException("Number should not be negative");
  }
  
  return fact(n);
 }
 
 private int fact(int n){
  if(n == 0 || n == 1){
   return 1;
  }
  
  return n * fact(n-1);
 }
 
}

Now from Java9 on wards methods can be private, public (or) default (Remember if you don’t provide any access specifier to a method, interface takes it as public by default).

Can I apply private keyword on both static and instance methods?
Yes, you can apply private access specifier on both static and instance methods.

Test.java
public interface Test{

 public static int factorial(int n){
  if (n < 0){
   throw new IllegalArgumentException("Number should not be negative");
  }
  
  return fact(n);
 }
 
 private static int fact(int n){
  if(n == 0 || n == 1){
   return 1;
  }
  
  return n * fact(n-1);
 }
}

Following list summarises the valid combinations of private, public, static, abstract and default.

public static : Valid Combination
public abstract : Valid Combination
public default : Valid Combination
private static : Valid Combination

Following table summarises the invalid combinations.

Combination
Compiler Error
static default
illegal combination of modifiers: static and default
private abstract
illegal combination of modifiers: abstract and private
private default
illegal combination of modifiers: abstract and private

Why do we require private methods in interfaces?
If two default methods needed to share code, a private interface method would allow them to do so, but without exposing that private method and all its "implementation details" via the interface.

Test.java

public interface Test{

 default String getNameInLowerCase(Employee emp){
  String name =  concatAndLowerStrings(emp.firstName, emp.lastName);
  return "[" + name + "]";
 }
 
 default String getEmployeeDetails(Employee emp){
  String name = concatAndLowerStrings(emp.firstName, emp.lastName);
  return "[" + emp.id + " , " + name + "]";
 }
 
 private String concatAndLowerStrings(String str1, String str2){
  String str3 = str1 +" , " +str2;
  return str3.toLowerCase();
 }
 
 public class Employee{
  public String firstName;
  public String lastName;
  public int id;
  
 }
}

Notify above snippet, methods ‘getNameInLowerCase’, ‘getEmployeeDetails’ use concatAndLowerStrings method without exposing the method details using private keyword.

References





Previous                                                 Next                                                 Home

Java9 Tutorial

You can get early access of java9 from https://jdk9.java.net/.

private methods in interfaces
try with resource enhancement
Diamond operator for anonymous classes
Jshell: java9 Interpreter
Allow SafeVarargs on Private Methods
     Add Modules

Previous                                                 Next                                                 Home

Friday, 13 January 2017

SWT: GridLayout

GridLayout provides much flexibility to design user interfaces. GridLayout provides number of properties to manipulate to get good looking user interface.

How to define GridLayout?
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
shell.setLayout(gridLayout);

Following are the different properties associated with GridLayout instance.
Property
Description
horizontalSpacing

Specifies the number of pixels between the right edge of one cell and the left edge of its neighbouring cell to the right.
makeColumnsEqualWidth

makeColumnsEqualWidth specifies whether all columns in the layout will be forced to have the same width. Default value is false.
marginBottom

marginBottom specifies the number of pixels of vertical margin that will be placed along the bottom edge of the layout.
marginLeft

marginLeft specifies the number of pixels of horizontal margin that will be placed along the left edge of the layout.
marginRight

marginRight specifies the number of pixels of horizontal margin that will be placed along the right edge of the layout.
marginTop

marginTop specifies the number of pixels of vertical margin that will be placed along the top edge of the layout.
marginWidth

marginWidth specifies the number of pixels of horizontal margin that will be placed along the left and right edges of the layout.
numColumns

numColumns specifies the number of cell columns in the layout.
verticalSpacing

verticalSpacing specifies the number of pixels between the bottom edge of one cell and the top edge of its neighbouring cell underneath.

What is GridData objects?
GridData object is the layout data object associated with GridLayout, this is used to control the behavior of widgets.

Following statements tells the layout to span the button across two columns.

GridData data3 = new GridData();
data3.horizontalSpan = 2;
button.setLayoutData(data3);

How to define GridData object?
There are two way.
Way1
Define GridData object and set the properties.

Ex:
GridData gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.verticalAlignment = GridData.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalSpan = 2;
button2.setLayoutData(gridData);

Way 2
Define using parameterized constructors.

Ex:
GridData gridData1 = new GridData (SWT.FILL, SWT.CENTER, true, false)
GridData gridData2 = new GridData (SWT.FILL, SWT.FILL, true, true, 2, 1)
button1.setLayoutData(gridData1);
button1.setLayoutData(gridData2);

Note:
Don't reuse the GridData object, As per JavaSpecification, Every control in a Composite that is managed by a GridLayout must have a unique GridData object. If the layout data for a control in a GridLayout is null at layout time, a unique GridData object is created for it.

Following is the complete working application.
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class Test {

 private static void addWidgetsToShell(Display display, Shell shell) {

  GridLayout gridLayout = new GridLayout();
  gridLayout.numColumns = 2;
  shell.setLayout(gridLayout);

  Label label1 = new Label(shell, SWT.NONE);
  label1.setText("Name:");
  Text text1 = new Text(shell, SWT.BORDER);

  Label label2 = new Label(shell, SWT.NONE);
  label2.setText("Age:");
  Text text2 = new Text(shell, SWT.BORDER);

  Label label3 = new Label(shell, SWT.NONE);
  label3.setText("Gender:");
  Text text3 = new Text(shell, SWT.BORDER);

  Button button = new Button(shell, SWT.CHECK);
  button.setText("Have you been employed in the past six months?");

  GridData gridData1 = new GridData();
  GridData gridData2 = new GridData();
  GridData gridData3 = new GridData();

  gridData1.widthHint = 60;
  gridData2.widthHint = 60;
  gridData3.widthHint = 60;

  label1.setLayoutData(gridData1);
  label2.setLayoutData(gridData2);
  label3.setLayoutData(gridData3);

  GridData gridData4 = new GridData(GridData.FILL_HORIZONTAL);
  GridData gridData5 = new GridData(GridData.FILL_HORIZONTAL);
  GridData gridData6 = new GridData(GridData.FILL_HORIZONTAL);

  text1.setLayoutData(gridData4);
  text2.setLayoutData(gridData5);
  text3.setLayoutData(gridData6);

  GridData gridData7 = new GridData();
  gridData7.horizontalSpan = 2;
  button.setLayoutData(gridData7);

  shell.open();

 }

 public static void main(String[] args) {

  /* Instantiate Display object, it represents SWT session */
  Display display = new Display();

  /*
   * Define Shell, it represent a window, You can add more than one shell
   * to Display
   */
  Shell shell = new Shell(display);
  shell.setSize(700, 200);
  shell.setText("GridLayout Demo");
  addWidgetsToShell(display, shell);

  /*
   * Run the event dispatching loop until an exit condition occurs, which
   * is typically when the main shell window is closed by the user.
   */

  while (!shell.isDisposed()) {
   if (!display.readAndDispatch()) {
    display.sleep();
   }
  }

  /* Dispose the display */
  display.dispose();

 }
}

Run above application, you can able to see following screen.



Previous                                                 Next                                                 Home