Friday, January 29, 2021

Generating a stream of Fibonacci numbers

A Java stream represents potentially an infinite sequence of data. This is a simple post that will go into the mechanics involved in generating a simple stream of Fibonacci numbers.

Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Java Career

The simplest way to get this stream of data is to use the generate method of Stream.

As you can imagine to generate a specific Fibonacci number in this sequence, the previous two numbers are required, which means the state of the previous two numbers need to be maintained somewhere. The two solutions that I will be describing here both maintain this state, however they do it differently.

Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Java Career

Mutable State


In the first approach, I am just going to maintain state this way:

class FibState {
    private long[] prev = new long[2];
    private int index = 0;
 
    public long nextFib() {
        long result = (index == 0) ? 1
                : ((index == 1) ? 1 : prev[0] + prev[1]);
        prev[0] = prev[1];
        prev[1] = result;
        index++;
        return result;
    }
}

with index keeping track of the index of the current fibonacci number in the sequence and prev capturing the most recent two in the sequence. So the next in the series is generated by mutating the index and the changing the array holding the recent values. So given this state, how do we generate the stream, using code which looks like this:

Stream<Long> streamOfFib() {
    FibState fibState = new FibState();
    return Stream.generate(() -> fibState.nextFib());
}

This is using a closure to capture the fibState and mutating it repeatedly as the stream of numbers is generated. The approach works well, though the thought of mutating one value probably should induce a level of dread – is it thread safe (probably not), will it work for parallel streams(likely not), but should suffice for cases where the access is strictly sequential. A far better approach is to get a version of state that is immutable.

Immutable State


class FibState {
    private final long[] prev;
    private final int index;
 
    public FibState() {
        this(new long[]{-1, 1}, 0);
    }
 
    public FibState(long[] prev, int index) {
        this.prev = prev;
        this.index = index;
    }
 
    public FibState nextFib() {
        int nextIndex = index + 1;
        long result = (nextIndex == 1) ? 1 : prev[0] + prev[1];
        return new FibState(new long[]{prev[1], result}, nextIndex);
    }
 
    public long getValue() {
        return prev[1];
    }
}

Instead of mutating the state, it returns the next immutable state. Alright, so now that this version of state is available, how can it be used – by using the “iterate” function of Stream, like this:

Stream<Long> streamOfFib() {
    return Stream
            .iterate(new FibState(), fibState -> fibState.nextFib())
            .map(fibState -> fibState.getValue());
}

this function takes two parameters – the initial state and something which can generate the next state. Also to return numbers from it, I am mapping this “state” type to a number in the “map” operation.

Wednesday, January 27, 2021

The Temporary Test Property

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

It may be seen in languages such as JavaScript where there’s a master let setting up some useful variables for various tests to use to assign values to. I’ve more seen it in Java though, where there can be a sort of phobia of creating temporary variables inside tests, so instead all the variables are declared in the parent class.

Let’s look at a quick example:

class ParagraphAnalyzerTest {

    private String analyzed;

    private ParagraphAnalyzer analyzer = new ParagraphAnalyzer();

    @Test

    void nouns() {

        analyzed = analyzer.justNouns("This is a word");

        assertThat(analyzed).isEqualTo("word");

    }

    @Test

    void verbs() {

        analyzed = analyzer.justVerbs("This is a word");

        assertThat(analyzed).isEqualTo("is");

    }

    @Test

    void ends() {

        analyzed = analyzer.first("This is a word");

        assertThat(analyzed).isEqualTo("This");

        analyzed = analyzer.last("This is a word");

        assertThat(analyzed).isEqualTo("words");

    }

}

In the above simple, fictional example, the test class has two members. There’s ParagraphAnalyzer which is the code under test and which it seems to make sense to have as a member of the fixture. Then there’s analyzed which seems to have a different value in each test.

The fact that each test gives its own value to the analyzed is a smell that analyzed is not being managed by the test fixture and so does not belong as a property of it.

We’re saving a repeated declaration of a String every time… which is so very not worth the baggage of this risky shared property.

Now, the risk is probably nothing, because the above test will create a new instance of the class for each test case, so there’s no bleed between states… but that’s only true if I don’t change the test instance lifecycle. JUnit 5 will let me do this differently. Plus, if I’m in the habit of using members for temp variables, what’s to stop me doing that with static members as well?

There’s no justification for this temp variable being promoted somewhere higher up the food chain.

You may also notice another test anti-pattern in the last unit test, above. The value of analyzed is being reassigned. Another awkward move. This is the Two For the Price of One test smell, where a single test case is executing two independent use cases.

When To Use What?

Oracle Java Exam Prep, Oracle Java Preparation, Oracle Java Certification, Oracle Java Career, Core Java, Oracle Java Tutorial and Material
Consider each test case as having its own state. The test case inherits any commonly set up or torn down state from the test fixture. This approach avoids code repetition, and other difficulties with setting up expensive resources for each test.

But… as soon as the common set up is done, each test case should do its own thing, clearly and without littering the test fixture with its problems.

Storing what is essentially request scope in the instance state of an object is an anti pattern outside of testing and should be considered on inside it too!

Monday, January 25, 2021

Extends vs Implements in Java

Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Prep, Java Preparation

Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. There are two main keywords, “extends” and “implements” which are used in Java for inheritance. In this article, the difference between extends and implements is discussed.

Before getting into the differences, lets first understand in what scenarios each of the keywords are used.

Extends: In Java, the extends keyword is used to indicate that the class which is being defined is derived from the base class using inheritance. So basically, extends keyword is used to extend the functionality of the parent class to the subclass. In Java, multiple inheritances are not allowed due to ambiguity. Therefore, a class can extend only one class to avoid ambiguity.

Example:

class One { 

public void methodOne() 

// Some Functionality 

class Two extends One { 

public static void main(String args[]) 

Two t = new Two(); 

// Calls the method one 

// of the above class 

t.methodOne(); 

Implements: In Java, the implements keyword is used to implement an interface. An interface is a special type of class which implements a complete abstraction and only contains abstract methods. To access the interface methods, the interface must be “implemented” by another class with the implements keyword and the methods need to be implemented in the class which is inheriting the properties of the interface. Since an interface is not having the implementation of the methods, a class can implement any number of interfaces at a time.

Example

// Defining an interface 
interface One { 
public void methodOne(); 

// Defining the second interface 
interface Two { 
public void methodTwo(); 

// Implementing the two interfaces 
class Three implements One, Two { 
public void methodOne() 

// Implementation of the method 

public void methodTwo() 

// Implementation of the method 

Note: A class can extend a class and can implement any number of interfaces simultaneously.

Example

// Defining the interface 
interface One { 

// Abstract method 
void methodOne(); 

// Defining a class 
class Two { 

// Defining a method 
public void methodTwo() 

// Class which extends the class Two 
// and implements the interface One 
class Three extends Two implements One { 

public void methodOne() 

// Implementation of the method 

Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Prep, Java Preparation
Note: An interface can extend any number of interfaces at a time.

Example:

// Defining the interface One 
interface One { 
void methodOne(); 

// Defining the interface Two 
interface Two { 
void methodTwo(); 

// Interface extending both the 
// defined interfaces 
interface Three extends One, Two { 

The following table explains the difference between the extends and interface:

Extends Implements 
By using “extends” keyword a class can inherit another class, or an interface can inherit other interfaces  By using “implements” keyword a class can implement an interface
It is not compulsory that subclass that extends a superclass override all the methods in a superclass.  It is compulsory that class implementing an interface has to implement all the methods of that interface. 
Only one superclass can be extended by a class.  A class can implement any number of an interface at a time 
Any number of interfaces can be extended by interface.  An interface can never implement any other interface

Friday, January 22, 2021

Testing Logging Output in Java

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

Testing that the logged output is as expected seems to be on the cusp of a good/bad idea. Is the logged output the intended behavior of the application? or is it an implementation detail that you’re just mirroring in a test?

Arguably, it’s sometimes the former… logging is the sort of thing that matters when it matters.

I’d argue that it’s often too low level a thing to be testing, but it’s a critical thing to test when:

◉ You’re writing a logging framework that centralises the logging logic

◉ You have some exceptional case that MUST be logged differently and need to lock down the behaviour

◉ Logging IS the logic for some reason

Note, I like to think of tests as locking down the logic – we wrote the code this way today, hopefully using TDD, to achieve something observable by a test. The test keeps that observable behaviour from disappearing by going red if someone breaks it. So the test locks down some spec.

Logging in the Modern World

These days we deliberately log to the System console, rather than log files. This works well when we’re containerising our application, or writing an AWS Lambda, and we want the hosting environment’s log scraper to pull the logs from stdout rather than mine log files as we write them.

Spooling log messages to the console, while once thought of as a no-no, is essentially a lot cleaner than telling a logging agent to go and read a file as we write it.

Can’t We Just Watch System.out Then?

Well, indeed we can. No need to register a listener into the logging framework. Let’s just look at what appears on the console. We can configure our logger to write to the console – in fact it probably does already!

Enter System Stubs

I will write more about it in due course, but System Stubs is a testing library I’ve worked hard on in recent weeks. It started life as a different project that I forked, and then I essentially reworked it to fit in with the sort of tests I’ve been writing. As such, it’s available as a JUnit 5 extension (as well as in other forms).

Let’s imagine we have some code under test that’s going to do some logging, and we want to see if a certain message appears.

Here’s a test:

@ExtendWith(SystemStubsExtension.class)

class TheOneAboutTheLoggingTest {

    @SystemStub

    private SystemOut systemOut;

    @Test

    void youKnow_ForLogging() {

         doTheThingThatShouldLog();

         assertThat(systemOut.getLines())

             .anyMatch(line -> line.contains("ERROR This is bad!"));

    }

}

Let’s just unpack a few of the elements in the above.

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Exam Prep, Java Preparation, Oracle Java Learning
There’s the JUnit 5 extension – SystemStubsExtension. No big deal. Then there’s a SystemOut object, which is used to capture System.out while the object is active. The object is created by the extension and is activated just before the test, then cleared up afterwards.

While the test is running, System.out is not appearing in the console, it’s being stored in the memory of the SystemOut object’s TapStream.

At any point we can expect the lines of text that have appeared on System.out. The getLines function provides a Stream<String> which we inspect here using AssertJ.

Given logging output usually contains timestamps, this method requires us to do some sort of substring checking to avoid having to predict the timestamp. Perhaps a future library might help parse the output a little more.

It’s also worth noting that NOT seeing the logging output on the console is a little annoying during this sort of test. In due course, I’m planning to release version 1.2.0 of SystemStubs which will allow a multiplex where the output appears on the console AND is also tapped.

So is Tapping System.out the Future of Log Testing?

Yes and no.

It’s enormously convenient and easy to do. So, I’m inclined to default to it.

However, for fine-grained testing of exactly what is being sent to the logging library, the reading of strings from a console is a bit messy.

Source: javacodegeeks.com

Wednesday, January 20, 2021

How to get current date time with Java 8

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

In this quick tutorial, we will see, how to get current date time using Java 8.

Java 8 had come up with new set of classes for date and time under java.time package, which are:

–  java.time.Instant

– java.time.ZonedDateTime

– java.time.OffSetDateTime

– java.time.LocalDateTime

Let us see how we can get current date and time using these classes and how they are different from each other.

Using Instant 

Instant represents a moment. For example, if World cup is starting at certain moment, it is exact that moment for everyone living in any part of world. If world cup is in Australia, then people in India can say that ,world cup started at different time than what what was time in Australia but it started at exact same moment on timeline for people of Australia as well as India. 

Using Instant, we can get the exact moment on timeline which is independent from time zones.

which in other words means that if two Instant objects are created at the same moment in any part of world, they will have exactly same value.

Instant represents date time in UTC(coordinated universal time), so it does not consider specific Zone and it is number of nanoseconds elapsed since epoch or since 1970-01-01T00:00:00Z. It is similar to GMT(Greenwich mean time).

All date times for specific Zones are calculated relative to UTC. 

For example: 

– A time in UTC (zone) itself, UTC + 0 is indicated by a Z( Z from Zulu time)

– Countries like Ireland, Portugal, Ghana follows UTC time zone, which means UTC + 0

– Japan follows UTC+9

– Barbados follows UTC-4

For complete list for all countries, you can check List of Countries with UTC time offsets

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Guides, Oracle Java Preparation
For our back end calculations in Java, we use Instant. For example, If we are running a job and want to calculate the time for next run we would use Instant. 

Now coming back to current date-time using Instant, we need to use now() method as below:

Instant instant = Instant.now();

System.out.println("Current Date Time using Instant:" + instant);

Output:

Current Date Time using Instant:2021-01-09T22:25:06.385917300Z

Using ZonedDateTime

If you want to know date time, in your time zone, at a particular moment( represented by Instant) you can use ZonedDateTime.

You can either adjust the instant created above to get the ZonedDateTime like below:

Adjusting Instant object

System.out.println("Using instant.atZone():" + instant.atZone(ZoneId.of("Europe/Amsterdam")));

Output:

Using instant.atZone():2021-01-09T23:25:06.385917300+01:00[Europe/Amsterdam]

This gives me exact date time in Amsterdam.

Using now(ZoneId zoneId):

Alternatively you can use factory method now(ZoneId zoneId) defined in ZonedDateTime class itself like below:

System.out.println("Using ZonedDateTime.now(zoneId):" + ZonedDateTime.now(ZoneId.of("Europe/Amsterdam")));

Output:

Using ZonedDateTime.now(zoneId):2021-01-09T23:25:06.408922700+01:00[Europe/Amsterdam]

Using now():

And there is one more option where in you can use factory method now() of ZonedDateTime class. However you must know that now() uses the default time zone of your JVM, which is subject to change, so better always pass zoneId.

System.out.println("ZonedDateTime with now():" + ZonedDateTime.now());

Output:

Using ZonedDateTime.now():2021-01-09T23:25:06.414919900+01:00[Europe/Berlin]

Another variant of now() is like below for using default time zone using ZoneId.systemDefault() as ZoneId.

System.out.println("Using ZonedDateTime.now(ZoneId.systemDefault())" + ZonedDateTime.now(ZoneId.systemDefault()));

Output:

Using ZonedDateTime.now(ZoneId.systemDefault()):2021-01-09T23:25:06.414919900+01:00[Europe/Berlin]

ZonedDateTime supports Day Light Savings

ZonedDateTime uses ZoneRules to determine how an offset varies for a particular time zone in case of Day light saving.

Lets take an example. Day light saving in Netherlands in 2021 is going to start from March 28, 2:00 AM and will end on October 31, 3:00 AM

Let us first try to see date time before(by 1 hour) Day light saving starts, i.e. at 1 AM

System.out.println("ZonedDateTime.of() before DLS: " + ZonedDateTime.of(2021, 3, 28, 1, 0, 0,0, ZoneId.of("Europe/Amsterdam")));

Output:

ZonedDateTime.of() before DLS: 2021-03-28T01:00+01:00[Europe/Amsterdam]

As you can see, it returned the time which we have asked for i.e. 1 AM and offset is of +1:00

Now let us try to see date time at the time when Day light saving is going to start i.e. at 2 AM.

System.out.println("ZonedDateTime.of() DLS start: " + ZonedDateTime.of(2021, 3, 28, 2, 0, 0,0, ZoneId.of("Europe/Amsterdam")));

Output: 

ZonedDateTime.of() DLS start: 2021-03-28T03:00+02:00[Europe/Amsterdam]

As you can see , ZonedDateTime API automatically adjusted the time and returned time which is 1 hour ahead i.e. 3 AM instead of 2 AM and also now Offset is set to +2:00.

Using OffsetDateTime

OffsetDateTime represents a moment in date time which is some duration ahead(+) or behind(-) the UTC or in other words with offset from UTC without a Time ZoneId such as “Europe/Amsterdam”.

You can use ZoneOffset class to represent offset in hours, hours: minutes or hours: minutes: seconds.

So if the OffSet is zero, then OffsetDatTime represents Instant, which is in UTC.

System.out.println("Using OffsetDateTime.now():" + OffsetDateTime.now());

Output:

Using OffsetDateTime.now():2021-01-09T23:25:06.415920100+01:00

Using LocalDateTime

LocalDateTime gives you date time without any offset(from UTC) information or any Zone information, which in other words means it can not represent moment on the timeline.

LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("localDateTime is:" + localDateTime);

Output:
localDateTime is:2021-01-09T23:25:06.416918700

Monday, January 18, 2021

Static Nested Classes Java

Static Nested Classes Java, Oracle Java Exam Prep, Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Career

In Java, it is possible to define a class within another class. Class defined within another Class is called a Nested Class.

Nested class is treated as a member of the Outer class because it is also defined within the Outer class like its other members(variables or methods).

public class OuterClass {

    class NestedClass {

    }

}

Although Outer class can be declared only either as public or package private(no access modifier) but Nested classes can have any of the access modifier public, private, protected or package private(no access modifier), reason being , nested class is also just like a member of the Outer class, so just like you can have public, private ,protected or package private instance variables or methods, you can have these access modifiers for nested classes as well.

Now if you define your nested class as static, then they are called static nested class and if you don’t define them as static then they are called non static nested classes or Inner classes. So Nested classes are broadly of two types :

– Static Nested Classes

– Inner Classes   

In this post, we will discuss static nested classes.

Static Nested Class:


They are just like any other Java class which are defined with a static modifier within a Outer class for the packaging convenience and from packaging convenience I mean that instead of creating another top level class we packaged this nested class within another class as this nested class made sense only in the context of enclosing Outer class. We will see example later.

public class OuterClass {
    public static class NestedClass {
 
    }
}

Rules for static nested class as a static member of Outer class


Rules for instantiating static nested class

Because static nested classes are static ,so just like the static methods and variables they follow the rules which static members within a class follows. So just like static methods and variables, they belong to their Outer class and not to the instance(s) of the Outer class. So you don’t need to instantiate OuterClass first but you just use <outer class><dot><nested class> syntax to instantiate the nested classes as in below example.

public class TestClass {
    public static void main(String[] args) {
        OuterClass.NestedClass nestedClass = new OuterClass.NestedClass();
    }
}

Rules for accessing the Outer class members from static nested class

Static nested class being static, can only access the static members of its outer class. It does not have access to the instance members of the Outer class. This makes sense again, if you think just from static perspective. Any static method of our class in general can only access the static variables or static methods only, so the same concept is applied for static nested classes as well, because they are also the static members of the Outer class from Outer class perspective.

public class OuterClass {
    private static String x;
    private String y;
 
    public static class NestedClass {
        public void test() {
            // x is accessible
            System.out.println(x);
 
            // y is not accessible here and it will give compiler time error 
            // "No static field 'y' can not be referenced from static context.
            System.out.println(y);
        }
    }
}

You might have noticed that test() method itself is not static but still the compiler warning says “can not be referenced from static context”, this is because although test() method is not a static method but still the class in which it has been defined as , is static, so from OuterClass perspective “y” which is not a static member of OuterClass is being referred from within it’s static member NestedClass.

Other than that from its own existence perspective, they are just like any normal Java classes, which means :

– You can create their objects(By using <OuterClass><dot><NestedClass> syntax).

– You can have instance variables within them.

– You can have instance methods within them.

– You can have static methods in them.

– You can extend them.

– You can declare them final.

Only difference from top level java class is that it can be declared static and it can have any of the access modifier which means public, package private, protected or private.

So to conclude this section, you need to see static nested classes from two perspective :

– As a static member of the Outer class and rules for accessing it(nested class) being a static member     And rules for accessing Outer class members.

– As a normal Java class which is just packaged within another class.

What is the use of Static nested Classes ?


1. Packaging Convenience and as Helper classes

In general, we use nested class when the class is not required to be used anywhere else other than in the class it is part of. For example we can define helper classes using nested static classes. And if they need to be accessed also from within Outer class only, we can declare static nested class as private, so that it is invisible to the outside world.

For example: 

Static Nested Classes Java, Oracle Java Exam Prep, Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Career
1. If we see java.util.Collections class in JDK, you can find lots of private nested classes like:

SetFromMap

ReverseComparator

CopiesList

As these classes serve only to Collections class, are not being used from anywhere else in JDK and does not use any instance variable or method of the outer Collection class, they have been kept as private and nested static classes.

2. Static nested classes specially should be used(instead of inner classes) when you don’t want to use enclosing class’s instance members in nested class but want to keep Outer class and Nested class together for packaging convenience. For example, in the Builder Pattern that we discussed in one of previous post, Builder is created as static nested class. This builder does not use/call any of the Outer class instance variable/method but as we know that this builder makes sense only in context of Student class, so we packaged Student and its builder together.

And we can instantiate this static nested builder without using the instance of the Outer class as below:

Student.StudentBuilder studentBuilder2 = new Student.StudentBuilder("2",                                                                                                     "Sachin", "Tendulkar").withAge("47");

3. They are very useful for creating Request and Response type of classes for your restful services as you can easily map them to the Json structure.

public class Employee {
    private String name;
    private String age;
 
    public static class Address {
        private int houseNumber;
        private String streetName;
    }
}

2. Better Readability and Maintainability 

It leads to more readable and maintainable code because you keep closely used classes together at one place instead of spreading it across in multiple top level classes.

Friday, January 15, 2021

Difference between Java and C language

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Guide, Oracle Java Prep

Here are some of the differences between Java and C language. 

C is much faster than Java

Java is slower than C due to overhead.

C JAVA 
C was developed by Dennis M. Ritchie between 1969 and 1973. Java was developed by James Gosling in 1995.
C is a Procedural Programming Language.  Java is Object-Oriented language. 
C is more procedure-oriented.  Java is more data-oriented. 
C is a middle-level language because binding of the gaps takes place between machine level language and high-level languages.  Java is a high-level language because translation of code takes place into machine language using compiler or interpreter. 
C is a compiled language that is it converts the code into machine language so that it could be understood by the machine or system.  Java is an Interpreted language that is in Java, the code is first transformed into bytecode and that bytecode is then executed by the JVM (Java Virtual Machine). 
C generally breaks down to functions.  Java breaks down to Objects. 
C programming language can be used for system programming as well as Application programming.   This is not the case in Java. 
C does not contain the property called Inheritance because it does not support OOPS, which is very useful for code reusability. Thus C is not suited when one has to relate the things according to the real world.  Java contains the property of Inheritance which is very useful in code reuseability. 
Memory allocation can be done by malloc in C  Memory allocation can be done by a new keyword in Java. 
C is a low-level language. It has difficult interpretation for the user but it has a closer significance to the machine-level code.  Java is a high-level language because translation of code takes place into machine language using compiler or interpreter. 
In C89 declaration of variables is at the beginning of the block but in the latest version of C that is C99 we can also declare variables anywhere.  We can declare variables anywhere. 
free is used for freeing the memory in C.   A compiler will free up the memory internally by calling the garbage collector.  
C does not supports Threading.  Java supports the concept of threading. 
C supports pointers.  Java does not supports pointers. 
It is not portable.  It is portable. 
Call by value and call by reference is supported in C.  It only supports a call by value. 
C is platform dependent.  Java is a platform independent. 
It supports user-based memory management.  It internally manages the memory. 
C is not robust that is strict type checking does not takes place while compile and run time.  Java is robust. 
Exception handling cannot be directly achieved in C and thus it lacks the maintenance of normal flow of the program.  Exception Handling is supported in Java. 
It follows a top-down approach.  Java follows a bottom-up approach.
Overloading functionality is not supported by C.   Java supports method overloading which helps in code readability. 
C supports Preprocessors. Java does not support Preprocessors. 
C does not supports OOPS concept.  Java supports OOPS concept. 
Union and structure datatypes are supported by C.  Java does not supports union and structures. 
C supports the storage classes.  Whereas Java does not suport the storage classes. 
It has 32 keywords.  It has 50 keywords. 
Go-to statements are supported in C language.  Java does not supports go-to statements. 
Virtual keywords are supported by C.  Virtual keywords are not supported by Java. 
Overloading functionality is not supported by C.  Java supports method overloading which helps in code readability. 
Default members of C are public.  Default members of Java are private. 
Data hiding is done by using static in C.  Data hiding is done by using private in Java. 

Wednesday, January 13, 2021

Builder Design Pattern

Oracle Java Exam Prep, Oracle Java Tutorial and Material, Core Java, Oracle Java Learning, Oracle Java certification

We will discuss Builder design pattern.

Key topics we are going to discuss are :

– Which category Builder Design Pattern falls in ?

– What problem builder Pattern is solving or when to use Builder pattern?

– Builder Pattern

– Builder Pattern Example

– Advantages of Builder Pattern

– Disadvantages of Builder Pattern

Which category Builder Design Pattern falls in ?

Builder pattern falls under Creational design patterns category, as it deals with the creation of object(s).Please note that Builder design pattern that I am going to describe here is not GOF design pattern but the one suggested by Joshua block in

Effective Java, as I personally see this pattern used for more often or more practical than the one suggested by GOF.

What problem builder Pattern is solving or when to use Builder pattern?

In nutshell, you should use Builder design pattern when :

– You have a class, which has some mandatory fields and some optional fields, which in other words means that your object can be constructed in various ways as per requirements. Although you are free to use it with a class with all mandatory fields as well when number of fields are too many(usually more than four is a good candidate).

– You want objects of your class to be immutable, which means once objects are instantiated there state can not be changed after that.

Now lets discuss these points in more detail.

You have a class with some mandatory and some optional fields :

What is the problem with having optional fields.

Let us say you have below Student class with mandatory and optional fields and have a constructor with all the fields.

package com.blogspot.oraclejavacertified;

public class Student {

    //mandatory fields

    private final String id;

    private String firstName;

    private String lastName;                                                                                                                                            //optional fields

    private String age;

    private String houseNumber;

    private String streetNumber;

    public Student(String id, String firstName, String lastName, String age, String houseNumber, String streetNumber) {

        this.id = id;

        this.firstName = firstName;

        this.lastName = lastName;

        this.age = age;

        this.houseNumber = houseNumber;

        this.streetNumber = streetNumber;

    }

    public String getId() {

        return id;

    }

    public String getFirstName() {

        return firstName;

    }

    public String getLastName() {

        return lastName;

    }

    public String getAge() {

        return age;

    }

    public String getHouseNumber() {

        return houseNumber;

    }

    public String getStreetNumber() {

        return streetNumber;

    }

}

Now, say the client of this code might want to create instance of Student with

– Only Mandatory fields

– All the Mandatory as well as optional fields

– Mandatory fields and one or more of the optional fields

Then the constructors for above scenarios will look like as below :

//Only Mandatory fields                                                       Student student2 = new Student("201", "firstName2", "surName2", null, null, null);

//All the Mandatory as well as optional fields                               Student student1 = new Student("101", "firstName1", "surName1", "16", "11", "2");

//Mandatory fields and one or more optional fields                           Student student3 = new Student("301", "firstName3", "surName3", "20", null, null);

Student student4 = new Student("301", "firstName4", "surName4", "20", "22", null);

Now, what is the problem with the above constructors?

Actually, there are multiple problems, like

– Client code has to unnecessarily pass null for all optional fields.

– Code readability is not good. As the number of parameters grow, it becomes difficult and error prone for client code to understand what needs to be passed at which position and later to read for the person who is going to maintain the code.

– When adjacent parameters are of same data type, you might accidently exchange their values which will go unnoticed at compile time but create some severe bug at run time. For example, developer can accidently interchange values for age and houseNumber.

So What can you do to solve these problems ?

Probably we can have look at the Telescoping constructor pattern.

Oracle Java Exam Prep, Oracle Java Tutorial and Material, Core Java, Oracle Java Learning, Oracle Java certification
In Telescoping constructor pattern, we create multiple constructor overloads starting with one with all mandatory fields and then with one optional field and then with two optional fields and so on until we have constructor with all fields.

Each constructor calls another constructor with one more optional field and passes the default value for the optional field(can be null or any other default you want to set) until the last constructor with all optional fields is called.

package com.blogspot.oraclejavacertified;

public class Student {

    //Mandatory fields

    private String id;

    private String firstName;

    private String lastName;

    //Optional fields

    private String age;

    private String houseNumber;

    private String streetNumber;

    public Student(String id, String firstName, String lastName) {

        this(id, firstName, lastName, "0");

    }

    public Student(String id, String firstName, String lastName, String age) {

        this(id, firstName, lastName, age, "0");

    }

    public Student(String id, String firstName, String lastName, String age, String houseNumber) {

        this(id, firstName, lastName, age, houseNumber, "0");

    }

    public Student(String id, String firstName, String lastName, String age, String houseNumber, String streetNumber) {

        this.id = id;

        this.firstName = firstName;

        this.lastName = lastName;

        this.age = age;

        this.houseNumber = houseNumber;

        this.streetNumber = streetNumber;

    }

}

Now let us see which problems telescoping constructor solved :

– Client code no longer has to pass null for all the optional fields as well.

– From client code perspective, readability is better.

But telescoping constructors comes with its own problems:

– What if more optional fields are added in Student class in future, then for each new field another constructor needs to be introduced.

– Still you need to carefully see all overloads of the constructor and choose the one which suits your requirement.

– Still if you have say age and streetNumber but houseNumber is not available, then you need to instantiate Student class like below, so still client need to pass in null value for optional field.

Student student = new Student("101", "firstName", "lastName", "35", null, "3");

– And still there is possibility of getting exchange of values of same data type, when the number of optional fields are too many.

We will see how builder pattern solves these problems later but for now let us discuss the other aspect which makes a case for using builder pattern.

You want objects of your class to be immutable :

If you don’t want state of your object to get changed once it has been created(and of course it has lots of fields), you can use build pattern, as builder pattern makes sure your object is immutable once it is created.

Advantages of Immutable classes :

– They are more reliable as it is known that their state is not going to change after creation.

– They are inherently thread safe and don’t need any synchronization.

– They make great candidates to be used as a key of a HashMap or to be put in a HashSet.

Now let us see implementation of Builder pattern by taking example of our Student class.

Builder pattern

– In builder pattern , you leave the responsibility of creating object or instantiating your class to Builder which is another class which has exactly same number of fields as your class whose objects builder is going to build.

– As your builder class is going to be used only for creating objects of your class and is not going to be used elsewhere, it is defined as static nested class within your class.

– You provide a builder’s constructor with only mandatory fields and then you provide methods(mutators) in builder to set the remaining optional fields. You can chain these methods as each of these method again returns Builder. Note that till now we are talking only about using builder constructor and using methods to set other optional fields and all these are still part of Builder object and we have not yet created actual Student object, so we are not concerned about immutability yet.

So in terms of code, we are here :

Student.StudentBuilder studentBuilder2 = ("2",                                                                               "Sachin", "Tendulkar").withAge("47");

Now all we need to do is call build() method of our builder on the created builder instance like below :

studentBuilder2.build()

which in turn calls private constructor of the Student class and passes “this” reference which is reference to the builder which is calling build() method.

public Student build() {
     return new Student(this);
}

In the constructor, values are copied from builder to the Student instance variables and a complete immutable student object is created.

private Student(StudentBuilder studentBuilder) {                                            
    id = studentBuilder.id;                                                            
    firstName = studentBuilder.firstName                                            
    lastName = studentBuilder.lastName;                                                
    age = studentBuilder.age;                                                        
    houseNumber = studentBuilder.houseNumber;                                        
    streetNumber = studentBuilder.streetNumber;                                
}

Builder pattern example


package com.test.builder;
 
public class Student {
    //Mandatory fields
    private final String id;
    private final String firstName;
    private final String lastName;
 
    //Optional fields
    private final String age;
    private final String houseNumber;
    private final String streetNumber;
 
    private Student(StudentBuilder studentBuilder) {
        id = studentBuilder.id;
        firstName = studentBuilder.firstName;
        lastName = studentBuilder.lastName;
        age = studentBuilder.age;
        houseNumber = studentBuilder.houseNumber;
        streetNumber = studentBuilder.streetNumber;
    }
 
    public String getId() {
        return id;
    }
 
    public String getFirstName() {
        return firstName;
    }
 
    public String getLastName() {
        return lastName;
    }
 
    public String getAge() {
        return age;
    }
 
    public String getHouseNumber() {
        return houseNumber;
    }
 
    public String getStreetNumber() {
        return streetNumber;
    }
 
    public static class StudentBuilder {
        //Mandatory fields
        private final String id;
        private final String firstName;
        private final String lastName;
 
        //Optional fields
        private String age;
        private String houseNumber;
        private String streetNumber;
 
        public StudentBuilder(String id, String firstName, String lastName) {
            this.id = id;
            this.firstName = firstName;
            this.lastName = lastName;
        }
 
        public StudentBuilder withAge(String age) {
            this.age = age;
            return this;
        }
 
        public StudentBuilder withHouseNumber(String houseNumber) {
            this.houseNumber = houseNumber;
            return this;
        }
 
        public StudentBuilder withStreetNumber(String streetNumber) {
            this.streetNumber = streetNumber;
            return this;
        }
 
        public Student build() {
            return new Student(this);
        }
     }
 
    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", age='" + age + '\'' +
                ", houseNumber='" + houseNumber + '\'' +
                ", streetNumber='" + streetNumber + '\'' +
                '}';
    }
}

and here is the test class :

package com.blogspot.oraclejavacertified;
 
public class TestStudentBuilder {
    public static void main(String[] args) {
        Student.StudentBuilder studentBuilder1 = new Student.StudentBuilder("1",                                              "Gauarv", "Bhardwaj");
        System.out.println(studentBuilder1.build());
 
        Student.StudentBuilder studentBuilder2 = new Student.StudentBuilder("2",                                             "Sachin", "Tendulkar").withAge("47");
        System.out.println(studentBuilder2.build());
    }
}

and here is the output:

Student{id='1', firstName='Gauarv', lastName='Bhardwaj', age='null', houseNumber='null', streetNumber='null'}
Student{id='1', firstName='Sachin', lastName='Tendulkar', age='47', houseNumber='null', streetNumber='null'}

Advantages of Builder Pattern :


– Client code is much more clean and readable. If we want to create object only with the mandatory fields ,we can just create builder instance with mandatory fields and then call build() method which will return us the Student object with only mandatory fields, however if we want to create Student object with some optional fields we can call respective methods like withAge() or withHouseNumber() and get Student object with all these fields as well. So we are not forcing client code to pass unnecessarily null values for the optional fields.

– Problem with getting values exchanged is also resolved as optional fields can be added by calling their respective methods which have clearly defined names.

– Object created using Builder pattern is immutable, as there are no setters in the Student class and also the constructor is private, so the only way to create Student object is via builder.

Disadvantages of Builder Pattern :


– Disadvantage is that you have to write lot of extra code for Builder class and as and when you need to add more fields, you need to add those fields both to your Student class as well as to your builder class. This is one of the reason that you should keep your Builder class within your class to be built as static nested class so that you don’t miss to add new field to builder as well .

Overall better code readability and immutability that Builder patter offers overweighs disadvantages it has, in my opinion.

Tuesday, January 12, 2021

Why Java is not a purely Object-Oriented Language?

Oracle Java Certification, Oracle Java Learning, Oracle Java Exam Prep, Oracle Java Career

Pure Object Oriented Language or Complete Object Oriented Language are Fully Object Oriented Language which supports or have features which treats everything inside program as objects. It doesn’t support primitive datatype(like int, char, float, bool, etc.). There are seven qualities to be satisfied for a programming language to be pure Object Oriented. They are:

1. Encapsulation/Data Hiding

2. Inheritance

3. Polymorphism

4. Abstraction

5. All predefined types are objects

6. All user defined types are objects

7. All operations performed on objects must be only through methods exposed at the objects.

Example: Smalltalk

Why Java is not a Pure Object Oriented Language?

Java supports property 1, 2, 3, 4 and 6 but fails to support property 5 and 7 given above. Java language is not a Pure Object Oriented Language as it contain these properties:

◉ Primitive Data Type ex. int, long, bool, float, char, etc as Objects: Smalltalk is a “pure” object-oriented programming language unlike Java and C++ as there is no difference between values which are objects and values which are primitive types. In Smalltalk, primitive values such as integers, booleans and characters are also objects.

In Java, we have predefined types as non-objects (primitive types).

int a = 5; 

System.out.print(a);

◉ The static keyword: When we declares a class as static then it can be used without the use of an object in Java. If we are using static function or static variable then we can’t call that function or variable by using dot(.) or class object defying object oriented feature.

◉ Wrapper Class: Wrapper class provides the mechanism to convert primitive into object and object into primitive. In Java, you can use Integer, Float etc. instead of int, float etc. We can communicate with objects without calling their methods. ex. using arithmetic operators.

String s1 = "ABC" + "A" ;

Oracle Java Certification, Oracle Java Learning, Oracle Java Exam Prep, Oracle Java Career

Even using Wrapper classes does not make Java a pure OOP language, as internally it will use the operations like Unboxing and Autoboxing. So if you create instead of int Integer and do any mathematical operation on it, under the hoods Java is going to use primitive type int only.

public class BoxingExample 

public static void main(String[] args) 

Integer i = new Integer(10); 

Integer j = new Integer(20); 

Integer k = new Integer(i.intValue() + j.intValue()); 

System.out.println("Output: "+ k); 

In the above code, there are 2 problems where Java fails to work as pure OOP:

1. While creating Integer class you are using primitive type “int” i.e. numbers 10, 20.
2. While doing addition Java is using primitive type “int”.

Monday, January 11, 2021

enum in Java

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

Enumerations serve the purpose of representing a group of named constants in a programming language. For example the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. Other examples include natural enumerated types (like the planets, days of the week, colors, directions, etc.).

Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command line flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time.

In Java (from 1.5), enums are represented using enum data type. In Java, we can also add variables, methods and constructors to it. The main objective of enum is to define our own data types(Enumerated Data Types).

Declaration of enum in java :

◉ Enum declaration can be done outside a Class or inside a Class but not inside a Method.

// A simple enum example where enum is declared 

// outside any class (Note enum keyword instead of 

// class keyword) 

enum Color 

RED, GREEN, BLUE; 

public class Test 

// Driver method 

public static void main(String[] args) 

Color c1 = Color.RED; 

System.out.println(c1); 

}

Output :

RED

// enum declaration inside a class. 
public class Test 
enum Color 
RED, GREEN, BLUE; 

// Driver method 
public static void main(String[] args) 
Color c1 = Color.RED; 
System.out.println(c1); 
}

Output :

RED

◉ First line inside enum should be list of constants and then other things like methods, variables and constructor.

◉ According to Java naming conventions, it is recommended that we name constant with all capital letters

Important points of enum :


◉ Every enum internally implemented by using Class.

/* internally above enum Color is converted to
class Color
{
     public static final Color RED = new Color();
     public static final Color BLUE = new Color();
     public static final Color GREEN = new Color();
}*/

◉ Every enum constant represents an object of type enum.
◉ enum type can be passed as an argument to switch statement.

// A Java program to demonstrate working on enum 
// in switch case (Filename Test. Java) 
import java.util.Scanner; 

// An Enum class 
enum Day 
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
THURSDAY, FRIDAY, SATURDAY; 

// Driver class that contains an object of "day" and 
// main(). 
public class Test 
Day day; 

// Constructor 
public Test(Day day) 
this.day = day; 

// Prints a line about Day using switch 
public void dayIsLike() 
switch (day) 
case MONDAY: 
System.out.println("Mondays are bad."); 
break; 
case FRIDAY: 
System.out.println("Fridays are better."); 
break; 
case SATURDAY: 
case SUNDAY: 
System.out.println("Weekends are best."); 
break; 
default: 
System.out.println("Midweek days are so-so."); 
break; 

// Driver method 
public static void main(String[] args) 
String str = "MONDAY"; 
Test t1 = new Test(Day.valueOf(str)); 
t1.dayIsLike(); 

Output:

Mondays are bad.

◉ Every enum constant is always implicitly public static final. Since it is static, we can access it by using enum Name. Since it is final, we can’t create child enums.
◉ We can declare main() method inside enum. Hence we can invoke enum directly from the Command Prompt.

// A Java program to demonstrate that we can have 
// main() inside enum class. 
enum Color 
RED, GREEN, BLUE; 

// Driver method 
public static void main(String[] args) 
Color c1 = Color.RED; 
System.out.println(c1); 

Output :

RED

Enum and Inheritance :


◉ All enums implicitly extend java.lang.Enum class. As a class can only extend one parent in Java, so an enum cannot extend anything else.

◉ toString() method is overridden in java.lang.Enum class,which returns enum constant name.

◉ enum can implement many interfaces.

values(), ordinal() and valueOf() methods :


◉ These methods are present inside java.lang.Enum.

◉ values() method can be used to return all values present inside enum.

◉ Order is important in enums.By using ordinal() method, each enum constant index can be found, just like array index.

◉ valueOf() method returns the enum constant of the specified string value, if exists

// Java program to demonstrate working of values(), 
// ordinal() and valueOf() 
enum Color 
RED, GREEN, BLUE; 

public class Test 
public static void main(String[] args) 
// Calling values() 
Color arr[] = Color.values(); 

// enum with loop 
for (Color col : arr) 
// Calling ordinal() to find index 
// of color. 
System.out.println(col + " at index "
+ col.ordinal()); 

// Using valueOf(). Returns an object of 
// Color with given constant. 
// Uncommenting second line causes exception 
// IllegalArgumentException 
System.out.println(Color.valueOf("RED")); 
// System.out.println(Color.valueOf("WHITE")); 

Output :

RED at index 0
GREEN at index 1
BLUE at index 2
RED

enum and constructor :


◉ enum can contain constructor and it is executed separately for each enum constant at the time of enum class loading.

◉ We can’t create enum objects explicitly and hence we can’t invoke enum constructor directly.

enum and methods :


Oracle Java Exam Prep, Oracle Java Tutorial and Material, Core Java, Oracle Java Prep
◉ enum can contain both concrete methods and abstract methods. If an enum class has an abstract method, then each instance of the enum class must implement it

// Java program to demonstrate that enums can have constructor 
// and concrete methods. 

// An enum (Note enum keyword inplace of class keyword) 
enum Color 
RED, GREEN, BLUE; 

// enum constructor called separately for each 
// constant 
private Color() 
System.out.println("Constructor called for : " + 
this.toString()); 

public void colorInfo() 
System.out.println("Universal Color"); 

public class Test 
{  
// Driver method 
public static void main(String[] args) 
Color c1 = Color.RED; 
System.out.println(c1); 
c1.colorInfo(); 

Output:

Constructor called for : RED
Constructor called for : GREEN
Constructor called for : BLUE
RED
Universal Color

Sunday, January 10, 2021

Generating random numbers in Java

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

Java provides three ways to generate random numbers using some built-in methods and classes as listed below:

◉ java.util.Random class

◉ Math.random method : Can Generate Random Numbers of double type.

◉ ThreadLocalRandom class

1) java.util.Random

◉ For using this class to generate random numbers, we have to first create an instance of this class and then invoke methods such as nextInt(), nextDouble(), nextLong() etc using that instance.

◉ We can generate random numbers of types integers, float, double, long, booleans using this class.

◉ We can pass arguments to the methods for placing an upper bound on the range of the numbers to be generated. For example, nextInt(6) will generate numbers in the range 0 to 5 both inclusive.

// A Java program to demonstrate random number generation 

// using java.util.Random; 

import java.util.Random; 

public class generateRandom{ 

public static void main(String args[]) 

// create instance of Random class 

Random rand = new Random(); 


// Generate random integers in range 0 to 999 

int rand_int1 = rand.nextInt(1000); 

int rand_int2 = rand.nextInt(1000); 


// Print random integers 

System.out.println("Random Integers: "+rand_int1); 

System.out.println("Random Integers: "+rand_int2); 


// Generate Random doubles 

double rand_dub1 = rand.nextDouble(); 

double rand_dub2 = rand.nextDouble(); 


// Print random doubles 

System.out.println("Random Doubles: "+rand_dub1); 

System.out.println("Random Doubles: "+rand_dub2); 

Output:

Random Integers: 547
Random Integers: 126
Random Doubles: 0.8369779739988428
Random Doubles: 0.5497554388209912

2) Math.random()


The class Math contains various methods for performing various numeric operations such as, calculating exponentiation, logarithms etc. One of these methods is random(), this method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. The returned values are chosen pseudorandomly. This method can only generate random numbers of type Doubles. Below program explains how to use this method:

// Java program to demonstrate working of 
// Math.random() to generate random numbers 
import java.util.*; 

public class generateRandom 
public static void main(String args[]) 
// Generating random doubles 
System.out.println("Random doubles: " + Math.random()); 
System.out.println("Random doubles: " + Math.random()); 

Output:

Random doubles: 0.13077348615666562
Random doubles: 0.09247016928442775
 

3) java.util.concurrent.ThreadLocalRandom class


This class is introduced in java 1.7 to generate random numbers of type integers, doubles, booleans etc. Below program explains how to use this class to generate random numbers:

Oracle Java Tutorial and Material, Oracle Java Exam Prep, Oracle Java Career, Core Java
// Java program to demonstrate working of ThreadLocalRandom 
// to generate random numbers. 
import java.util.concurrent.ThreadLocalRandom; 

public class generateRandom 
public static void main(String args[]) 
// Generate random integers in range 0 to 999 
int rand_int1 = ThreadLocalRandom.current().nextInt(); 
int rand_int2 = ThreadLocalRandom.current().nextInt(); 

// Print random integers 
System.out.println("Random Integers: " + rand_int1); 
System.out.println("Random Integers: " + rand_int2); 

// Generate Random doubles 
double rand_dub1 = ThreadLocalRandom.current().nextDouble(); 
double rand_dub2 = ThreadLocalRandom.current().nextDouble(); 

// Print random doubles 
System.out.println("Random Doubles: " + rand_dub1); 
System.out.println("Random Doubles: " + rand_dub2); 

// Generate random booleans 
boolean rand_bool1 = ThreadLocalRandom.current().nextBoolean(); 
boolean rand_bool2 = ThreadLocalRandom.current().nextBoolean(); 

// Print random Booleans 
System.out.println("Random Booleans: " + rand_bool1); 
System.out.println("Random Booleans: " + rand_bool2); 

Output:

Random Integers: 536953314
Random Integers: 25905330
Random Doubles: 0.7504989954390163
Random Doubles: 0.7658597196204409
Random Booleans: false
Random Booleans: true