Wednesday, February 10, 2021

Code a Java Game with (almost) Zero Coding Skills

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

Today, the gaming industry is getting better day by day with the latest tools and technology. Video games are not only popular among children, and even elders play video games with great enthusiasm. If you are not that into games before, you must look at the graphics and animations included in today’s gaming. Gaming is an industry where there is a tremendous demand of developers to turn gaming into reality with their coding and innovative skills. For developing a game, you do not have to be professional. There are many platforms that will provide you exciting features that can be easily implemented within your games. 

In the below article, we are addressing especially to the Java developers both beginners and experts who want to develop Java game projects. This article will give you a start on how to begin and what you should be learning to develop a good game. 

1. Is Java good for developing games?

There is always a discussion about whether Java is good enough to develop innovative games. The answer may vary among different developers depending on what type of game you want to develop. Java works well for some platforms and not good enough for some platforms. Java may not work well if you’re going to publish it in the Standard app store. For running a Java application, you will require the JRE (Java Runtime Environment) and may not be available on people’s systems to run the game. So developers try to include JRE within your game or JAVA application, which can be a tedious process. But if developers tend to manage this process in a simpler way, you are good to go with running Java games on any platform.

2. Why Not Java?

Below are some reasons why Java is not suitable for game development.

◉ Earlier, the developer requires “direct access” for enhancing performance and UI. Using direct access will outdate the VM languages like Java and C#.

◉ Most gaming consoles like 360, PS3 do not come with JVM, which will not allow you to reuse the code from the PC version. Compiling C++ code is much easier than running JVM to support various gaming devices.

◉ The most commonly used gaming engines as Unreal comes with C++ bindings. You can also use some Java connectors, for example, OpenGL.

◉ For Windows PC gaming, DirectX is a necessity to run games properly. But, DirectX does not have concrete Java support.

◉ If you want to run Web-based games, you can run the games using JavaScript or Flash. You can design the games in Java using various features like GWT.

Java is primarily used to create and design Android games these days because Java is the Android platform’s primary language. Also, you create web-based games using Java in conjunction with the Flash.

3. Why Java?

Though the gaming world is diverse and you can divide the games into the below-mentioned categories. 

◉ Big games like 3D- shooters and action RPG are high budget games, including AAA-level gaming projects. C++ is used to develop these games along with the game engines. Such games are designed for a mass audience. Java is merely used for developing Big games due to the JVM requirement. But, you can use Java for creating the backend.

◉ Indie games are small and amateur game projects that do not require a large team to design and develop the game. These games require innovative scripts and subjective vision instead of including high-end graphics. One of the indie games is Minecraft, which was created by a single Java developer, and the game has gained immense popularity. Thus, we can say Java works well for Indie game projects. 

◉ Mobile games- it has gained much more popularity than PC games with various gaming applications. People mostly spend more time on their phones and like to play games in their free time. But the question is Java good for developing mobile games? The answer is a direct yes. Also, we know that Java is the primary language for creating Android applications. 

So, we can say that Java is the best suitable language for creating Indie and Android gaming applications. Not only this, Java supports and manages the high-loaded online gaming server. While learning Java, you can learn concepts for developing games. Java is a universal language that can be used anywhere like server-side, back-end mobile applications, web-based applications, and great animations. Once you are set with Java, you can easily switch to any other language efficiently. 

4. How can a beginner create their game?

Creating video games is not an easy task and requires excellent coding skills. Even if you are a beginner, you do not have to worry about creating games using Java. In this advanced technology world, we have all solutions where you can follow instructions to create small games. Below, we will highlight some options for developing games in Java.

4.1 Option 1: using CodeGym, game section

This feature allows beginners to create classical games with knowledge of Java basics. The code section on the CodeGym is free to all users. 

◉ This game section allows you to create customized video games like Minesweeper, snake, etc. some of the CodeGym games are still in development, like Moon lander, Racer.

◉ Each game consists of various sub-task with instructions. The student will write the code and run it through the auto CodeGym system based on the instruction. Students can move to the next steps if everything goes right. You can code directly to the CodeGym site with the help of a select plugin.

◉ Once you complete the last step, your game is ready to publish and share among other people. 

◉ These games are elementary and require Java initial knowledge and concepts like primitive data types, loops, branches, classes, objects, string, and structure.

◉ CodeGym is available for free. If you have Java knowledge, the CodeGym provides you the opportunity to customize games.

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Guides
CodeGym

4.2 Option 2: For Intermediate Java developers

If you like Minecraft, then it is an excellent option to make modifications with Java. After modification, you will be able to change the game content that provides players more chances to interact with the Minecraft world. You can create small games within Minecraft. To make customized modifications to the code, you must know how to work with decompiled code and modify it.

◉ For modding, you require IDE and JDK along with modding tools. You can use Forge as one of the most popular Java Modding tools. 

◉ Java knowledge for making mods depends on how complex your modifications are. 

◉ You must have class, objects, data structures, Java collection, and threads knowledge.

◉ Minecraft is not free, and you have to pay for the Minecraft version. You have to create an account on Minecraft and get it validated using Java email validation feature.

4.3 Option 3: For experienced Java core developers

Writing Java games is not an easy task and requires good programming skills. But, today, various frameworks and library options help you to create games efficiently. A good game will need Graphics, animation, GUI, sound, and Artificial intelligence. 

◉ For rendering 2D and 3D vector graphics, you can use OpenGL API. Java offers functions and libraries for OpenGL. Java provides cross-platform libraries that are free and open-source. 

◉ libGDX can work for cross-platform games that offer the Box 2D engine for creating game physics, graphics classes, and special tools for audio. It comes with various modules to create AI-based characters. Creating games with libGDX can run on any platform and do not require different code for each platform.

Monday, February 8, 2021

Java Fibonacci Series Recursive Optimized using Dynamic Programming

A quick guide to write a java program print Fibonacci series and find the nth Fibonacci number using recursive optimized using dynamic programming.

1. Overview

In this article, we will learn how to print the fibonacci series and find the nth fibonacci number using recursive approach.

Generating a stream of Fibonacci numbers

In the following sections we will try to run the program for below scenarios.

Saturday, February 6, 2021

Java Heap Sizing in a Container: Quickly and Easily

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

We have seen that Java has made improvements to identify the memory based on a running environment i.e. either a physical machine or a Container (docker). The initial problem with java was that It wasn't able to figure out that it was running in a container and It used to capture the memory for whole hardware where the container was running.

Now a Java Program running in a container is able to identify the cgroup limit and assign the memory (heap) according to that, (If we do not specify the min and max heap size, which we used to define earlier). So we can run our java program in a container and utilize hardware memory properly, but can we very sure that Java program is using heap size according to cgroup definition?

We have a solution to this problem as XshowSettings:category. This is a handy HotSpot JVM flag (option for the Java launcher java) is the -XshowSettings option. This option is described in the Oracle Java launcher description page as follows:

-XshowSettings:category

Shows settings and continues. Possible category arguments for this option include the following:

all

Shows all categories of settings. This is the default value.

locale

Shows settings related to locale.

properties

Shows settings related to system properties.

vm

Shows the settings of the JVM.

[These types of flags described in the Java tech note - as https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html ]

The showSettings flag provides lots of details about the program running in that JVM, however, our interest is to find out the memory utilization so we will stick to the argument as -> -XshowSettings:vm -version

Let's verify this by running a simple container program without specifying the cgroup flag (which informs java that the program is running in a Java container)

(I set a container memory of 100MB and my JVM sets a max heap of 3.24G)

[root java-8]# docker run -m 100MB oracle-server-jre java -XshowSettings:vm -version

VM settings:

    Max. Heap Size (Estimated): 3.24G

    Ergonomics Machine Class: server

    Using VM: Java HotSpot(TM) 64-Bit Server VM

java version "1.8.0_181"

Java(TM) SE Runtime Environment (build 1.8.0_181-b13)

Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)

We can clearly see that Java Heap is capturing the heap available to the hardware however the docker size was specified to 100 mb only, Now let's tell Java that the program is running inside the container and see the results.

With java version 1.8.0_181 (including unlock experimental version and Cgroup limit with a specification of memory 1GB MB) with only jdk Docker 

[root]# docker run -m 1GB oracle-server-jre java -XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap -XshowSettings:vm -version

VM settings:

    Max. Heap Size (Estimated): 228.00M

    Ergonomics Machine Class: server

    Using VM: Java HotSpot(TM) 64-Bit Server VM

java version "1.8.0_181"

Java(TM) SE Runtime Environment (build 1.8.0_181-b13)

Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)

Oracle Java Exam Preparation, Oracle Java Tutorial and Material, Oracle Java Certification, Core Java
The JVM was able to detect the container has only 1GB and set the max heap to 228M, which is almost 1/4th of the total available size.

We can see that the Java Heap is set to 1/4th of the docker size and rest of the 3/4th memory is utilized by docker, but what if our container doesn't require 3/4 memory,  

If the container or the program configuration doesn't need that much of memory then this is not the correct utilization of memory. The ratio between Java heap and Container size is defined inside JVM code, so the question is - can we configure this ratio?? 

Yes, Java did a very good thing by providing another option to change the ratio of container memory and java heap size. Java introduced another flag as MaxRAMFraction ( the default value to this flag is 4, so heap size takes 1/4th of container size and we can change it by defining it explicitly)

we have defined RAM fraction =2, Which settles heap size on almost 50% of the total.

[root]# docker run -m 1GB oracle-server-jre java -XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap -XX:MaxRAMFraction=2 -XshowSettings:vm -version

VM settings:    

    Max. Heap Size (Estimated): 455.50M

    Ergonomics Machine Class: server

    Using VM: Java HotSpot(TM) 64-Bit Server VM

java version "1.8.0_181"

Java(TM) SE Runtime Environment (build 1.8.0_181-b13)

Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)

The heap size reaches approximately to 50% of the total container size.

Now we can change the ratio as well according to our Java program comfort level, but this leads to another thought that is is safe to run a container, if we define this ratio to 1? (however JVM won't capture whole container memory and It leaves some memory to run some other container programs like container debug shell (docker exec) and diagnostics, OS processes, etc. If the program or container needs more memory under load then it will kill the container, so I feel defining the least ratio

-XX:MaxRAMFraction=2

 seems safe(ish), if we want to customize the default JVM ratio which seems to be the safest ratio.

Friday, February 5, 2021

Java TreeMap Vs HashMap With Examples

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

A quick guide to understand the differences between the TreeMap and HashMap with examples.

1. Overview

We will learn the core differences between TreeMap and HashMap classes with example programs.

If you are new to java programming, suggest to go through the below topics.

HashMap Examples

TreeMap Examples

In java, All Map implementations are to store the key-value pairs but there are few differences based on the implementations.

HashMap is extensively used in the day to day development from the collection framework when compared to TreeMap. Both uses internally bucketing concept but when any bucket partition becomes large the it does convert into TreeNode Structure.

2. Similarities between HashMap and TreeMap

The below are the common things in both classes. Let us look into those before understanding the differences.

2.1 HashMap and TreeMap classes implement Map<K,V>, Cloneable, Serializable interfaces and extends AbstractMap<K,V> class.

2.2 Both stores the values based on the keys. Always key and value should be provided.

2.3 Always key should be unique and if we add the same key again then old value will be replaced with the new value.

2.4 These are not synchronized.

2.5 Not thread-safe because if the original Map is modified during the iteration then it cause to throw runtime exception ConcurrentModificationException.

3. HashMap Examples

In the below example, we added few values to HashMap using put() method. Next, printed the all the values of HashMap.

Further tried to print the values using iterator and deleted the key “0333” from the original hashmap.

Removal key from hashmap produces the runtime exception.

package com.oraclejavacertified.collections.hashmap;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Set;

public class HashMapExamples {

    public static void main(String[] args) {

        Map<String, String> hashMap = new HashMap<>();

        hashMap.put("0111", "one's");

        hashMap.put("0222", "two's");

        hashMap.put("0333", "three's");

        hashMap.put("0444", "four's");

        hashMap.put("0111", "one's modified");

        System.out.println("HashMap values are - " + hashMap);

        System.out.println("Iterating Hashmap and modifying the values");

        Set<String> keys = hashMap.keySet();

        Iterator<String> iterator = keys.iterator();

        while (iterator.hasNext()) {

            String key = iterator.next();

            System.out.println("key - " + key + ", value - " + hashMap.get(key));

            if (key == "0333") {

                hashMap.remove(key);

            }

        }

    }

}

Output:

HashMap values are - {0111=one's modified, 0222=two's, 0333=three's, 0444=four's}

Iterating Hashmap and modifying the values

key - 0111, value - one's modified

key - 0222, value - two's

key - 0333, value - three's

Exception in thread "main" java.util.ConcurrentModificationException

    at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1490)

    at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1513)

    at com.oraclejavacertified.collections.hashmap.HashMapExamples.main(HashMapExamples.java:29)

4. TreeMap Examples

In the below example, we added few values to TreeMap using put() method. Next, printed the all the values of TreeMap in sorted order.

Further tried to print the values using iterator and deleted the key “0333” from the original treemap.

Removal key from treemap produces the runtime exception.

package com.oraclejavacertified.collections.treemap;

import java.util.Iterator;

import java.util.Map;

import java.util.Set;

import java.util.TreeMap;

public class TreeMapExamples {

    public static void main(String[] args) {

        Map<String, String> treeMap = new TreeMap<>();

        treeMap.put("0111", "one's");

        treeMap.put("0222", "two's");

        treeMap.put("0333", "three's");

        treeMap.put("0444", "four's");

        treeMap.put("0111", "one's modified");

        System.out.println("treeMap values are - " + treeMap);

        System.out.println("Iterating treeMap and modifying the values");

        Set<String> keys = treeMap.keySet();

        Iterator<String> iterator = keys.iterator();

        while (iterator.hasNext()) {

            String key = iterator.next();

            System.out.println("key - " + key + ", value - " + treeMap.get(key));

            if (key == "0333") {

                treeMap.remove(key);

            }

        }

    }

}

Output:

Core Java, Oracle Java Tutorial and Material, Oracle Java Guides, Java Preparation, Java Career
treeMap values are - {0111=one's modified, 0222=two's, 0333=three's, 0444=four's}

Iterating treeMap and modifying the values

key - 0111, value - one's modified

key - 0222, value - two's

key - 0333, value - three's

Exception in thread "main" java.util.ConcurrentModificationException

    at java.base/java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1208)

    at java.base/java.util.TreeMap$KeyIterator.next(TreeMap.java:1262)

    at com.oraclejavacertified.collections.treemap.TreeMapExamples.main(TreeMapExamples.java:29)

5. Differences between HashMap and TreeMap

The below are the main differences between these two maps.

5.1 TreeMap implements the NavigableMap interfaces rather than Map interface.

5.2 HashMap is implemented based on the hashtable

     TreeMap is implemented based on Tree Structured based map such as Red Black Tree which is a balanced.

5.3 HashMap allows only one null key and multiple null values.

      TreeMap does not allow null key but allows null values.

5.4 HashMap does not sort the keys where as TreeMap does sort the keys.

5.5 HashMap is faster then TreeMap because hashmap does not sort so it provides easy access to insertion and retrieval with constant time O(1) with put() and get() methods.

5.6 HashMap uses the equals() method for duplicate keys comparison but for TreeMap, keys are compared and sorted based on the compareTo() method. So, key must implement the Comparator or Comparable interface else will get the runtime error.

Wednesday, February 3, 2021

Java and the New Duke Personality

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

For 24+ years, Java technology has advanced the world we interact with every day. With Oracle’s stewardship, Java technology continues to offer developers innovative functionality to build out the next generation of applications that bring utility to us, both personally and professionally.

And during the history of Java, it’s been represented by the highly recognized Duke personality. Back in the early days of Java development, Sun Microsystems’ Green Project team created its first working demo—an interactive handheld home entertainment controller called the Star7. At the heart of the animated touch-screen user interface was a cartoon character named Duke.


The jumping, cartwheeling Duke was created by one of the team’s graphic artists, Joe Palrang. Joe went on to work on popular animated movies such as Shrek, Over the Hedge, and Flushed Away.

Duke was designed to represent a “software agent” that performed tasks for the user. Duke was the interactive host that enabled a new type of user interface that went beyond the buttons, mice, and pop-up menus of the desktop computing world.

Oracle Java Tutorial and Material, Oracle Java Certification, Core Java, Java Preparation, Java Career
Duke was instantly embraced. In fact, at about the same time Java was first introduced and the first Java cup logo was commissioned, Duke became the official mascot of Java technology. In 2006, Duke was officially “open sourced” under a BSD license. Developers and designers were encouraged to play around with Duke and for the first time had access to Duke’s graphical specifications through a java.net project. Efforts around Duke are now hosted as “Project Duke” at OpenJDK.

At Oracle, we celebrate Duke, too. A living, life-size Duke was a popular feature at every JavaOne developer conference, and now at Oracle’s flagship developer event…Oracle Code One.

This year, Oracle is releasing a new Duke personality that embodies the open and innovative spirit and how Java continues to propel itself into the future.

Source: oracle.com

Monday, February 1, 2021

A Java Test Class Doesn’t Test a Class

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

At Interview

A great job interview question is to ask someone what test automation they’ve constructed and how they came to do it.

A not-great answers is “none”. In my experience, worse than that is the person who answers “I have to write a test class for every class, and a test method for every method”. By fixating on the code under test, rather than the behaviours and nature of constructing a scenario, you often do precisely the wrong sort of testing.

Test Behaviour from Different Perspectives

The objective is to set up some sort of scenario and then test the behaviour within that scenario. The same code under test may behave differently depending on what we interface it with. It’s situational.

It, therefore, does not follow that a single class should be tested from one other test class. Nor does it follow that a single test class is only ever going to focus on one part of the system.

From the test pyramid we might assume that the lowest level tests will have fixtures focussing on only a small part of the system. However, other fixture may look further afield.

Fixtures Happen to be Classes

It gets confusing because the convention happens to be to create a test class to test a class. So the natural assumption is that you keep all tests in that class. It’s a good working assumption, as often it’s true.

However, watch out for whether the test starts to perform a diverse set of different tests. The easiest way to spot that is by looking at the properties of the test class, set up each time. Does each test case use the majority of the available resources?

How To Decide a Test Fixture

We may instinctively start by creating the usual mechanics of a test class. Something like this:

class MyTest {

   // some test input or expected output

   private static final SomeObject COMPLEX_DATA = new ...;

   private Thing whatWeAreTesting = new ...;

   // ... other resources

   @BeforeEach

   void beforeEach() {

       // some additional setup

   }

   @AfterEach

   void afterEach() {

       // some tidy up

   }

   @Test

   void testOne() { ... }

}

I tend to start a test with some of the above in place, usually adding the beforeEach and afterEach on a case by case basis if needed.

But what if we weren’t allowed to use any of the object level values? What if we couldn’t create static resources? What would go in each of our test methods?

There would be some repeated setup stuff, there would be some stuff that may be repeated, but is not common set up, so much as the test examples which may be used in different contexts from one test to the next, and there would be some stuff that’s unique or used rarely.

If you were to imagine the test refactored to independent methods you may encounter a few situations:

Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation, Oracle Java Learning
◉ Some global setup is being repeated across multiple tests – implying these tests should live in a single fixture with a beforeAll/afterAll pattern

◉ Some set up is repeated across all tests – suggesting the object-level set up, perhaps with beforeEach and afterEach depending on how easy it is to set things up

◉ Some things are used for a subset of tests – suggesting that there’s are multiple fixtures required

Tests Can Share Implementation

There can be base classes for tests, and inheritance of test implementation is not, in my opinion, an anti-pattern.

Similarly, tests may share a test data factory for producing complex objects for both test input and expected output.