Friday, August 28, 2020

Difference between JVM, JIR, JRE, and JDK in Java

JRE, JVM, and JDK are three terms you often heard in conjunction with Java programming language, and most people either confuse them or think they all are the same. In this Java article, you will learn what is Java Run-time (JRE), what is Java Virtual Machine (JVM) and what is Java Development Kit (JDK) along with Just in Time compiler or JIT. Once you know what JRE, JVM or JDK means you can differentiate them easily by yourself.

JRE, JVM, JIR, and JDK in Java Programming language


Now, let’s understand all JRE (Java Runtime Environment), JVM (Java Virtual Machine), and JDK (Java Development Kit) in detail to learn the differences between them.

1. Java Runtime Environment (JRE)


Java is everywhere in the browser, in mobile, in TV, or in set-top boxes, and if you are into Java programming language than you know that Java code which is bundled in JAR (Java archive) file requires Java virtual machine JVM to execute it.

Now JVM is an executable or program like any other program and you can install that into your machine. You have seen browsers often suggesting download JRE run a Java Applet downloaded from the Internet.

Various versions of JRE is available in java.oracle.com and most of the user who just wants to execute Java program inside a browser or standalone downloads JRE. All browsers including Internet Explorer, Firefox, and Chrome can work with JRE.

2. Java Virtual Machine (JVM)


When you download JRE and install on your machine you got all the code required to create JVM. Java Virtual Machine is get created when you run a java program using java commands like java HelloWorld.

JVM is responsible for converting byte code into machine-specific code and that’s why you have different JVM for Windows, Linux, or Solaris but one JAR can run on all this operating system.

Java Virtual machine is at the heart of Java programming language and provides several features to Java programmers including Memory Management and Garbage Collection, Security, and other system-level services.

Java Virtual Machine can be customized like we can specify starting memory or maximum memory of heap size located inside JVM at the time of JVM creation.

If we supplied an invalid argument to java command it may refuse to create Java Virtual Machine by saying “failed to create Java virtual machine: invalid argument“.

It’s one of the advanced courses for Java programmers to learn more about JVM, Performance, and Memory management including troubleshooting memory leaks in Java.

Oracle Java, JVM, JIR, JRE, JDK, Oracle Java Exam Prep, Oracle Java Learning

3. Java Development Kit (JDK)


JDK is also loosely referred to as JRE but its lot more than JRE and it provides all the tools and executable require to compile debug and execute Java Program. Just like JRE, JDK is also platform-specific and you need to use separate installers for installing JDK on Linux and Windows. 

The current version of JDK is 1.7 which is also referred to as Java7 and it contains javac (java compiler) based on programming rules of Java7 and Java which can execute java7 code with new features like String in Switch, fork-join framework or Automatic Resource Management. 

When you install JDK, the installation folder is often referred to as JAVA_HOME. All binaries are located inside JAVA_HOME/bin which includes javac, java, and other binaries and they must be in your system PATH in order to compile and execute Java programs.

4. Difference between JRE, JDK, and JVM


In short, there are few differences between JRE, JDK, and JVM:

1)  JRE and JDK come as installers while JVM is bundled with them.

2)  JRE only contain environment to execute java program but doesn’t contain other tools for compiling java program.

3)  JVM comes along with both JDK and JRE and created when you execute the Java program by giving the “java” command.

4. Just in Time Compiler (JIT)


Initially, Java has been accused of poor performance because it’s both compiles and interprets instruction. Since compilation or Java file to class file is independent of the execution of Java program do not confuse. 

Here compilation word is used for byte code to machine instruction translation. JIT is an advanced part of Java Virtual machine which optimizes byte code to machine instruction conversion part by compiling similar byte codes at the same time and thus reducing overall execution time. 

JIT is part of Java Virtual Machine and also performs several other optimizations such as in-lining function.

Oracle Java, JVM, JIR, JRE, JDK, Oracle Java Exam Prep, Oracle Java Learning

That’s all on JRE, JDK and Java Virtual machine and difference between them. Though they look similar they are different and having a clear idea of JVM, JIT or JDK helps in java programming.

Source: javacodegeeks.com

Wednesday, August 26, 2020

Java Creates New Big Data Opportunities

If you think that we live in the age of digital information, you are totally right. But do you know just how much data is generated globally?

It is impossible to determine the exact figure, but rough estimations say that people, machines, and organizations create more than 2.5 quintillion bytes of data every day. It’s a mind-blowing number and it proves that modern businesses need super-powerful programs to collect and analyze big data.

Java is one of the best tools in this field as it creates a whole bunch of new big data opportunities. If you are interested in learning how it works, keep reading to see the impact of Java in big data.

1. How Big Is Big Data?


Before we focus on Java, we want to explain the sheer magnitude of big data and prove that it’s really a major business concept. According to the report, Amazon attracts more than 4.3 thousand unique visitors every minute. If you think that’s a lot, wait until you see the following stats:

◉ Google users run over 40 thousand searches every second.
◉ Twitter users publish 500 million tweets every day.
◉ WhatsApp users exchange up to 65 billion messages daily.
◉ Businesses harnessing the potential of big data see a profit increase of up to 10%.

Oracle Java Tutorial and Materials, Oracle Java Exam Prep, Oracle Java Guides, Oracle Java Learning

On the other hand, studies also reveal that 95% of businesses struggle with unstructured data and cannot exploit the potential of their information libraries to the fullest extent.

This is where IT professionals step in to help businesses thrive. LinkedIn named data science the fastest-growing job in 2017, while big data is projected to generate 11.5 million new jobs by 2026. At the same time, Glassdoor claims that the average big data engineer makes more than $100 thousand annually.

We guess these numbers are enough to get you thinking about a big data career, so let’s see how Java can help you with that.

2. Five Reasons Why Java Is Perfect for Big Data Projects


You don’t have to be a Java developer to understand the potential of this programming language, but too many IT professionals still don’t know why it plays such a major role in big data. We shortlisted five practical reasons to use Java in big data analytics:

1. Availability of Java-focused big data tools

The first reason on our list is simple – big data tools compatible with Java are available and easy to access. These are open-source platforms such as Hadoop or Mahout, which gives you a fair share of flexibility and the right to use Java tools free of charge. The bottom line is that you don’t have to learn any other programming language when Java-focused tools are free to use.

2. Type safety is Java’s advantage

Type safety is a huge issue among data scientists because it’s critical to figure out and categorize data types properly. This is particularly important in big data projects with massive information libraries.

Jake Gardner, one of the best essay writers at the assignment proofreading services, explains that it gives Java a comparative advantage: “Java is type-safe, so developers don’t have to waste time on redundant tests.”

3. Scalability of the programming language

A lot of big data projects are continuous and require ongoing adjustments and maintenance. As such, they need a reliable tool with enough scalability potential. Java fits in perfectly because its broad toolkit, interoperability, and developer community allow big data projects to grow and scale as needed.

4. Built-in features and libraries

As one of the leaders in the programming universe, Java is also the pioneer of big data management. It comes with a fairs share of built-in features and libraries designed with big data purposes. In other words, you rarely ever need to start from scratch and build everything on your own.

5. Lots of learning resources

Of course, big data projects force Java developers to learn continuously and improve their knowledge year after year. The best thing about Java is that you can find a lot of learning resources online and keep pace with the latest findings and trends in this field. Some of our favorite Java-oriented resources include Code Combat, Codegym, Java In-Depth, and The Ultimate Hands-On Hadoop.

3. Best Java Tools for Big Data Projects


Java is obviously the way to go when it comes to big data projects, but it’s not so easy to choose the best tools for this purpose. After all, there are hundreds of Java platforms you could check out here, so it’s much easier to shortlist options and focus on top-performing tools only. We selected five proven Java tools for big data projects:

◉ Hadoop

Hadoop is probably the most complex of all Java-related big data tools you can play with, but it’s totally worth the effort because it offers a variety of business applications. It contains numerous libraries and platforms specialized for data management and large information volumes. The problem for many developers is the fact that Hadoop’s MapReduce requires a lot of time to figure out and perfect.

◉ Spark

If you are looking for a reliable Hadoop alternative, then Spark may as well be your best choice. The tool is very efficient as it offers developers more than enough functions and agility, while it also doesn’t require as much learning time. As such, Spark is typically the most desirable big data platform for massive SQL and machine learning projects.

◉ Mahout

Big data goes hand in hand with machine learning, which is also why Mahout plays such a major role in big data projects. Mahout is the library of machine learning tools and learning resources that focused on Java in particular. The library is based mainly on Hadoop, so the two platforms complement each other.

◉ Storm

Developers looking for a tool specialized in real-time data processing and analysis should keep an eye on Storm. Despite being much more focused than Spark and similar tools, Storm is unmatched in terms of scalability and interoperability. This definitely makes Storm one of your must-learn Java tools for big data projects.

◉ Deeplearning4j

We saved developers’ favorite tool for last. Deeplearning4j is all-encompassing and intuitive at the same time, which makes it fairly easy to learn. Besides that, Deeplearning4j is known for its scalability and comprehensive micro-service support. You can also integrate the platform with the majority of popular big data tools.

4. The Bottom Line


Java is one of the most popular programming languages thanks to its near-unlimited applications, so it’s not a surprise to see that it earned its spot in the big data world as well. Java creates some serious big data opportunities and makes an excellent career choice for young developers globally.

In this post, we introduced you to the key big data facts and showed you a few practical reasons why to use Java for big data purposes. Java has a huge potential in data analytics, so don’t hesitate to experiment with it and try your knowledge in big data projects.

Monday, August 24, 2020

Testing with Hoverfly and Java Part 1: Get started with Simulation Mode

These days a major problem exists when it comes to testing code that has to do with various cloud services where test tools are not provided.

For example although you might have the tools for local Pub/Sub testing, including Docker images you might not have anything that can Mock BigQuery.

This causes an issue when it comes to the CI jobs, as testing is part of the requirements, however there might be blockers on testing with the actual service. The case is, you do need to cover all the pessimistic scenarios you need to be covered (for example timeouts).

And this is where Hoverfly can help.

Hoverfly is a lightweight, open source API simulation tool. Using Hoverfly, you can create realistic simulations of the APIs your application depends on

Oracle Java Tutorial and Materials, Oracle Java Learning, Oracle Java Exam Prep


<dependencies>
        <dependency>
            <groupId>io.specto</groupId>
            <artifactId>hoverfly-java</artifactId>
            <version>0.12.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

Instead of using the Hoverfly docker image we shall use the Java Library for some extra flexibility.

We got two options on configuring the Hoverfly simulation mode. One is through the Java dsl and the other one is through json.

Let’s cover both.

The example below uses the Java DSL. We spin up hoverfly on 8085 and load this configuration.

class SimulationJavaDSLTests {

    private Hoverfly hoverfly;

    @BeforeEach
    void setUp() {
        var simulation = SimulationSource.dsl(service("http://localhost:8085")
                .get("/user")
                .willReturn(success("{\"username\":\"test-user\"}", "application/json")));

        var localConfig = HoverflyConfig.localConfigs().disableTlsVerification().asWebServer().proxyPort(8085);
        hoverfly = new Hoverfly(localConfig, SIMULATE);
        hoverfly.start();
        hoverfly.simulate(simulation);
    }

    @AfterEach
    void tearDown() {
        hoverfly.close();
    }

    @Test
    void testHttpGet() {
        var client = HttpClient.newHttpClient();
        var request = HttpRequest.newBuilder()
                .uri(URI.create("http://localhost:8085/user"))
                .build();
        var res = client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                .thenApply(HttpResponse::body)
                .join();
        Assertions.assertEquals("{\"username\":\"test-user\"}",res);
    }
}

Now let’s do the same with Json. Instead of manually trying things with json we can make the code do the work for us.

var simulation = SimulationSource.dsl(service("http://localhost:8085")
            .get("/user")
            .willReturn(success("{\"username\":\"test-user\"}", "application/json")));

var simulationStr = simulation.getSimulation()
System.out.println(simulationStr);

We can get the JSON generated by the Java DSL. The result would be like this.

{
  "data": {
    "pairs": [
      {
        "request": {
          "path": [
            {
              "matcher": "exact",
              "value": "/user"
            }
          ],
          "method": [
            {
              "matcher": "exact",
              "value": "GET"
            }
          ],
          "destination": [
            {
              "matcher": "exact",
              "value": "localhost:8085"
            }
          ],
          "scheme": [
            {
              "matcher": "exact",
              "value": "http"
            }
          ],
          "query": {},
          "body": [
            {
              "matcher": "exact",
              "value": ""
            }
          ],
          "headers": {},
          "requiresState": {}
        },
        "response": {
          "status": 200,
          "body": "{\"username\":\"test-user\"}",
          "encodedBody": false,
          "templated": true,
          "headers": {
            "Content-Type": [
              "application/json"
            ]
          }
        }
      }
    ],
    "globalActions": {
      "delays": []
    }
  },
  "meta": {
    "schemaVersion": "v5"
  }
}

Let’s place this one on the resources folder of tests under the name simulation.json

Oracle Java Tutorial and Materials, Oracle Java Learning, Oracle Java Exam Prep

And with some code changes we get exactly the same result.

public class SimulationJsonTests {
    private Hoverfly hoverfly;
    @BeforeEach
    void setUp() {
        var simulationUrl = SimulationJsonTests.class.getClassLoader().getResource("simulation.json");
        var simulation = SimulationSource.url(simulationUrl);
        var localConfig = HoverflyConfig.localConfigs().disableTlsVerification().asWebServer().proxyPort(8085);
        hoverfly = new Hoverfly(localConfig, SIMULATE);
        hoverfly.start();
        hoverfly.simulate(simulation);
    }
    @AfterEach
    void tearDown() {
        hoverfly.close();
    }
    @Test
    void testHttpGet() {
        var client = HttpClient.newHttpClient();
        var request = HttpRequest.newBuilder()
                .uri(URI.create("http://localhost:8085/user"))
                .build();
        var res = client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                .thenApply(HttpResponse::body)
                .join();
        Assertions.assertEquals("{\"username\":\"test-user\"}",res);
    }
}

Also sometimes there is the need of combining simulations regardless they json or Java ones. This can also be facilitated by loading more that one simulations.

@Test
    void testMixedConfiguration() {
        var simulationUrl = SimulationJsonTests.class.getClassLoader().getResource("simulation.json");
        var jsonSimulation = SimulationSource.url(simulationUrl);
        var javaSimulation = SimulationSource.dsl(service("http://localhost:8085")
                .get("/admin")
                .willReturn(success("{\"username\":\"test-admin\"}", "application/json")));
        hoverfly.simulate(jsonSimulation, javaSimulation);
        var client = HttpClient.newHttpClient();
        var jsonConfigBasedRequest = HttpRequest.newBuilder()
                .uri(URI.create("http://localhost:8085/user"))
                .build();
        var userResponse = client.sendAsync(jsonConfigBasedRequest, HttpResponse.BodyHandlers.ofString())
                .thenApply(HttpResponse::body)
                .join();
        Assertions.assertEquals("{\"username\":\"test-user\"}",userResponse);
        var javaConfigBasedRequest = HttpRequest.newBuilder()
                .uri(URI.create("http://localhost:8085/admin"))
                .build();
        var adminResponse = client.sendAsync(javaConfigBasedRequest, HttpResponse.BodyHandlers.ofString())
                .thenApply(HttpResponse::body)
                .join();
        Assertions.assertEquals("{\"username\":\"test-admin\"}",adminResponse);
    }

That’s it, we are pretty setup to continues exploring Hoverfly and it’s capabilities.

Friday, August 21, 2020

Java Exercises for Beginners

Many people who tried learning to program never become programmers. Why? Among all the reasons, one can single out the most important: these people didn’t have enough practice. So if searching for Java programming exercises is a clever decision. Plus, practicing programming itself is a very exciting experience (much more exciting than reading theory!) and if you do it the right way, it will quickly lead you to your goal of becoming a programmer.

Oracle Java Certification, Oracle Java Exam Prep, Oracle Java Learning, Oracle Java Tutorial and Materials

Why practice?


◉ “Learning to swim without diving into water” 
◉ “How to play violin. No violin required!” 
◉ “Java in six months without writing any code”. 

What do these imaginary bestsellers have in common? Well, first of all they don’t exist. They could exist only as science fiction books, because they don’t work in reality. Swimming, playing a musical instrument and programming are all hands-on activities! Even if you learn the physics of the contact of rigid bodies with water, but at the same time avoid the pool, you will not learn to swim for sure. No matter how much you learn music theory, you won’t play the violin until you put years of practice into it. It’s the same with programming! Only you can learn it much faster than a violin.

By the way: theory is also important. If you devote 80% of your time to coding and 20% to learning theory, you will succeed!

How to organize your practicing 


You can do it in different ways. The main thing is that these activities are suitable for you, that they are not too difficult and not too easy.

1. Make a rough plan of your programming learning. You may use the table of contents for a Java book or the schedule of online courses as an example.

2. Make a learning schedule. If you’re serious in your desire to become a software developer, it is a good idea to practice every day, or at least every other day. For how many hours? It depends on your free time. 

3. Actually learning. Dedicate 20% of learning time to theory reading and 80% to code. This is a proven formula and it works.

4. Do not be lazy to make a short summary of your knowledge regularly. You may write a summary on paper or use your favorite application or blogging platform for it. 

5. Read your own code and someone else’s code carefully.

6. Ask questions. If you don’t have programmers friends, check out specialized forums,  there are many of them.

Where to find Java beginner’s exercises and how to solve them?


Okay, you may say. Where can I find Java exercises for beginners? And how do you make sure your code does what it should? In fact, when we created the CodeGym course, we started from exactly these needs of novice programmers.

That’s what CodeGym is

First, it is a universal learning platform for anyone learning Core Java. Except for the course here you can find articles on Java, a forum where you can ask questions about any programming topic, exercises to recreate classic video games, and much more. CodeGym course is dedicated to Core Java, covers all its topics and a little more.

Practice in CodeGym course: how it works?

Oracle Java Certification, Oracle Java Exam Prep, Oracle Java Learning, Oracle Java Tutorial and Materials

The course consists of lectures and a huge number of tasks. Most CodeGym students call the exercises system the main feature of the course. 

◉ Firstly, there are more than 1200 coding tasks here. Some of them are very simple, others will make you sweat, think, ask questions, google…

◉ The condition of the problem is divided into subclauses, which greatly helps beginners not to get confused in the condition.

◉ An automatic solution validation is built into the course. When you have solved the problem, you send it for verification to a special CodeGym server. If the decision is correct, you get points — dark matter. Points get you access to the following lectures.

◉ If there is a mistake in the solution, a smart validator will tell you where it is and give you some tips on how to fix it.

◉ If you don’t understand how to solve the problem anyway, click on the help button, and you will find yourself in a special section of CodeGym Help — the other students and CodeGym buddies definitely help to solve the problem.

◉ You always can postpone the difficult task and come back to it later.

◉ By the way, you can solve problems both directly on the CodeGym website and via the IntelliJ IDEA development environment. It is a professional tool that almost all Java developers use.

CodeGym walkthrough achievement — Java Developer Skill! 

Progressing through CodGym is like walking through a video game.

The course is divided into 4 parts. Each part has 10 levels. Your alter ego is the robot named Amigo — a novice programmer that you are pumping as an RPG protagonist. 

How it works: 

1. You open a lecture, read it.
2. If necessary, read additional materials and proceed to the coding tasks.
3. You get points called dark matter for solving problems. You can spend them on opening new lectures.
4. So gradually, lecture by lecture, task by task, level by level, you are pumping your skill as a Java programmer up.
5. Once you complete all 40 levels, you will have a solid Core Java knowledge backed up by approximately 500 hours of hands-on practice.

What kind of Java exercises should you solve? 


Java basics 

The abc of language. Java basics means language constructs and the main general principles of programming. The first is language specific, the second is common to most programming languages.

Topics: 

◉ First Java programs aka “Hello, World”. Keyboard output
◉ Variables, methods, and classes
◉ Primitive DataTypes: int, double, char, boolean 
◉ Work with String  
◉ Basics of keyboard input in Java 
◉ Conditions (if-else)   
◉ Loops (for and while) 
◉ Introduction to Classes and Objects
◉ Arrays  

Where to find the tasks: CodeGym, Java Syntax Quest, level 0 to 7.  

Object-Oriented Programming (OOP)

Well, maybe OOP fundamentals is not the most difficult topic, but extremely important. It contains a lot of subtleties on which interviewers like to entrap future Java Juniors. The CodeGym course contains lectures to help you understand the philosophy of OOP and practical programming tasks for beginners that will help you understand the object-oriented principles through the practice.

Topics: 

◉ Classes and objects in general 
◉ Condition and behavior of the object 
◉ Inheritance 
◉ Encapsulation 
◉ Polymorphism 
◉ Overloading and overriding 
◉ Abstraction and abstract classes 
◉ Virtual Methods 
◉ Interfaces 
◉ Interface implementations 
◉ InstanceOf 
◉ Access Modifiers
◉ The order of Constructor calls

Java Collections and Data Structures

If you understand the data structures and their fundamental differences, you can correctly apply them for different tasks. And this is a kind of superpower of the developer. Java Collection Framework is a hierarchy of interfaces and their implementations that is part of the JDK and allows the developer to use a large number of data structures out of the box. Java collections exercises are represented on CodeGym widely for beginners and intermediate students.  

Topics: 

◉ Arrays 
◉ ArrayList, LinkedList
◉ HashSet, HashMap
◉ Iterable 
◉ Collection Interface
◉ List Interface and implementations  
◉ Map Hierarchy
◉ Set Interface and implementations 
◉ Queue
◉ Trees, Red-Black trees 
◉ Iterators 

Exceptions

Exception handling is a special mechanism that is responsible for working with abnormal situations in Java. This mechanism greatly simplifies the process of bug catching in Java programs. To use it effectively, you need to figure out how exception handling is arranged in Java. There are a bunch of such tasks on CodeGym, and you can meet them even in the very first Java Syntax quest.  

Topics:

◉ Stack Trace 
◉ Exceptions types 
◉ Try Catch Finally construction 
◉ Runtime Exceptions 
◉ IOExceptions 
◉ Multi-Catch 

Input/output streams

Admittedly, Java I/O streams are complex. However Java students start using Input/Output streams way before having any idea of them. Even the very first Java programs contain this System.out.println thing. According to I/O streams complexity at first it is almost impossible to understand their work, moreover, it is not necessary. It is better to do a little bit later, when you already know the basics and solve some coding tasks. 

Topics: 

◉ Introduction to Input/Output Streams
◉ FileInputStream and FileOutputStream
◉ InputStream and OutputStream
◉ BufferedInputStream
◉ Create your own wrapper for System.in 
◉ Adapter
◉ Reader and Writer
◉ FileReader and FileWriter 
◉ BufferedReader and InputStreamReader
◉ Your own wrapper for System.out

Generics 

Generalization is the very essence of automation, that is, in a sense, and programming. So the topic of generics or generics in Java shouldn’t be overlooked either. CodeGym has Generic programming tasks.

Topics: 

◉ What are Generics 
◉ Generics: super, extends, list
◉ Type Erasure 
◉ Generics: Class
◉ Generics: ? wildcard

Concurrency/Multithreading

Multithreading in Java is a legendary topic. On the one hand, it is multithreading that is admittedly the most difficult topic in whole Core Java. On the other hand, experts recognize that Concurrency is one of the very strong and well-organized features of Java. So you have to puzzle it over. The main thing is to solve a sufficient number of problems. Well, one cannot do without repeated reading of the theory as well.

Topics: 

◉ What is thread 
◉ Creating and starting new threads
◉ Join 
◉ Creating and stopping threads: start, interrupt, sleep, yield
◉ Marker interface and deep copies 
◉ Synchronized, volatile
◉ Deadlock, Wait. notify, notifyAll

Source: javacodegeeks.com

Monday, August 17, 2020

How to do test refactoring towards fluent assertion pattern?

What are Clean Tests?


The Clean Code rules apply equally to the production code and the test code. So do code cleanup every time, including when you write tests. You will often notice opportunities for refactoring right after adding a new test or even before writing it. This will be the case when a new test requires parts that are already included in other tests – such as assertions or system configuration.

Such adjustments should take into account the basic principles of Clean Code. They mainly concern maintaining readability and maintaining the ease of introducing further changes. We should also make sure that the code is quick to read and understand.

Refactoring example


Below is a set of several integration tests. They check the price list for visiting a fitness club (gym, sauna, swimming pool). The logic also includes the calculation of loyalty points.

Although the example of this test is quite short, it already contains some code duplications. Code repeats can be found at the beginning and end of each test case.

@Test
public void twoHours_isOnly_payEntryFee() {
  Facility beFitGym = new Facility("Be Fit Gym", Facility.GYM);
  Visit visit = new Visit(beFitGym, 2);
  Client client = new Client("Mike");

  // when
  client.addVisit(visit);
  String payment = client.getReceipt();

  // Then
  assertThat(payment)
    .valueByXPath("/table/tr[1]/td[1]")
    .isEqualTo("Be Fit Gym");
       
  assertThat(payment)
    .valueByXPath("/table/tr[1]/td[2]")
    .isEqualTo("4.0");
       
  assertThat(payment)
    .valueByXPath("/table/tr[1]/td[3]")
    .isEqualTo("100");
}

@Test
public void twoHours_PayForEach() {
  // Given
  Facility beFitGym = new Facility("Jacuzzi", Facility.STEAM_BATH);
  Visit visit = new Visit(beFitGym, 2);
  Client client = new Client("Mike");

  // When
  client.addVisit(visit);
  String payment = client.getReceipt();

  // Then
  assertThat(payment)
   .valueByXPath("/table/tr[1]/td[1]")
   .isEqualTo("Be Fit Jacuzzi");
       
  assertThat(payment)
    .valueByXPath("/table/tr[1]/td[2]")
    .isEqualTo("10.0");

  assertThat(payment)
    .valueByXPath("/table/tr[1]/td[3]")
    .isEqualTo("300");
}

Refactoring in small steps


Formatowanie

Before I do my first transformation, note the value of code formatting. The above code has already been formatted. Before that, it looked like the code below. You probably see the difference when the code is clearer?

@Test
public void twoHours_PayForEach() {
  ...
  assertThat(payment).valueByXPath("/table/tr[1]/td[1]").isEqualTo("Gym");
  assertThat(payment).valueByXPath("/table/tr[1]/td[2]").isEqualTo("10.0");
  assertThat(payment).valueByXPath("/table/tr[1]/td[3]").isEqualTo("300");
}

Make assertions dependent on local variables

In well-formatted code, code repeats are more visible. This is how I prepare the code to extract methods that contain repetitions of logic. Before I perform the method extraction, I will make the repeating code dependent on local variables by extracting them.

@Test
public void twoHours_payEntryFee() {
  // Given
  Facility beFitGym = new Facility("Be Fit Gym", Facility.GYM);
  Visit visit = new Visit(beFitGym, 2);
  Client client = new Client("Mike");

  // When
  client.addVisit(visit);
  String payment = client.getReceipt();

  // Then
  String facilityName = "Be Fit Gym";
  String facilityPrice = "4.0";
  String facilityPoints = "100";

  assertThat(payment)
   .valueByXPath("/table/tr[1]/td[1]")
   .isEqualTo(facilityName);
       
  assertThat(payment)
    .valueByXPath("/table/tr[1]/td[2]")
    .isEqualTo(facilityPrice);

  assertThat(payment)
    .valueByXPath("/table/tr[1]/td[3]")
    .isEqualTo(facilityPoints);
}

Extract the assertions method

Now it’s time to extract the method. This is an automatic code refactoring in most Java development environments.

private void assertFacility(String payment,
    String facilityName,
    String facilityPrice,
    String facilityPoints) {
 
  assertThat(payment)
    .valueByXPath("/table/tr[1]/td[1]")
    .isEqualTo(facilityName);

  assertThat(payment)
    .valueByXPath("/table/tr[1]/td[2]")
    .isEqualTo(facilityPrice);

  assertThat(payment)
    .valueByXPath("/table/tr[1]/td[3]")
    .isEqualTo(facilityPoints);
}

The extracted local variables are no longer needed, so we can inline them. Below is the result of this test refactoring.

@Test
public void twoHours_isOnly_payEntryFee() {
  Facility beFitGym = new Facility("Be Fit Gym", Facility.GYM);
  Visit visit = new Visit(beFitGym, 2);
  Client client = new Client("Mike");

  // when
  client.addVisit(visit);
  String payment = client.getReceipt();

  // Then
  assertFacility(payment, "Be Fit Gym", 4.0, 100);
}

@Test
public void twoHours_PayForEach() {
  // Given
  Facility beFitGym = new Facility("Jacuzzi", Facility.STEAM_BATH);
  Visit visit = new Visit(beFitGym, 2);
  Client client = new Client("Mike");

  // When
  client.addVisit(visit);
  String payment = client.getReceipt();

  // Then
  assertFacility(payment, "Jacuzzi", 10.0, 150);
}

Pay attention to the parameters of the methods

Note that the tests have become shorter. The problem, however, is now the number of parameters that additionally belong to two groups. The first group is the input data (the first parameter) and the second group are the values of each assertion (the next three parameters). Additionally, if the parameters next to each other are of the same type, it is easy to get confused in their order.

Create a new assertion class

Next, I will use the above two groups of parameters as the direction for subsequent changes. I put the method in a new class and define one of the groups as a constructor parameter. Then the current method will only contain parameters from the second group and will gain access to the first group through the class fields.

Dokonaj ektrakcji klasy poprzez ekstrakcję delegata

To create a new class, I launch “extract delegate” code refactoring, which is another automated conversion in IntelliJ IDE for Java language.

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

Here is the result of code transformation.

private final FacilityAssertion facilityAssertion = new FacilityAssertion();

@Test
public void twoHours_isOnly_payEntryFee() {
  Facility beFitGym = new Facility("Be Fit Gym", Facility.GYM);
  Visit visit = new Visit(beFitGym, 2);
  Client client = new Client("Mike");

  // when
  client.addVisit(visit);
  String payment = client.getReceipt();

  // Then
  facilityAssertion.assertFacility(payment, "Be Fit Gym", 4.0, 100);
}

@Test
public void twoHours_PayForEach() {
  // Given
  Facility beFitGym = new Facility("Jacuzzi", Facility.STEAM_BATH);
  Visit visit = new Visit(beFitGym, 2);
  Client client = new Client("Mike");

  // When
  client.addVisit(visit);
  String payment = client.getReceipt();

  // Then
  facilityAssertion.assertFacility(payment, "Jacuzzi", 10.0, 150);
}

Inline field

The extra field in the class was not my goal. So I am absorbing this field. Then the new assertion object will be recreated from scratch wherever the field was used by logic.

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

@Test
public void twoHours_isOnly_payEntryFee() {
  Facility beFitGym = new Facility("Be Fit Gym", Facility.GYM);
  Visit visit = new Visit(beFitGym, 2);
  Client client = new Client("Mike");

  // when
  client.addVisit(visit);
  String payment = client.getReceipt();

  // Then
  new FacilityAssetion().assertFacility(payment, "Be Fit Gym", 4.0, 100);
}

@Test
public void twoHours_PayForEach() {
  // Given
  Facility beFitGym = new Facility("Jacuzzi", Facility.STEAM_BATH);
  Visit visit = new Visit(beFitGym, 2);
  Client client = new Client("Mike");

  // When
  client.addVisit(visit);
  String payment = client.getReceipt();

  // Then
  new FacilityAssetion().assertFacility(payment, "Jacuzzi", 10.0, 150);
}

Then I re-extract the “assertFacility” method. Thanks to this, calling the assertion constructor will be in one place only. Below the refactoring result.

private void assertFacility(String payment, String facilityName, 
      String facilityPrice, String facilityPoints) {
        new FacilityAssertion()
          .assertFacility(payment, facilityName, 
                          facilityPrice, facilityPoints);
    }

@Test
public void twoHours_isOnly_payEntryFee() {
  Facility beFitGym = new Facility("Be Fit Gym", Facility.GYM);
  Visit visit = new Visit(beFitGym, 2);
  Client client = new Client("Mike");

  // when
  client.addVisit(visit);
  String payment = client.getReceipt();

  // Then
  assertFacility(payment, "Be Fit Gym", 4.0, 100);
}

@Test
public void twoHours_PayForEach() {
  // Given
  Facility beFitGym = new Facility("Jacuzzi", Facility.STEAM_BATH);
  Visit visit = new Visit(beFitGym, 2);
  Client client = new Client("Mike");

  // When
  client.addVisit(visit);
  String payment = client.getReceipt();

  // Then
  assertFacility(payment, "Jacuzzi", 10.0, 150);
}

Move the parameter from the method to the constructor

The constructor (FacilityAssertion) is currently only called from one place. So I add a new parameter in constructor, then a field in this class. When the method uses the “payment” field instead of the “payment” parameter – I can delete the unnecessary parameter.

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

Replace the constructor with a static method call

Next, in the FacilityAssertion class, I run the automatic code transformation “Replace constructor call with static method”.

public class FacilityAssertion {
  private String payment;

  private FacilityAssertion(String payment) {
     this.payment = payment;
  }

  public static FacilityAssertion assertThat(String payment) {
      return new FacilityAssertion(payment);
  }

  void hasAttributes(String facilityName, String facilityPrice, 
     String facilityPoints) {
    XmlAssert.assertThat(this.payment)
      .valueByXPath("/table/tr[1]/td[1]")
      .isEqualTo(facilityName);

    XmlAssert.assertThat(this.payment)
      .valueByXPath("/table/tr[1]/td[2]")
      .isEqualTo(facilityPrice);

    XmlAssert.assertThat(this.payment)
      .valueByXPath("/table/tr[1]/td[3]")
      .isEqualTo(facilityPoints);
  }
}

Replace method with a method chain

Time to build a method chain. So I do the last extraction of a few new methods that will contain “return this” at their ends. This will allow me to make code refactoring of these methods into a call chain.

public class FacilityAssertion {
  private String payment;

  private FacilityAssertion(String payment) {
    this.payment = payment;
  }

  public static FacilityAssertion assertThat(String payment) {
    return new FacilityAssertion(payment);
  }

  FacilityAssertion hasAttributes(String facilityName,
    String facilityPrice,
    String facilityPoints) {
      return hasName(facilityName)
              .hasPrice(facilityPrice)
              .hasPoints(facilityPoints);
  }

  FacilityAssertion hasPoints(String facilityPoints) {
    XmlAssert.assertThat(this.payment)
      .valueByXPath("/table/tr[1]/td[3]")
      .isEqualTo(facilityPoints);
    return this;
  }

  FacilityAssertion hasPrice(String facilityPrice) {
    XmlAssert.assertThat(this.payment)
     .valueByXPath("/table/tr[1]/td[2]")
     .isEqualTo(facilityPrice);
    return this;
  }

  FacilityAssertion hasName(String facilityName) {
    XmlAssert.assertThat(this.payment)
     .valueByXPath("/table/tr[1]/td[1]")
     .isEqualTo(facilityName);
    return this;
  }
}

Inline initial assertion method


@Test
public void twoHours_isOnly_payEntryFee() {
  Facility beFitGym = new Facility("Be Fit Gym", Facility.GYM);
  Visit visit = new Visit(beFitGym, 2);
  Client client = new Client("Mike");
  // when
  client.addVisit(visit);
  String payment = client.getReceipt();
  // Then
  assertThat(payment)
    .hasName("Be Fit Gym")
    .hasPrice("4.0")
    .hasPoints("100");
}
@Test
public void twoHours_PayForEach() {
  // Given
  Facility beFitGym = new Facility("Jacuzzi", Facility.STEAM_BATH);
  Visit visit = new Visit(beFitGym, 2);
  Client client = new Client("Mike");
  // When
  client.addVisit(visit);
  String payment = client.getReceipt();
  // Then
  assertThat(payment)
    .hasName("Jacuzzi")
    .hasPrice("10.0")
    .hasPoints("150");
}

Use the builder or factory pattern analogously for the test setup

You’ve surely noticed that now the test configurations differ only in the type of facility and the visit duration. The returned facility name is always the same, so you can check it separately and only once.

@Test
public void twoHours_isOnly_payEntryFee() {
  // Given
  String payment = newPaymentFor(Facility.GYM, 2);
  // Then
  assertThat(payment)
    .hasPrice("4.0")
    .hasPoints("100");
}
@Test
public void twoHours_PayForEach() {
  // Given
  String payment = newPaymentFor(Facility.STEAM_BATH, 2);
  // Then
  assertThat(payment)
    .hasPrice("10.0")
    .hasPoints("150");
}

As you can see, we refactored code above into clean tests. They have no code duplication and are easy to understand. Writing another test is also simple.

Libraries promoting the fluent builder pattern


Fluent assertion pattern is supported by testing libraries. One of them is asserjJ that works very well with JUnit. It follows fluent builder pattern and allow to create one assertion at a time. It facilitates writing one detailed message in case of test failure or returning a new nested assertion instance that checks more.

Take care of tests readability

Uncle Bob once said (or wrote), “treat your tests like a first-class citizen.” So take care of your tests by constantly refactoring them! Clean Code is also Clean Tests!

Remember that the concept of the refactoring pyramid and the SOLID principles are equally applicable in cleaning tests through refactoring.

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

Friday, August 14, 2020

Different ways to remove Spaces from String In Java

Oracle Java Study Materials, Oracle Java Learning, Oracle Java Exam Prep, Java Guides

String manipulation is done most often while programming. Like removing spaces in or around the string text. This also known as ‘strip’ping off spaces in the string. So up till now we are all aware of the different ways to remove spaces from string in java, namely trim, replaceAll. However, java 11 has made some new additions to these with methods like, strip, stripLeading , stripTrailing.

Majority of the times, we just use the trim method for removing spaces. We never stop and think is there may be a better way to suit our need? Sure, trim() works well for most of the cases, but there are many different methods in java. Each having its own advantages and disadvantages. How do we decide which method suits us best?

Well, in this blog we shall cover the different methods in detail.

Different ways to remove spaces from string in java


1. trim() : Removing leading and trailing spaces from the string
2. strip() : Removes spaces at the beginning and end of the string. Strip method is Unicode charset aware
3. trim vs strip : Differences between trim and strip method
4. stripLeading() : Removes white spaces only from the beginning of the string
5. stripTrailing() : Removes white spaces only from ending of the string
6. replace() : Replaces all target characters with new character
7. replaceAll() : Replaces all matched characters with new character. This method takes regular expression as input to identify target substring that needs to be replaced
8. replaceAll vs replace : Differences between replace and replaceAll method
9. replaceFirst() : Replaces only first occurrence of target substring with new replacement string

Most important point to note is that in java a string object is immutable. It means we cannot modify a string, hence all the methods returns new string with all the transformations.

trim() method in java


trim() is the most commonly used method by java developers for removing leading and trailing spaces. For trim method space character means any character whose ASCII value is less than or equal to 32 (‘U+0020’).

Example of trim method to remove spaces:


public class StringTrimTest {

    public static void main(String[] args) {
        String string = "    String    with    space    ";
        System.out.println("Before trim: \"" + string +"\"");
        System.out.println("After trim: \"" + string.trim() +"\"");
   }
}

Output:

Before trim: "    String    with    space    "
After trim: "String    with    space"

strip() method Java 11


In the release of Java 11 new strip() method was added to remove leading and trailing spaces from String.

This method was added as there are various space characters according to Unicode standards having ASCII value more than 32(‘U+0020’). Ex: 8193(U+2001).

To identify these space characters, new method isWhitespace(int) was added from Java 1.5 in Character class. This method uses unicode to identify space characters. You can read more about unicode space characters here.

The strip method uses this Character.isWhitespace(int) method to cover wide range of white space characters and remove them.

Example of strip():


public class StringStripTest {
    public static void main(String[] args) {
        String string = "    String    with    space    ";
        System.out.println("Before strip: \"" + string+"\"");
        System.out.println("After strip: \"" + string.strip()+"\"");
    }
}

Output:

Before strip: "    String    with    space    "
After strip: "String    with    space"

Difference between trim and strip method in java


trim() strip()
From Java 1   From Java 11
Uses codepoint(ASCII) value   Uses Unicode value 
Removes leading and trailing character(space)   Removes leading and trailing character(space)
Removes characters having ASCII value less than or equal to ‘U+0020’ or ’32’   Removes all space characters according to unicode 

Let’s look at the example where we will use white space character higher than 32 (‘U+0020’) unicode.

public class StringTrimVsStripTest {
    public static void main(String[] args) {
        String string = '\u2001'+"String    with    space"+ '\u2001';
        System.out.println("Before: \"" + string+"\"");
        System.out.println("After trim: \"" + string.trim()+"\"");
        System.out.println("After strip: \"" + string.strip()+"\"");
   }
}

Output:

Before: "  String    with    space  "
After trim: " String    with    space "
After strip: "String    with    space"

In the above example we can see that trim method is unable to remove space character added by ‘\u2001’ unicode character.

stripLeading() method Java 11


Added in Java 11, stripLeading() method removes all leading spaces from a String.

Similar to strip method stripLeading also uses Character.isWhitespace(int) for identifyng white spaces.

public class StringStripLeadingTest {
    public static void main(String[] args) {
        String string = "    String    with    space    ";
        System.out.println("Before: \"" + string+"\"");
        System.out.println("After : \"" + string.stripLeading()+"\"");
    }
}

Output:

Before: "    String    with    space    "
After : "String    with    space    "

stripTrailing() method Java 11


Added in Java 11, stripTrailing() method removes all ending spaces from a String.

Similar to strip method stripTrailing also uses Character.isWhitespace(int) for identifying white spaces.

public class StringStripTrailingTest {
    public static void main(String[] args) {
      String string = "    String    with    space    ";
      System.out.println("Before: \"" + string+"\"");
        System.out.println("After : \"" + string.stripTrailing()+"\"");
    }
}

Output:

Before:"    String    with    space    "
After :"    String    with    space"

replace(CharSequence target, CharSequence replacement):


Added from java 1.5, This method is used to replace each target substring with the specified replacement string.

This method replaces all matching target elements.

Note: One more method replace(char oldChar, char newChar) is present in java string class. The only differences is that this method takes single character as target and replacement. We cannot use this method to remove space, because we cannot have empty character as replacement.

Example to remove all spaces from string


public class StringReplaceTest {
  
    public static void main(String[] args) {
        String string = "    String    with    space    ";
        System.out.println("Before : \"" + string + "\"");
        System.out.println("Replace: \"" + string.replace(" ", "") + "\"");
    }
}

Output:

Before  : "    String    with    space    "
Replace : "Stringwithspace"

replaceAll (String regex, String replacement)


Oracle Java Study Materials, Oracle Java Learning, Oracle Java Exam Prep, Java Guides
Added in java 1.4, this is one of the most powerful method for string manipulation. We can use this method for many purposes.

Using replaceAll() method we can replace each matching regular expression substring with the given replacement string. For example for removing all spaces, removing leading spaces, removing trailing spaces and so on.

We just need to create correct regular expression with correct replacement parameter. Some regular expression examples as below:

\s+ : Find all space
^\s+ : Find all spaces at line beginning
\s+$ : Find all spaces at line ending

Example to replacing spaces in string,


NOTE: In java to add ‘/’ we have to use escape character so for “\s+” we have to use “\\s+”

public class StringReplaceAllTest {
    public static void main(String[] args) {
        String string = "    String    with    space    ";
        System.out.println("Before replaceAll : \"" + string+"\"");
        System.out.println("Replace all space : \"" + string.replaceAll(" ", "") + "\"");
        System.out.println("Replace all regex : \"" + string.replaceAll("\\s+", "") + "\"");
        System.out.println("Replace Leading   : \"" + string.replaceAll("^\\s+", "") + "\""); 
        System.out.println("Replace trailing  : \"" + string.replaceAll("\\s+$", "") + "\"");
    }
}

Output:

Before replaceAll : "    String    with    space    "
Replace all space : "Stringwithspace"
Replace all regex : "Stringwithspace"
Replace Leading   : "String    with    space    "
Replace trailing  : "    String    with    space"

As we can see that replaceAll() is pretty powerful method if we use it with proper regular expression.

Difference between replaceAll and replace method


replaceAll() replace()
From Java 1.4 From Java 1.5
Accepts regular expression for target identification Accepts string for target identification
Used for fix or dynamic string replacement Used for fix string replacement
Removes characters having ASCII value less than or equal to ‘U+0020’ or ’32’ Removes all space characters according to unicode

replaceFirst(String regex, String replacement)


Added in java 1.4, replaceFirst method replaces only the first match of given regular expression with replacement string.

This method can be very useful if you just need to replace only one first occurence. For example if we just need to remove leading spaces we can use “\\s+” or “^\\s+”.

We can also use this method to remove trailing spaces by using “\\s+$” regular expression. As this expression will only match the last spaces in line. So last spaces are considered as the first match for this method.

Let’s take an example for removing leading and trailing spaces from string

public class StringReplaceFistTest {
      public static void main(String[] args) {
      String string = "    String    with    space    ";
      System.out.println("Before   : \"" + string+"\"");
        System.out.println("Replace  : \"" + string.replaceFirst("space", "update") + "\"");
        System.out.println("Leading  : \"" + string.replaceFirst("\\s+", "") + "\"");
        System.out.println("Trailing : \"" + string.replaceFirst("\\s+$", "") + "\"");    }
}

Output

Before   : "    String    with    space    "
Replace  : "    String    with    update    "
Leading  : "String    with    space    "
Trailing : "    String    with    space"