Java Static Initializer Block

It is Sunday at 07:36 AM in the Twin Cities of St. Paul and Minneapolis. I try to get in at least a couple of 2-hour blocks each weekend day. I can see from my home office that the day is still dark although sunrise occurred at 07:14 AM.

Lately I have not posting much due to the fact that I am working on software that I would like to have finished by the end of this week. I like the project because the requirements were quite vague. In addition, the hardware when I received it had a couple issues. After contacting the vendor I had to wait a week before I could take the unit to be repaired. It just took a few hours for me to drive to the OEM’s office, have it looked at and repaired and get back home. Very knowledgeable technical support!

The architecture that I chose is similar to what you would do in the cloud using microservices. When all is done will have a set of four or perhaps five services that will interact getting the task done. If I have time by next week I would like to get a ML (machine learning) model able to perform one of the tasks. Given that I need several hundred images, chances are that that will be a follow on feature.

What I have enjoyed so far in the project is that I have been able to decide on which programming languages and technologies to use for the different services. By reading and experimenting on a consistent base, I am able to increase the set of tools I can use to solve problems.

After breakfast while taking a shower I decided to skip watching a YouTube video on Azure. I will continue that task tomorrow. Today I felt like writing some code so I went to the HackerRank web site. It seems that the system will automatically pick up the difficulty of the challenges based on how many you solve. Lately I have been working on the challenges in the “Cracking the Coding Interview” book and I just like them. Need to get back to it as soon as I complete the task at work.

I will also continue learning and experimenting with Azure. For what I have learned so far it seems to be easier to use that the interfaces from other providers. Will see how it performs for ML which is my main interest at this time.

Let’s now dive into the main subject for this post. The idea is to solve it using static initialization variables and block. I tend to use static variables when needed. In general some methods need to perform specific tasks once. For those I tend to use the following code which works on most (if not all programming languages). I will touch on this later on.

1
2
2

-1
2
java.lang.Exception: Breadth and height must be positive

1
-2
java.lang.Exception: Breadth and height must be positive

As we can see from the screen capture, I ran the program three times. On the first pass I entered two positive numbers which should work. On the second pass the first number is negative so the code should display a message. In the last pass the second number is negative do the program should return the same message. All seems to be working as expected.

Let’s take a look at the test scaffolding provided by HackerRank:

	/*
	 * Test scaffolding.
	 */
	public static void main(String[] args) {

		// **** ****
		if (flag) {
			int area = B * H;
			System.out.print(area);
		}	
	}

The main() function uses variables flag, B and H. They have to be defined and set outside of this function. The logic to set the flag must be dependent on the values we enter for B and H.

	/*
	 *  static blocks are executed before constructors
	 *  
	 *  in most situations static variables should be avoided
	 *  therefore static initialization blocks are generally not a great idea
	 */
	
	// **** open scanner ****
	static Scanner sc 	= new Scanner(System.in);
	
	// **** initial values ****
	static int B		= sc.nextInt();
	static int H		= sc.nextInt();
	static boolean flag	= false;

	/*
	 * static initializer
	 */
	static {
		
//		// ???? ????
//		System.out.println("static block <<< B: " + B + " H: " + H); // **** update flag or display message **** if ((B > 0) && (H > 0))
			flag = true;
		else
			System.out.println("java.lang.Exception: Breadth and height must be positive");
		
//		// ???? ????
//		System.out.println("static block <<< flag: " + flag);
		
		// **** close scanner ****
		sc.close();
	}

In this code we open and close a scanner use to read the B and H values. The three variables are declared as static and initialized. As expected the scanner is used to read the values of B and H. The flag is by default set to false;

We now use a static block to alter the value of flag if needed. If one or both specified values are negative, the code displays the required message and the flag remains set to false so we do not compute the area. If the values are both positive, we do not display the message but we do set the flag to true. This allows the main() function to display the area.

That is all for this challenge.

After my first 2-hour block I went upstairs and asked my wife if she was ready for some hot tea. We get our tea from Trader Joe’s. We vary based on what is available and in season. We just finished a couple boxes of mango tea. We stopped by last week and they did not have it. It is a summer flavor. We got a couple boxes of pomegranate tea. That should last for a month or two.

When my wife and I seat to chat I always have to cut it based on what else I need to do. Today is a week day so we chatted for almost an hour. She is going to do some wash and ironing while I get in a second 2-hour block in my office.

We chatted about the two YouTube videos (we did not finish the second) that we watched yesterday while preparing lunch. I grilled potatoes with onions and garlic in a cast iron pan and warmed on a separate pan roasted beef chunks also with onions and red wine, while my wife and I pecked on Capocollo ham and cheese chunks on sesame seed crackers while drinking a bottle of red wine. I do not recall the name or vineyard, but it was quite good and paired well with our appetizers and meal. We do enjoy wines! The video we watched completely was “Discover the Wines of Southern Italy” hosted by Michael Fagan. The host seems to know a lot about wines and is quite good at describing them.

What called my attention was the pride on the people that produced the different wines. In general they seemed to enjoy and most important showed pride on what they did. Most of the producers came from several generations of people in the same line of work. This is why their products, yet different, are among the best in the world.

I have been working developing software for a few decades. I also take pride on what I do. Developing software is an art and a science as it is producing wine. My family came from Italy as recent as my parents who were born in Genoa. I am first generation developing software and our two sons are both working in the same industry, yet we all work for different companies.

Our conversation during the past break shifted from wine to software. It is interesting how most companies do not take pride on what they produce. I seem that the goals are to make money with products that are good enough to meet the base minimums and typically are full of bugs. They all seem to kind of work is customers do exactly what they were tested against which in most cases were generated to lightly match some loosely set of requirements. Quality takes time and requires craftsmen that take pride on what they do. Boeing is an example. Most airlines, utilities, banks, retailers seem to follow the same rules.

OK, moving on, let’s look at the edited test scaffolding.

	/*
	 * Test scaffolding.
	 */
	public static void main(String[] args) {

		// **** ****
		if (flag) {
			int area = B * H;
			System.out.print(area);
		}
	
//		// ???? ????
//		System.exit(0);
		
		
		// **** instantiate an object ****
		MyClass myClass = new MyClass();
		
		// **** ****
		myClass.doSomething(1);
		
		// **** :::: ****
		
		// **** ****
		myClass.doSomething(2);
		
		// **** instantiate a different object ****
		MyClass secondInstance = new MyClass();
		
		// **** ****
		secondInstance.doSomething(3);
	}

The first section is what was needed for the HackerRank challenge. I spent time thinking and experimenting to see why I would use static initializing blocks on my code or not.

In this example UI instantiated a class and made two calls to the doSomething() method. I then created a separate instance and called it once.

2
3
6
doSomething <<< do this ONCE! arg: 1
doSomething <<< ALWAYS do this... arg: 1
doSomething <<< ALWAYS do this... arg: 2
doSomething <<< ALWAYS do this... arg: 3

The output seems to call some code in a method once. It seems to initialize a class. It seems to accomplish the same as the first code but in a slightly different way.

/*
 * 
 */
class MyClass {

	// **** ****
	static boolean firstPass	= true;
	
	// **** constructor ****
	public MyClass() {
	}
	
	// **** ****
	public int doSomething(int arg) {
		
//		// **** ****
//		static boolean firstPass = true;
		
		// **** initialization ****
		int retVal = 0;

		// **** ****
		if (firstPass) {
			
			// ???? ????
			System.out.println("\ndoSomething <<< do this ONCE! arg: " + arg);
			
			// **** ****
			firstPass = false;
		}
		
		// **** always do this ****
		System.out.println("doSomething <<< ALWAYS do this... arg: " + arg);
		
		// **** inform the caller what went on ****
		return retVal;
	}
}

We start by defining a static variable that will be used to force the execution of some code inside the doSomething() method once. It works the same but on a single variable. The static block can be used to alter the initial values.

Also note that the static variables are used for the class.  They are not needed or accepted by the compiler inside a method. The idea is that a method should do one thing and only one. If you need some processing done only once, then declare a different method which we would call only once and then a different one that we would call it repeatedly.

The entire code for this project can be found in my GitHub repository.

If you have comments or questions regarding this, or any other post in this blog, or if you would like for me to serve of assistance with any phase in the SDLC (Software Development Life Cycle) of a project associated with a product or service, please do not hesitate and leave me a note below. If you prefer, send me a message using the following address:  john.canessa@gmail.com. All messages will remain private.

Keep on reading and experimenting. It is the best way to learn, refresh your knowledge and increase your development toolset!

John

Follow me on Twitter:  @john_canessa

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.