Friday, February 26, 2021

Retry In The Future

Oracle Java Tutorial and Material, Oracle Java Preparation, Core Java, Oracle Java Learning, Oracle Java Career

Writing asynchronous code in Javascript is relatively easy.

// async function

let attempt = 1;

while (true) {

    try {

        const result = await operationThatMayFail();

        // it didn't fail

        return result;

    } catch (error) {

        if (attempt >= maxAttempts || 

              error !== 'Retryable') {

            // either unhandleable, or no further attempts

            throw error;

        }

    }

    attempt++;

    await sleep(pauseTime);   

}

This infinite loop runs until the operation succeeds, or it throws an error that we don’t like (not 'Retryable') or we run out of attempts. In between attempts it sleeps before retrying.

This apparently sequential code is made out of the async/await pattern and is easy to reason about, though the first await statement might look like it could be replaced immediately returning, which it can’t…

The Promise API in Javascript is very handy/powerful, but the flattening of it into what looks like blocking code is even better!

So How Do We Do This In Java?

Trigger warning – you don’t want to know the answer to this!!!

I’ll answer this in Java 11, though there’s an optimisation to be made with later versions.

I’ve produced an example library and its unit tests for you to play with, so go and have a look. This is terrifying code. The most weird thing about this code is that this isn’t the first time I’ve implemented one of these, though this implementation was written tonight from scratch.

The first thing we need to know is that Java 8 and onwards provides a CompletableFuture which is very similar in intent to the Javascript Promise. A CompletableFuture says it WILL have an answer in the future, and there are various options for composing further transformations and behaviour upon it.

Our goal in this exercise is to write something which will allow us to execute a function that completes in the future a few times, until it succeeds. As each attempt needs to call the function again, let’s characterise attempts via an attempter as Supplier<CompletableFuture<T>>. In other words, something that can supply a promise to be doing the work in the future can be used to get our first attempt and can be used in retries to perform subsequent attempts. Easy!

The function we want to write, therefore, should take a thing which it can call do to the attempts, and will return a CompletableFuture with the result, but somehow hide the fact that it’s baked some retries into the process.

Here’s a signature of the function we want:

/**

     * Compose a {@link CompletableFuture} using the <code>attempter</code> 

     * to create the first

     * attempt and any retries permitted by the <code>shouldRetry</code> 

     * predicate. All retries wait

     * for the <code>waitBetween</code> before going again, up to a 

     * maximum number of attempts

     * @param attempter produce an attempt as a {@link CompletableFuture}

     * @param shouldRetry determines whether a {@link Throwable} is retryable

     * @param attempts the number of attempts to make before allowing failure

     * @param waitBetween the duration of waiting between attempts

     * @param <T> the type of value the future will return

     * @return a composite {@link CompletableFuture} that runs until success or total failure

     */

    public static <T> CompletableFuture<T> withRetries(

        Supplier<CompletableFuture<T>> attempter,

        Predicate<Throwable> shouldRetry,

        int attempts, Duration waitBetween) {

    ...

}

The above looks good… if you have a function that returns a CompletableFuture already, it’s easy to harness this to repeatedly call it, and if you don’t, then you can easily use some local thread pool (or even the fork/join pool) to repeatedly schedule something to happen in the background and become a CompletableFuture. Indeed, CompletableFuture.supplyAsync will construct such an operation for you.

So how to do retries…

Retry Options

Java 11 doesn’t have the function we need (later Java versions do). It has the following methods of use to us on a CompletableFuture:

◉ thenApply – which converts the eventual result of a future into something

◉ thenCompose – which takes a function which produces a CompletionStage out of the result of an existing CompletableFuture and sort of flatMaps it into a CompletableFuture

◉ exceptionally – which allows a completable future, which is presently in error state, to render itself as a different value

◉ supplyAsync – allows a completable future to be created from a threadpool/Executor to do something eventually

What we want to do is somehow tell a completable future –

completableFuture.ifErrorThenRetry(() -> likeThis())

And we can’t… and even if we could, we’d rather it did it asynchronously after waiting without blocking any threads!

Can We Cook With This?

We have all the ingredients and we can cook them together… but it’s a bit clunky.

We can make a scheduler that will do our retry later without blocking:

// here's an `Executor` that can do scheduling

private static final ScheduledExecutorService SCHEDULER =

     Executors.newScheduledThreadPool(1);

// which we can convert into an `Executor` functional interface

// by simply creating a lambda that uses our `waitBetween` Duration

// to do things later:

Executor scheduler = runnable -> 

    SCHEDULER.schedule(runnable, 

        waitBetween.toMillis(), TimeUnit.MILLISECONDS);

So we have non-blocking waiting. A future that wants to have another go, can somehow schedule itself and become a new future which tries later… somehow.

We need the ability to flatten a future which may need to replace its return value with a future of a future:

private static <T> CompletableFuture<T> flatten(
        CompletableFuture<CompletableFuture<T>> completableCompletable) {
    return completableCompletable.thenCompose(Function.identity());
}

Squint and forget about it… it does the job.

Adding The First Try


Doing the first attempt is easy:

CompletableFuture<T> firstAttempt = attempter.get();

All we have to do now is attach the retrying to it. The retry will, itself, return a CompletableFuture so it can retry in future. This means that using firstAttempt.exceptionally needs the whole thing to become a future of a future..!!!

return flatten(
    firstAttempt.thenApply(CompletableFuture::completedFuture)
        .exceptionally(throwable -> 
             retry(attempter, 1, throwable, shouldRetry, attempts, scheduler)));

We have to escalate the first attempt to become a future of a future on success (with thenApply) so we can then use an alternate path with exceptionally to produce a different future of a future on failure (with attempt 1)… and then we use the flatten function to make it back into an easily consumer CompletableFuture.

If this looks like voodoo then two points:

◉ it works
◉ you ain’t seen nothing yet!!!

Retrying in the Future of the Future of the Future


Oracle Java Tutorial and Material, Oracle Java Preparation, Core Java, Oracle Java Learning, Oracle Java Career
Great Scott Marty, this one’s tricky. We can have some easy guard logic in the start of our retry function:

int nextAttempt = attemptsSoFar + 1;
if (nextAttempt > maxAttempts || !shouldRetry.test(throwable.getCause())) {
    return CompletableFuture.failedFuture(throwable);
}

This does the equivalent of the catch block of our original Javascript. It checks the number of attempts, decides if the predicate likes the error or not… and fails the future if it really doesn’t like what it finds.

Then we have to somehow have another attempt and add the retry logic onto the back of it. As we have a supplier of a CompletableFuture we need to use that with CompletableFuture.supplyAsync. We can’t call get on it, because we want it to happen in the future, according to the waiting time of the delaying Executor we used to give us a gap between attempts.

So we have to use flatten(CompletableFuture.supplyAsync(attempter, scheduler)) to put the operation into the future and then make it back into a CompletableFuture for onward use… and then… for reasons that are hard to fathom, we need to repeated the whole thenApply and exceptionally pattern and flatten the result again.

This is because we first need a future that will happen later, in a form where we can add stuff to it, and we can’t add stuff to it until… I mean, I understand it, but it’s just awkward:

return flatten(flatten(CompletableFuture.supplyAsync(attempter, scheduler))
    .thenApply(CompletableFuture::completedFuture)
    .exceptionally(nextThrowable ->
         retry(attempter, nextAttempt, nextThrowable, 
             shouldRetry, maxAttempts, scheduler)));

Well, if flattening’s so good, we may as well do it lots, eh?

Wednesday, February 24, 2021

Java.Lang.Float class in Java

Core Java, Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Certification, Oracle Java Exam Prep, Oracle Java Preparation

Float class is a wrapper class for the primitive type float which contains several methods to effectively deal with a float value like converting it to a string representation, and vice-versa. An object of Float class can hold a single float value. There are mainly two constructors to initialise a Float object-

◉ Float(float b: Creates a Float object initialized with the value provided.

Syntax: public Float(Float d)

Parameters:

d : value with which to initialize

◉ Float(String s): Creates a Float object initialized with the parsed float value provided by string representation. Defalut radix is taken to be 10.

Syntax:  public Float(String s) 

                    throws NumberFormatException

Parameters: 

s : string representation of the byte value 

Throws: 

NumberFormatException: If the string provided does not represent any float value.

Methods:

1. toString(): Returns the string corresponding to the float value.

Syntax : public String toString(float b)

Parameters :

b : float value for which string representaion required.

2. valueOf() : returns the Float object initialised with the value provided.

Syntax : public static Float valueOf(float b)

Parameters :

b : a float value

Another overloaded function valueOf(String val) which provides function similar to

new Float(Float.parseFloat(val,10))

Syntax : public static Float valueOf(String s)

           throws NumberFormatException

Parameters :

s : a String object to be parsed as float

Throws :

NumberFormatException : if String cannot be parsed to a float value.

3. parseFloat() : returns float value by parsing the string. Differs from valueOf() as it returns a primitive float value and valueOf() return Float object.

Syntax : public static float parseFloat(String val)

             throws NumberFormatException

Parameters :

val : String representation of float 

Throws :

NumberFormatException : if String cannot be parsed to a float value in given radix.

4. byteValue() : returns a byte value corresponding to this Float Object.

Syntax : public byte byteValue()

5. shortValue() : returns a short value corresponding to this Float Object.

Syntax : public short shortValue()

6. intValue() : returns a int value corresponding to this Float Object.

Syntax : public int intValue()

7. longValue() : returns a long value corresponding to this Float Object.

Syntax : public long longValue()

8. doubleValue() : returns a double value corresponding to this Float Object.

Syntax : public double doubleValue()

9. floatValue() : returns a float value corresponding to this Float Object.

Syntax : public float floatValue()

10. hashCode() : returns the hashcode corresponding to this Float Object.

Syntax : public int hashCode()

11. isNaN() : returns true if the float object in consideration is not a number, otherwise false.

Syntax : public boolean isNaN()

Another static method isNaN(float val) can be used if we dont need any object of float to be created. It provides similar functionality as the above version.

Syntax : public static boolean isNaN(float val)

Parameters :

val : float value to check for

12. isInfinite() : returns true if the float object in consideration is very large, otherwise false. Specifically any number beyond 0x7f800000 on positive side and below 0xff800000 on negative side are the infinity values.

Syntax : public boolean isInfinite()

Another static method isInfinite(float val) can be used if we dont need any object of float to be created. It provides similar functionality as the above version.

Syntax : public static boolean isInfinte(float val)

Parameters :

val : float value to check for

13. toHexString() : Returns the hexadecimal representation of the argument float value.

Syntax : public static String toHexString(float val)

Parameters

val : float value to be represented as hex string

14. floatToIntBits() : returns the IEEE 754 floating-point “single format” bit layout of the given float argument. Detailed summary of IEEE 754 floating-point “single format” can be found here.

Syntax : public static int floatToIntBits(float val)

Parameters :

val : float value to convert

15. floatToRawIntBits() : returns the IEEE 754 floating-point “single format” bit layout of the given float argument. It differs from previous method as it preserves the Nan values.

Syntax : public static int floatToRawIntBits(float val)

Parameters :

val : float value to convert

16. IntBitsToFloat() : Returns the float value corresponding to the long bit pattern of the argument. It does reverse work of the previous two methods.

Syntax : public static float IntBitsToFloat(long b)

Parameters :

b : long bit pattern

17. equals() : Used to compare the equality of two Float objects. This methods returns true if both the objects contains same float value. Should be used only if checking for equality. In all other cases compareTo method should be preferred.

Syntax : public boolean equals(Object obj)

Parameters :

obj : object to compare with

18. compareTo() : Used to compare two Float objects for numerical equality. This should be used when comparing two Float values for numerical equality as it would differentiate between less and greater values. Returns a value less than 0,0,value greater than 0 for less than,equal to and greater than.

Syntax : public int compareTo(Float b)

Parameters :

b : Float object to compare with

19. compare() : Used to compare two primitive float values for numerical equality. As it is a static method therefore it can be used without creating any object of Float.

Syntax : public static int compare(float x,float y)

Parameters :

x : float value

y : another float value

// Java program to illustrate 

// various float class methods 

// of Java.lang class 

public class GfG 

public static void main(String[] args) 

float b = 55.05F; 

String bb = "45"; 


// Construct two Float objects 

Float x = new Float(b); 

Float y = new Float(bb); 


// toString() 

System.out.println("toString(b) = " + Float.toString(b)); 


// valueOf() 

// return Float object 

Float z = Float.valueOf(b); 

System.out.println("valueOf(b) = " + z); 

z = Float.valueOf(bb); 

System.out.println("ValueOf(bb) = " + z); 


// parseFloat() 

// return primitive float value 

float zz = Float.parseFloat(bb); 

System.out.println("parseFloat(bb) = " + zz); 


System.out.println("bytevalue(x) = " + x.byteValue()); 

System.out.println("shortvalue(x) = " + x.shortValue()); 

System.out.println("intvalue(x) = " + x.intValue()); 

System.out.println("longvalue(x) = " + x.longValue()); 

System.out.println("doublevalue(x) = " + x.doubleValue()); 

System.out.println("floatvalue(x) = " + x.floatValue()); 


int hash = x.hashCode(); 

System.out.println("hashcode(x) = " + hash); 


boolean eq = x.equals(y); 

System.out.println("x.equals(y) = " + eq); 


int e = Float.compare(x, y); 

System.out.println("compare(x,y) = " + e); 


int f = x.compareTo(y); 

System.out.println("x.compareTo(y) = " + f); 


Float d = Float.valueOf("1010.54789654123654"); 

System.out.println("isNaN(d) = " + d.isNaN()); 


System.out.println("Float.isNaN(45.12452) = "

+ Float.isNaN(45.12452F)); 


// Float.POSITIVE_INFINITY stores 

// the positive infinite value 

d = Float.valueOf(Float.POSITIVE_INFINITY + 1); 

System.out.println("Float.isInfinite(d) = "

+ Float.isInfinite(d.floatValue())); 


float dd = 10245.21452F; 

System.out.println("Float.toString(dd) = "

+ Float.toHexString(dd)); 


int float_to_int = Float.floatToIntBits(dd); 

System.out.println("Float.floatToLongBits(dd) = "

+ float_to_int); 


float int_to_float = Float.intBitsToFloat(float_to_int); 

System.out.println("Float.intBitsToFloat(float_to_long) = "

+ int_to_float); 

Output :

toString(b) = 55.05
valueOf(b) = 55.05
ValueOf(bb) = 45.0
parseFloat(bb) = 45.0
bytevalue(x) = 55
shortvalue(x) = 55
intvalue(x) = 55
longvalue(x) = 55
doublevalue(x) = 55.04999923706055
floatvalue(x) = 55.05
hashcode(x) = 1113338675
x.equals(y) = false
compare(x,y) = 1
x.compareTo(y) = 1
isNaN(d) = false
Float.isNaN(45.12452) = false
Float.isInfinite(d) = true
Float.toString(dd) = 0x1.4029b8p13
Float.floatToLongBits(dd) = 1176507612
Float.intBitsToFloat(float_to_long) = 10245.215

Tuesday, February 23, 2021

Controlling the Visibility of Class and Interface in Java

Core Java, Oracle Java Learning, Oracle Java Certification, Oracle Java Exam Prep, Oracle Java Preparation

Maintenance is one of the important aspects of software development, and experience has shown that software that maintains its component’s visibility low is more maintainable than one that exposes its component more. You’re not going to know it upfront, but when redesigning the application, you’re going to miss it terribly.

You end up patching and repeating the same errors, as maintaining backward compatibility is a must-have requirement for many applications. You will not do much because the class and interfaces are tightly integrated with a lot of other applications. Java has always prioritized encapsulation, providing access modifiers of support from the very beginning. By making them public, package-private or private provides ways to monitor the visibility of some type, such as class or interface.

Below are some rules to control the visibility:

1. A top-level class (a class whose name is the same as the Java source file that contains it) can also be either a public or a private package (without an access modifier) and cannot be a private one. Private, public, or package-private may only be a nesting class.

2. A public class is accessible to all and most visible, try to keep public only key interfaces, never let the implementation go public until you believe it’s complete and mature.

3. The private type, on the other hand, is less visible, and in Java, only the nested class or interface can be private. You have full control over this class to change its actions with experiences, new technology, tools, and redesign, as it’s least visible.

4. Package-private visibility is a clever midway and is also default visibility, there’s no such keyword as package-private, instead if you don’t have any access modifier as Java thinks it’s package-private, and then make it only visible on the same package.

5. If the classes and interfaces are only shared within the same package between other classes, make them package-private. As the client is unable to reach them, they are therefore reasonably safe to change.

How to control Visibility of Class or Interface in Java?

In addition to decreasing class or interface visibility using the access modifier, based on your runtime environment, there are many other ways to do so. At the component level, such as Websphere, Weblogic, or JBoss in Application Server, an interface class may be proxied or wrapped to reduce external visibility.

No matter what you do, there will still be certain types that need to be exposed to the outside world, but you can always handle them with proxy or wrapper. Although client programs will load proxied implementation classes, an immutable proxy or wrapper would often be obtained.

For example, the Java Servlet API (javax.servlet) getServletContext() returns an implementation of javax.servlet.ServletContext, which is typically an immutable proxy to satisfy the ServletContext framework promises. It is most possible that a separate version of the javax.servlet.ServletContext specification operates on the application server.

It is possible to use a similar pattern in the implementation of other externally accessible interfaces, e.g. Javax.ejb.EJBContext, Javax.ejb.TimerService, ServletRequest, ServletResponse, etc. To support these global interfaces, various application servers can use various applications.

JDK Example of Controlling Visibility of Java Class

Core Java, Oracle Java Learning, Oracle Java Certification, Oracle Java Exam Prep, Oracle Java Preparation
EnumSet class is another fascinating example of managing visibility. In order to prevent instantiation, the Java designer made the abstract class and provided factory methods as the only way to create an instance of that class, e.g. Methods from EnumSet.of() or EnumSet.noneOf().

Internally, in the form of RegularEnumSet and JumboEnumSet, they have two separate implementations, which are automatically selected based on the size of the main universe by static factory methods.

For instance, if the number of values in Enum is less than 64, then RegularEnumSet is used, otherwise, the JumboEnumSet instance is returned. The beauty of this design is that package-private means that consumers have no idea about any of these implementations.

Modifier Description
Default  declarations are visible only within the package (package private)
Private  declarations are visible within the class only 
Protected  declarations are visible within the package or all subclasses 
Public  declarations are visible everywhere 

Private Access Modifier


// Java program for showcasing the behaviour 
// of Private Access Modifier 

class Data { 
// private variable 
private String name; 
public class Main { 
public static void main(String[] main){ 
// create an object of Data 
Data d = new Data(); 
// access private variable and field from another class 
d.name = "Kapil"; 
}

Output:

Main.java:18: error: name has private access in Data
     d.name = "Programiz";
      ^
In the above example, we have declared a private variable named name and a private method named display(). When we run the program, we will get the above error:

Protected Access Modifier


// Java program for showcasing the behaviour 
// of Protected Access Modifier 

class Animal { 
// protected method 
protected void display() { 
System.out.println("I am an animal"); 

class Dog extends Animal { 
public static void main(String[] args) { 

// create an object of Dog class 
Dog dog = new Dog(); 
// access protected method 
dog.display(); 
}

Output

I am an animal

Public Access Modifier:


// Java program for showcasing the behaviour 
// of Public Access Modifier 

// Animal.java file 
// public class 

class Animal { 
// public variable 
public int legCount; 

// public method 
public void display() { 
System.out.println("I am an animal."); 
System.out.println("I have " + legCount + " legs."); 

// Main.java 
public class Main { 
public static void main( String[] args ) { 
// accessing the public class 
Animal animal = new Animal(); 

// accessing the public variable 
animal.legCount = 4; 
// accessing the public method 
animal.display(); 
}

Output

I am an animal.
I have 4 legs.

Monday, February 22, 2021

Unit testing private methods

Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Exam Prep, Core Java, Java Career

Introduction

In this article, I will contemplate the testing of private methods in unit tests. After that, I will propose a way or pattern to do it, if you must. Finally, I will show how you can generate this pattern automatically.

Read More: 1Z0-900: Java EE 7 Application Developer

And yes, I will also write a takeaway section to know what you have read.

Test or not to Test Private Methods

Unit testing is usually not black-box testing. It is debatable if it ought to be or not. Practice shows that it rarely is. When we equip the tested unit with different mocks, we play around with the implementation and not the defined functionality that a black-box test should only deal with.

After setting up and injecting the mock objects, we invoke the tested methods, and these methods are usually public. In other words, the invocation of the tested system is more like a black-box test. You can say that the test setup is not a black-box test, but the actual test is.

The advantage of black-box testing is that it does not need to change if the tested module changes’ internal working. If the functionality changes, it is another story. It is easier to refactor, optimize, simplify, beautify your code if there are clean unit tests that do not depend on the implementation. If the unit tests depend on the implementation, then you cannot reliably refactor your code. As soon as you change the implementation, the test has to follow the change.

I do not particularly appreciate when the unit test cannot be black-box, but there are cases when it is unavoidable. An unusual and frequent case is when we want to test a private method. If you want to, or even God forgive, have to test a private method, it is a code smell. The method may be simple, and you can achieve the coverage of its functionality by invoking only the public API of the tested unit. You do not have to test the private method, and if you do not have to, you must not want.

Another possibility is that that the private method is so complicated that it deserves its own test. In that case, the functionality deserves a separate utility class.

Still, there is a third possibility. After all the contemplating, we decide that the private method remains inside the unit, and we want to test it.

It is a small, insignificant problem that you cannot invoke from outside, and the test is inevitably out of the unit. Some developers remove the private modifier changing the access level from private to “test-private”.

No kidding! After more than 500 technical interviews over the past ten years, I have heard many things. I regret that I did not start recording these. As I heard a few times, one of these lovely things: “test private” as a terminology instead of package-private. Two or three candidates out of the 500 said that the accessibility is test private when there is no access modifier in front of the class member. It means they said that the member can also be accessible from the unit tests. From other classes in the same package? Not so sure.

What this story suggests is that many developers struggle to test private methods. I have also seen this in many other projects.

I am not too fond of this approach because we weaken the access protection of a class member to ease testing.

A different approach is when the tests use reflection to access the class members. There are two issues with this approach. One is the suboptimal performance. The other is the bloated code. The fact that the access to the class members via reflection is slower than the direct access is usually not significant. We are talking about tests. If the test execution needs significant time, then the tests are wrong, or the project is large or has some particular testing need. Even in these cases, the reason for the slow speed is usually not the reflective access.

The bloated code, on the other hand, hinders readability. It is also cumbersome to write every time things like

Field f = sut.getClass().getDeclaredField("counter");

f.setAccessible(true);

f.set(sut, z);

when we want to set a private field, or

Method m = sut.getClass().getDeclaredMethod("increment");

m.setAccessible(true);

m.invoke(sut);

when we want to invoke a private method. The maintenance of such tests is also questionable. If the name of the method or field changes, the test has to follow. There is no significant risk of forgetting because the test will fail, but still, it is a manual editing functionality. Most of the IDEs support renaming. Whenever I rename a method or field, the IDE renames all the references to it. Not when the reference is part of a string.

There is no real solution to this issue, except when you write code that does not need the testing of private methods and fields. Still, some approaches have advantages.

Doing it with a Style

One approach is to declare a private static delegating inner class with the same name as the tested class. This class has to implement the same methods as the original tested class, and these implementations should delegate to the original methods. The class also has to implement setters and getters to all the fields.

If we instantiate this class instead of the original one, then we can invoke any method or set any field without reflective access in the test code. The inner class hides the reflective access.

The reason to name the class with the same simple name as the tested class is that the tests do not need to change this way. If a test has a code that instantiated the tested class calling new Sut() and now we start to have an inner class named Sut, then the constructor all of a sudden will refer to the inner class.

Let’s see an example. The following class is a simple example that has one public method and a private one. The complexity of the methods barely reaches the level that would rectify extensive testing, but this makes it suitable for demonstration purposes.

public class SystemUnderTest {

private int counter = 0;

public int count(int z) {

while (z > 0) {

z--;

increment();

}

return counter;

}

private void increment(){

counter++;

}

}

The test itself is also very simple:

@Test

void testCounter() throws Exception {

final var sut = new SystemUnderTest();

sut.setCounter(0);

sut.increment();

Assertions.assertEquals(1, sut.getCounter());

}

The only problem with this solution that the system under test does not contain the setter, and the method increment() is private. The code, as it is now, does not compile. We have to provide an implementation of the delegating static inner class named SystemUnderTest.

The following code shows an implementation of this class, which I created manually.

private static class SystemUnderTest {

private javax0.geci.jamal.sample.SystemUnderTest sut = new javax0.geci.jamal.sample.SystemUnderTest();

private void setCounter(int z) throws NoSuchFieldException, IllegalAccessException {

Field f = sut.getClass().getDeclaredField("counter");

f.setAccessible(true);

f.set(sut, z);

}

private int getCounter() throws NoSuchFieldException, IllegalAccessException {

Field f = sut.getClass().getDeclaredField("counter");

f.setAccessible(true);

return (int) f.get(sut);

}

private void increment() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

Method m = sut.getClass().getDeclaredMethod("increment");

m.setAccessible(true);

m.invoke(sut);

}

private int count(int z) {

return sut.count(z);

}

}

It is already an achievement because we could separate the messy reflective access from the test code. The test, this way, is more readable. Since we cannot avoid the reflective code, it will not get better than this as per the readability. The other issue, maintainability, however, can still be improved.

Doing it Automated

Creating the delegating inner class is relatively straightforward. It does not need much innovation. If you specify the task precisely, any cheaply hired junior could create the inner class. It is so simple that even a program can create it. It does not need the human brain.

If you tried to write a Java program from scratch that generates this code, it would be, well, not simple. Fortunately (ha ha ha), we have Java::Geci, and even more, we have the Jamal module. Jav::Geci is a code generation framework that you can use to generate Java code. The framework contains readily available code generators, but it is also open and pluggable, providing a clean API for new code generators. It does all the tasks needed for most of the code generators and lets the code generator program focus on its core business.

Code generation.

For simpler applications, when the code generation is straightforward and does not need a lot of algorithm implementation, the module Jamal can be used. Jamal is a text-based templating language, which can be extended with Java classes implementing macros. The Java::Geci Jamal module includes a code generator that parses the source files and looks for code that has the following structure:

/*!Jamal

TEMPLATE

*/

CODE HERE

//__END__

When it sees one, it evaluates the code that is written on the lines TEMPLATE using Jamal, and then it replaces the lines of CODE HERE with the result. It generates code, and if there was a generated code but is stale, it updates the code.

The code generation runs during the test execution time, which has advantages and disadvantages.

One disadvantage is that the empty code or stale code should also compile. The compilation should not depend on the up-to-date-ness of the generated code. In practice, we usually (well, not usually, rather always) can cope with it.

The advantage is that the code generation can access the Java code structures via reflection. That way, for example, the code generators can get a list of all declared fields or methods and can generate some delegating methods for them.

The Jamal module contains Java classes implementing macros that can do that. The fact that you can express the generation of the unit test delegating inner class as Jamal macros shows the tool’s power. On the other hand, I have to note that this task is somewhere at the edge of the tool’s complexity. Nevertheless, I decided to use this task as a sample because generating setter and getters is boring. I also want to avoid lazy readers asking me why to have another setter/getter generator, as it happened at some conferences where I talked about Java::Geci. Setter and getter generator is not a good example, as it does not show you the advantage. You can do that with the IDE or using Lombok or some other tool. Perhaps after reading this article, you can try and implement the setter/getter generation using Jamal just for fun and to practice.

The previous code snippets were from the class ManualTestSystemUnderTest. This class contains the manually created delegating inner class. I created this class for demonstration purposes. The other testing class, GeneratedTestSystemUnderTest contains the generated sample code. We will look at the code in this file and how Java::Geci generates it automatically.

Before looking at the code, however, I have to make two notes:

◉ The example code uses a simplified version of the macros. These macros do not cover all the possible causes.

◉ On the other hand, the code includes all the macros in the source file. Professional code does not need to have these macros in the source. All they need is an import from a resource file and then the invocation of a single macro. Two lines. The macros generating the delegating inner class are defined in a resource file. It is written once, you do not need to write them all the time. I will show you at the end of this article how it is invoked.

Let’s have a look at the class GeneratedTestSystemUnderTest! This class contains the following Jamal template in a Java comment:

/*!jamal

{%@import res:geci.jim%}\

{%beginCode SystemUnderTest proxy generated%}

private static class SystemUnderTest {

private javax0.geci.jamal.sample.SystemUnderTest sut = new javax0.geci.jamal.sample.SystemUnderTest();

{%!#for ($name,$type,$args) in

({%#methods

{%class javax0.geci.jamal.sample.SystemUnderTest%}

{%selector private %}

{%format/$name|$type|$args%}

%}) =

{%@options skipForEmpty%}

private $type $name({%`@argList $args%}) throws Exception {

Method m = sut.getClass().getDeclaredMethod("$name"{%`#classList ,$args%});

m.setAccessible(true);

m.invoke(sut{%`#callArgs ,$args%});

}

%}

{%!#for ($name,$type,$args) in

({%#methods

{%class javax0.geci.jamal.sample.SystemUnderTest%}

{%selector/ !private & declaringClass -> ( ! canonicalName ~ /java.lang.Object/ )%}

{%format/$name|$type|$args%}

%}) =

{%@options skipForEmpty%}

private $type $name({%`@argList $args%}) {

{%`#ifNotVoid $type return %}sut.$name({%`#callArgs $args%});

}

%}

{%!#for ($name,$type) in

({%#fields

{%class javax0.geci.jamal.sample.SystemUnderTest%}

{%selector/ private %}

{%format/$name|$type%}

%}) =

{%@options skipForEmpty%}

private void {%setter=$name%}($type $name) throws Exception {

Field f = sut.getClass().getDeclaredField("$name");

f.setAccessible(true);

f.set(sut,$name);

}

private $type {%getter/$name/$type%}() throws Exception {

Field f = sut.getClass().getDeclaredField("$name");

f.setAccessible(true);

return ($type)f.get(sut);

}

%}

{%!#for ($name,$type) in

({%#fields

{%class javax0.geci.jamal.sample.SystemUnderTest%}

{%selector/ !private %}

{%format/$name|$type%}

%}) =

{%@options skipForEmpty%}

private void {%setter/$name%}($type $name) {

sut.$name = $name;

}

private $type {%getter/$name/$type%}() {

return sut.$name;

}

%}

}

{%endCode%}

*/

In this code the macro start string is {% and the macro closing string is %}. It is the default setting when Java::Geci starts Jamal to process a source file. This way, the macro enhanced template can freely contain standalone { and } characters, which is very common in Java. Macros implemented as Java code use the @ or the # character in front of the macro name. If there is no such character in front of the macro name, then the macro is user-defined from a @define ... macro.

The text of the template contains three parts:

1. the start of the code,

2. four loops, and

3. the end of the generated code in the template (this is just a closing } character).

The start of the template

{%@import res:geci.jim%}\

{%beginCode SystemUnderTest proxy generated%}

private static class SystemUnderTest {

private javax0.geci.jamal.sample.SystemUnderTest sut = new javax0.geci.jamal.sample.SystemUnderTest();

imports the macro definitions from the resource file geci.jim. The file itself is part of the library. If you have the dependency on the classpath when the code generator and the Jamal processor runs, you can import the definition from this resource file. The macro definitions in this file are simple Jamal macros defined as text. You can have a look at them at the URL

https://github.com/verhas/javageci/blob/1.6.1/javageci-jamal/src/main/resources/geci.jim

The next line uses the beginCode user-defined macro, which is defined in geci.jim as the following:

{%@define beginCode(:x)=//<editor-fold desc=":x">%}

When this macro is used it will result the start of an editor fold that helps to keep the generated code non-intrusive when the file is opened in the IDE. When this macro is evaluated, it will be

//<editor-fold desc="SystemUnderTest proxy generated">

The next two lines start the private static inner class. It is just plain text; there is no macro in it.

Now we get to the four loops that generate proxy codes for

1. Delegating proxy methods for the private methods of the tested class.

2. Delegating proxy methods for the non-private methods declared in the class or inherited, except those inherited from the Object class.

3. Setter and getter methods for the private fields of the tested class.

4. Setter and getter methods for the non-private fields of the tested class.

Since these are very similar, I will discuss here only the first in detail.

{%!#for ($name,$type,$args) in

({%#methods

{%class javax0.geci.jamal.sample.SystemUnderTest%}

{%selector private %}

{%format/$name|$type|$args%}

%}) =

{%@options skipForEmpty%}

private $type $name({%`@argList $args%}) throws Exception {

Method m = sut.getClass().getDeclaredMethod("$name"{%`#classList ,$args%});

m.setAccessible(true);

m.invoke(sut{%`#callArgs ,$args%});

}

%}

The loop is constructed using a for macro, a Java-implemented, built-in macro of Jamal from the core package. This macro is always available for any Jamal processing. This macro iterates through a comma-separated list and repeats its contents for each list element replacing the loop variables with the actual values. There can be more than one loop variable. In such a case, like in our example, the actual value is split up along the | characters. The comma used as a list separator, and the values separator | can be redefined. In the above case, the for loop uses three-loop variables, $name, $type`, and$args. The start with a$` sign has no significance. Any string can be used as a loop variable.

The list of values is between the () characters after the in keyword. This list is the result of the evaluation of the methods built-in macro. This macro is implemented in Java and is part of the Java::Geci Jamal module. It is not a generally available Jamal macro, but when we run the code generation of Java::Geci, this JAR file is on the classpath, and thus this macro is available.

The methods macro lists the methods of a class.

The class name is taken from the user-defined macro $class, which can be defined using the user-defined macro class. The listing also considers a selector expression that can be used to filter out some of the methods. It is also provided in a user-defined macro, and there is also a helper macro in geci.jim to define it, named selector. In the example above, the selector expression is private, which will select only the private methods.

When the list is collected, the macro methods must convert it to a comma-separated list. To do that, it uses a formatting string that can contain placeholders. In our case, the placeholders are $name, $type, and $args. Every element in the list for the for loop will contain these three strings for the listed methods separated by two | characters as indicated by the format string.

The part after the = sign in the for loop is repeated for each method. It will declare a private method that invokes the same method of the tested method. To do that, it uses the help of the Java::Geci Jamal module provided built-in macros argList, classList, and callArgs. These help generating code that declares the arguments, lists the classes of the argument types or lists the arguments for the actual call.

Since this is just an article and not a full-blown documentation of Java::Geci and Jamal, I skip some details. For example, why the macro for uses the # character in front of it instead of @, why there is a backtick character in front of the macros in the loop’s body, and why the for loop uses a ! character. These details control the macro evaluation order. The list of the methods needs to be created before the for loop starts because it requires the method list. On the other hand, the macros in the loop’s body have to be evaluated after the loop generated the text for every listed method.

Also, note that this implementation is for demonstration purposes only. It simplifies the problem and does not cover all the corner cases. For example, it will generate a setter for a final field.

If you want to use this code generation, you can use the macro proxy(KLASS) defined in the resource file res:unittestproxy.jim.

You can have a look at the class UnitTestWithGeneratedUnitTestProxy, which is a tad more complex than the sample and tests these macros. The start of the generated code is the following:

/*!jamal

{%@import res:unittestproxy.jim%}\

{%beginCode SystemUnderTest proxy generated%}

{%proxy javax0.geci.jamal.unittestproxy.TestSystemUnderTest%}

{%endCode%}

*/

It merely imports the res:unittestproxy.jim file, which imports geci.jim and then uses the macro proxy to generate all the needed code covering all the corner cases.

If you want to use the code generator in your code, you have to do two things:

A. Include the dependency in your pom.xml file:

<dependency>

<groupId>com.javax0.geci</groupId>

<artifactId>javageci-jamal</artifactId>

<version>1.6.1</version>

<scope>test</scope>

</dependency>

B. Create a small unit test that runs the code generator:

@Test

@DisplayName("run the Jamal generator")

public void testRunJamalGenerator() throws Exception {

Geci geci = new Geci();

Assertions.assertFalse(

geci.register(new JamalGenerator())

.generate()

, geci.failed()

);

}

The generator runs during the unit test. During the test run, it has access to the structure of the Java code via reflection. The Jamal macros like methods, fields can query the different classes and provide the list of the methods and fields. The test fails if there was any new code generated. It only happens when the code generator runs the first time or when the tested system has changed. In this case, the test fails because the compiled code during the execution is not the final one. In such a case, start Maven again, and the second time the compilation already runs fine. Do not forget to commit the changed code. There is no risk of failing to update the generated code, like in IDE provided code generation that you have to invoke manually.

Takeaway


What you should remember from this article:

◉ Try not to test private methods. If you feel the need, you did something wrong. Probably. Possibly not.

◉ If you test private methods arrange the reflective code into a private static class that delegates the call to the original class. This will remove the implementation of the reflective access from the test and the test remains what it has to be: functionality test.

◉ If you are a lazy person, and as a good programmer you have to be, use a Java::Geci and Jamal to generate these inner classes for your tests.

◉ Master Java::Geci and Jamal and use them to generate code for your other, specific needs.

Source: javacodegeeks.com

Friday, February 19, 2021

Difference between abstract class and interface

Abstract Class, Interface, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Oracle Java Guides

Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface 
Abstract class can have abstract and non-abstract methods.  Interface can have only abstract methods. Since Java 8, it can have default and static methods also.
Abstract class doesn't support multiple inheritance.  Interface supports multiple inheritance. 
Abstract class can have final, non-final, static and non-static variables.  Interface has only static and final variables. 
Abstract class can provide the implementation of interface.  Interface can't provide the implementation of abstract class. 
The abstract keyword is used to declare abstract class.  Interface can't provide the implementation of abstract class. 
An abstract class can extend another Java class and implement multiple Java interfaces.  An interface can extend another Java interface only. 
An abstract class can be extended using keyword "extends".  An interface can be implemented using keyword "implements". 
A Java abstract class can have class members like private, protected, etc.  Members of a Java interface are public by default. 
Example:
public abstract class Shape{
public abstract void draw();
Example:
public interface Drawable{
void draw();

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).

Example of abstract class and interface in Java


Let's see a simple example where we are using interface and abstract class both.

//Creating interface that has 4 methods  
interface A{  
void a();//bydefault, public and abstract  
void b();  
void c();  
void d();  
}  
  
//Creating abstract class that provides the implementation of one method of A interface  
abstract class B implements A{  
public void c(){System.out.println("I am C");}  
}  
  
//Creating subclass of abstract class, now we need to provide the implementation of rest of the methods  
class M extends B{  
public void a(){System.out.println("I am a");}  
public void b(){System.out.println("I am b");}  
public void d(){System.out.println("I am d");}  
}  
  
//Creating a test class that calls the methods of A interface  
class Test5{  
public static void main(String args[]){  
A a=new M();  
a.a();  
a.b();  
a.c();  
a.d();  
}}  

Output:

I am a
I am b
I am c
I am d

Thursday, February 18, 2021

Programming Language For Placement – C++, Java or Python?

Many times we’ve seen students struggling with the dilemma of choosing a worthwhile Programming Language for the sake of placements. Though this situation is somewhat justifiable as among the numerous Programming Language available across the world, to pick out the one that can help you to get your DREAM JOB is not an easy job.

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Preparation, Oracle Java Guides, Oracle Java Certified

But wait…do you know that it is not that difficult to make a worthwhile choice in such a situation – yes, all you need to do is follow a strategical approach and perform several assessment practices. And with a similar concern, in this article, we’ll discuss those approaches and assessment practices that will help you to make the right choice for placements among these three renowned programming languages – C++, Java, and Python!!

Before moving further, you need to know that having sound knowledge of the particular programming language is reasonably important while going out for the tech interviews as recruiters emphasize assessing your programming knowledge and skills during multiple phases like in coding round, technical interview rounds,, etc. That means, whichever language you’re working upon, you need to get your programming fundamentals clear with it.

Now let’s take a brief look at the details of all these three programming languages:

1. C++ 


It is a general-purpose programming language that supports object-oriented programming paradigms. The language acts as a mid-level language as it can be used for both – system programming and large-scale user applications. It can be considered as the advanced version of the C Language and the basic syntax of both languages is somewhat similar. Moreover, C++ provides you with rich library support in the form of Standard Template Library. Indeed, C++ has been among one of the top programming languages for a long time and the language has a wide range of applications such as Operating Systems, Cloud/Distributed Systems, Web Browsers, and many more.  

2. JAVA


Java is an object-oriented programming language that works on Write Once, Run Anywhere principle which means the compiled JAVA code can execute on each platform that supports JAVA without doing recompilation. The language offers you various remarkable features such as portability, robustness, multithreading, security & platform-independency, and many more. Though in the last year’s index report, JAVA has seen a decline in its demand and popularity. But the language is still having much occupancy in the tech world. If we look at the numbers, there are around nearly 8-9 million JAVA Developers across the world and the language has its wide use in the development of enterprise-scale web applications and Android applications.

3. Python


Python is undeniably one of the most favorable languages for young developers, more specifically students. Most probably, the reason behind it is its simple syntax and easy to learn nature. It is a high-level, general-purpose programming language that supports multiple programming paradigms like structured, functional, and object-oriented programming. Python comes up with various worthwhile features such as extensive library support, easy integration with other languages, automatic garbage collection support, and many more. The language is being used by nearly every IT giant whether it be Google, Amazon, Facebook, or any other and it is widely used in domains like Web Development, Machine Learning, Web scraping, etc.

As of now, you must have known about these 3 languages and so you would’ve also been familiar with the fact that each programming language has its own features & use cases. Now, it’d be easier for you to make a choice among these 3 programming languages for the placement concerns based on the below-mentioned parameters:

1. Which Programming Language is Faster?

You’re recommended to start your decision-making process with this basic yet most under-rated parameter of the programming languages. The reason behind taking this factor into account is that a faster programming language is always preferred in the tech industry as it optimizes the development cost for any organization. Though, you need to remember that here faster programming language is concerned with the running time of the program rather than of developers coding time (however it saves a lot of your coding time as well through STL).

Moreover, if we take the scenario of these 3 programming languages – C++, Java, and Python – JAVA is relatively faster than Python in terms of speed and C++ is comparatively faster than the other two languages.

2. Most Relevant for Competitive Programming?

Everyone knows that Competitive Programming plays a pivotal process during the recruitment process as it adds much-needed value to your resume and sharpens your programming skills also. Hence, you need to pick out a programming language that can fulfill all the requirements for competitive programming efficiently. And, C++ is the most recommended programming language for competitive programming primarily because of the availability of a rich library known as Standard Template Library that allows you to deal with various data structures such as lists, graphs, stacks, arrays, trees, and others effectively. Also, as C++ supports Object-Oriented Programming methods, it helps you to solve real-time problems in coding contests.

3. Which Programming Language can give you an edge during Technical Interviews?

This is a bit tricky parameter. During the recruitment process, particularly in the technical interview round, the interviewer often asks you several questions related to programming functionalities. So, you need to be proficient with these programming fundamentals and concepts to do well during placements. For example – you may be asked questions based on pointers, structures & unions, etc. However, like C++, Java & Python does not come up with these low-level programming functionalities and underlying mechanisms. And apart from this low-level programming knowledge, as C++ also provides you with the knowledge of OOPs concepts, it is surely having an upper hand in this particular parameter.

4. What are your End-Goals?

NOTE: This is indeed the most important parameter of all.

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Preparation, Oracle Java Guides, Oracle Java Certified
WHY… ?? Because every programming language has its own area of expertise and applications. Okay, let us understand it with a scenario – suppose you’re looking forward to making a career in Android Development then the comparison between Java and Kotlin will be more worthwhile. Similarly, if your end goal is to get into Game Development, you can go with C++ without giving a second thought or if you’re fascinated with having a career in trending technologies like Machine Learning Artificial Intelligence, etc. – you can consider Python for that. In short, once you’ll get clear with your end-goal, it will become easier for you to understand which language is the best fit for your requirements.

Also, you need to know that once you’ll command over any low-level language like C or C++, it will hardly take you 3-4 weeks to learn other languages like Java, Python, etc. Hence, you’re strongly recommended to learn and master one language first instead of unnecessarily keep switching the languages.

So, these are several parameters based on which you can decide a particular programming language for your placement and career goals. Apart from these above-mentioned parameters, several other parameters that can also be taken into consideration are demand & popularity of the language, job opportunities, etc. Again, you must ensure to identify your requirements and area of interest before opting for any of the programming languages.

In the end, whichever programming language you would choose, you must be confident and efficient with that to get success!!

Wednesday, February 17, 2021

Developing a Module with Java 9 in Eclipse IDE, Part 2

In an earlier post, "Developing a Module with Java 9 in Eclipse IDE, Part 1," we introduced modules in Java 9. JSR 376: JavaTM Platform Module System provisions for a module system and Java 9 implements a module system. We defined a module and the associated directives of module, exports, and requires. We also discussed the objectives and benefits of the module system. In this continuation post, we shall introduce using modules in Eclipse IDE. This post has the following sections:

Setting the Environment

Download and install an Eclipse IDE edition that supports Java 9. Eclipse IDE for Java EE Developers (eclipse-jee-photon-M6-win32-x86_64.zip) is used in this tutorial.

Creating a Java Project

To create a Java project, select File>New>Java Project, as shown in Figure 1.

Figure 1: File>New>Java Project

In the New Java Project window, specify the project details, as shown in Figure 2. Specify the Project name (HelloJigsaw) and select the checkbox Use default location. For JRE, select the Use an execution environment JRE radio button and select JavaSE-9. In Project layout, select Create separate folders for sources and class files and click the Configure default link.

Figure 2: New Java Project

We need to set the build path for the source and output folders. In Preferences (Filtered), only Java>Build Path is displayed, as shown in Figure 3. In Source and output folders, select the radio button Folders. Specify the Source folder name as src and Output folder name as modules.hello.jigsaw. Click Apply and Close.

Figure 3: Setting Build Path

Having configured the project details in Create a Java Project, click Next, as shown in Figure 4.

Figure 4: New Java Project>Next

In Java Settings, the Source tab displays the folders src and modules, as shown in Figure 5. In Details, select the Create module-info.java file checkbox. The Default output folders field displays the default output folders. Click Finish.

Figure 5: Java Settings

Configuring a Module Declaration


In this section, we shall create a module declaration in the source code file module-info.java. The module declaration to add is as follows:

module hello.jigsaw {
}

The module does not declare any dependencies and does not export specific packages. By default, all packages in a module are exported. When the option to Create module-info.java file is selected, as shown in Figure 5, a New module-info.java dialog gets displayed (see Figure 6). Specify a module name which, by convention, usually starts with a lowercase letter. Specify a module name in the Module name field, hello.jigsaw as an example.

Figure 6: Specifying Module Name

A new Java project gets created, including the module-info.java source file, as shown in Figure 7.

Figure 7: Java Project HelloJigsaw

Adding the Main Class for the Module


In this section, we shall add the main class for the module. The main class is called Main and should be in a package by the same name as the module name, which is hello.jigsaw. The Main class to add is as follows; the class declares a main method that is invoked when the class is run and outputs a Hello Jigsaw message.

package hello.jigsaw;
public class Main {
   public static void main(String[] args) {
      System.out.println("Hello Jigsaw!");
   }
}

To add the Main class, right-click the HelloJigsaw project in Package Explorer and select New>Class. In the New Java Class window (see Figure 8), the Source folder should be pre-specified as HelloJigsaw/src. Specify the Package as hello.jigsaw, which is the same name as the module name. Specify the class name in the Name field as Main. Select the checkbox for adding the public static void main(String[] args) method, which makes the class a Java application, and click Finish.

Figure 8: Configuring Main Class

The Main class gets added to the Java project HelloJigsaw, as shown in the Package Explorer in Figure 9.

Figure 9: Main Class added

Copy the code for the Main class, as listed earlier, to the Main class in Eclipse IDE, as shown in Figure 10.

Figure 10: Main Class with Source Code

Configuring VM Args for the Module Path


We have created a module declaration in the module-info.java file and the Main application file. How does the Main application find the module? We need to configure VM args for the Main application to include the module path. Right-click the HelloJigsaw project in Package Explorer and select Properties. In the Properties window, select Run/Debug Settings and select the Main class (see Figure 11). Click Edit…

Figure 11: Run/Debug Settings

In Edit Configuration (see Figure 12), the Main tab is selected by default, with the application name specified in the Name field as Main. The project is specified in the Project field as HelloJigsaw. The Main class is hello.jigsaw.Main.

Figure 12: Edit Configuration

Select the Arguments tab and specify the args in the VM arguments field, as shown in Figure 13, and as listed:

--module-path modules -m hello.jigsaw.Main

The --module-path arg specifies the module path as one or more directories with modules and the -m option specifies the module. Click OK.

Figure 13: VM Arguments

In Run/Debug Settings, click Apply and Close, as shown in Figure 14.

Figure 14: Properties>Run/Debug Settings>Apply and Close

Running the Java Module Application


In this section, we shall run the Java module application. Right-click the Main.java file in Package Explorer and select Run As>Java Application, as shown in Figure 15.

Figure 15: Main.java>Run As>Java Application

The Java module application runs and outputs a Hello Jigsaw message in the Console (see Figure 16).

Figure 16: Output from Module Application

Source: developer.com