## Convert Integer to Binary in Java

December 09, 2020

## Integer to Binary

In This Article we will see how we can convert Integer to Binary number. We will see some built in options that Java provides as well as two different custom implementation.
Using Integer.toBinaryString
Using Integer.toBinaryString() method we can convert a integer to Binary String very easily
``````private static String toBinary1(Integer i) {
return Integer.toBinaryString(i);
}``````
Using Integer.toString()
We can also use Integer.toString() and pass the number and radix to convert the integer to String. In this case we pass 2 as radix to convert the Integer to Binary Number String.
`````` private static String toBinary2(Integer i) {
return Integer.toString(i, 2);
}``````
Using BigInteger
BigInteger also provides a toString() method where we can pass 2 as radix to convert it to Binary Number String.
``````private static String toBinary2(Integer i) {
BigInteger bigInt = new BigInteger(String.valueOf(i));
return bigInt.toString(2);
}``````
By Dividing.
Following code is a custom method to convert an Integer to Binary.
``````private static String toBinary_divide(Integer i) {

StringBuilder ret = new StringBuilder();

while (i > 0) {

if (i % 2 == 1) {
ret.insert(0, "1");
}
else {
ret.insert(0, "0");
}
i = i / 2;
}

return ret.toString();
}``````
This is another custom method to convert Integer to Binary String. This Algorithm works by masking each bit in the original number and creating a char array. And finally converting the char array to String.
``````private static String toBinary_mask(Integer num) {
char ret[] = new char[32];

for (int i = 0; i < 32; i++) {
int mask = 1 << i;
ret[31 - i] = (num & mask) != 0 ? '1' : '0';
}
return new String(ret);
}``````

### Full Code

IntegerToBinaryConverter.java
``````import java.math.BigInteger;

public class IntegerToBinaryConverter {

public static void main(String[] args) {
System.out.println("Convert to Binary 2020 = " + toBinary1(2020));
System.out.println("Convert to Binary 2020 = " + toBinary2(2020));
System.out.println("Convert to Binary 2020 = " + toBinary3(2020));
System.out.println("Convert to Binary 2020 = " + toBinary_divide(2020));
System.out.println("Convert to Binary 2020 = " + toBinary_mask(2020));
}

private static String toBinary1(Integer i) {
return Integer.toBinaryString(i);
}

private static String toBinary2(Integer i) {
return Integer.toString(i, 2);
}

private static String toBinary3(Integer i) {
BigInteger bigInt = new BigInteger(String.valueOf(i));
return bigInt.toString(2);
}

private static String toBinary_divide(Integer i) {
StringBuilder ret = new StringBuilder();
while (i > 0) {
if (i % 2 == 1) {
ret.insert(0, "1");
}
else {
ret.insert(0, "0");
}
i = i / 2;
}
return ret.toString();
}

private static String toBinary_mask(Integer num) {
char ret[] = new char[32];
for (int i = 0; i < 32; i++) {
int mask = 1 << i;
ret[31 - i] = (num & mask) != 0 ? '1' : '0';
}
return new String(ret);
}
}``````
Console Output
Convert to Binary 2020 = 11111100100
Convert to Binary 2020 = 11111100100
Convert to Binary 2020 = 11111100100
Convert to Binary 2020 = 11111100100
Convert to Binary 2020 = 00000000000000000000011111100100

### Summary

This article shows different ways to convert the Integer to Binary String. The Bit masking is very efficient and in fact the builtin methods like Integer.toString() uses Bit masking internally. For more information on Bit masking the links provided in Reference section is very useful.

October 30, 2020

## JavaScript Data Types

This article covers the datatypes available for JavaScript. The latest ECMAScript standard defines nine types: 7 Primitive types and 2 Structural Types.

## Primitive Types

The six primitive types are Boolean, Null, Undefined, String, Number, BigInt, and Symbol.

### Boolean type

Boolean represents a logical entity and can have two values: true and false. The Boolean object will be with the initial true only if the parameter passed is an object, array, or true. Else the Boolean object will be false.
Following code shows the different values the Boolean object will have when passed different parameters.
``````var b1 = new Boolean();
console.log(b1); //false

var b2 = new Boolean(false);
console.log(b2);//false

var b3 = new Boolean(0);
console.log(b3);//false

var b4 = new Boolean(NaN);
console.log(b4);//false

var b5 = new Boolean(undefined);
console.log(b5);//false

var b6 = new Boolean(null);
console.log(b6); //false

var b7 = new Boolean({});
console.log(b7);//true

var b8 = new Boolean(true);
console.log(b8);//true

var b9 = new Boolean([]);
console.log(b9);//true``````

### Null type

The Null type has exactly one value: null. Every Object is derived from null value, and therefore typeof operator returns object for it.
The following code shows one important feature of null, it is of type object.
``````var n1 = null;
console.log(n1); //null
console.log(typeof n1); //object``````

### Undefined type

A variable that has not been assigned a value has the value undefined.
The following code shows one example where a variable u1 is defined but not assigned any value.
``````var u1 ;
console.log(typeof u1);//undefined
console.log(u1);//undefined``````

### String

The string type is used to represent textual data. JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it
Strings can be created as primitives, from string literals, or as objects, using the String() constructor. In case of primitive typeof returns "string" otherwise it returns "object". String object can be converted to string primitives using valueOf() method on the String object.
``````const string1 = "A string primitive";
const string2 = new String("A String object");
console.log(typeof string1); //string
console.log(typeof string2); //object
console.log(typeof string2.valueOf());//string ``````

### Number

The Number type is a double-precision 64-bit binary format IEEE 754 value (numbers between -(2^53 − 1) and 2^53 − 1). In addition to representing floating-point numbers, the number type has three symbolic values: +Infinity, -Infinity, and NaN ("Not a Number"). Number.MAX_VALUE or Number.MIN_VALUE represents the maximum and minimum values possible using numbers.
``````console.log(Number.MAX_VALUE); //1.7976931348623157e+308
console.log(Number.MIN_VALUE); //5e-324
console.log(1/0); //Infinity``````

### BigInt type

The BigInt type is a numeric primitive in JavaScript that can represent integers with arbitrary precision. A BigInt is created by appending n to the end of an integer or by calling the constructor. BigInts cannot be operated on interchangeably with Numbers. Instead, a TypeError will be thrown.
Following code shows how to find the value of 2^53, we have choosen 53 because then the product value will be beyond the capacity of numbers. If you
``````const xbig = 2n ** 53n;
console.log(xbig); //9007199254740992n``````

### Symbol type

A Symbol is a unique and immutable primitive value and may be used as the key of an Object property (see below).
The following example shows how to create a Symbol object.
``````let sym1 = Symbol()
let sym2 = Symbol('foo')
let sym3 = Symbol('foo')``````

## Structural Types

Object and Functions are two structural data types.
typeof operator shows that for object and function the operator returns "object" and "function" respectively.
``````var o1 = {};
console.log(typeof o1);//object

var f1 = function () {};
console.log(typeof f1);//fuction``````

## Java Convert Integer to Roman Numbers

October 26, 2020

### Roman Number

Roman numerals have seven symbols. The table below shows these symbols and their decimal equivalents.

SymbolNumber
I1
V5
X10
L50
C100
D500
M1,000

### Negative Numbers and Range

We cannot represent negative numbers using Roman Numbers. The largest number you can write in Roman numerals is 3,999 which is MMMCMXCIX Numbers larger than 3,999 in Roman numerals is represented using an overline. An overline on a Roman numeral means we are multiplying that Roman numeral by 1,000. For the number 50,000 in Roman numerals, you would use the Roman numeral L (50) with an overline to make it 50,000

### Conversion Rules

I can be placed before V or X, represents subtract one, so IV (5-1) = 4 and 9 is IX (10-1)=9.
X can be placed before L or C represents subtract ten, so XL (50-10) = 40 and XC (100-10)=90.
C placed before D or M represents subtract hundred, so CD (500-100)=400 and CM (1000-100)=900. Roman numerals are usually written in highest to lowest from left to right except for some special cases where the left character is less than the right character.

### Implementation

The algorithm is simple
1) Place the roman literals in an array
2) Place corresponding integer values (numbers) in another array maintaining the corresponding indices.
3) Try subtracting the biggest number from the numbers array from the input value until the input is 0.
4) Append the corresponding roman literal to output String.

ToRoman.java
The following class defines a method that accepts an integer and returns a Roman Number in the form of a String object.
`````` /**
* I can be placed before V or X
*
* X can be placed before L or C
*
* C can be placed before D or M
*
*
*/
public static String convertToRomanNumber(int num) {

int number[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String roman[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

StringBuilder result = new StringBuilder();
for (int i = 0; i < number.length; i++) {
while (num >= number[i]) {
num = num - number[i];
result = result.append(roman[i]);
}
}

return result.toString();
}``````
Console
System.out.println("Integer 4 : Roman " + RomanNumbers.convertToRomanNumber(4)); System.out.println("Integer 100 : Roman " + RomanNumbers.convertToRomanNumber(100)); System.out.println("Integer 2000 : Roman " + RomanNumbers.convertToRomanNumber(2000)); System.out.println("Integer 3,999 : Roman " + RomanNumbers.convertToRomanNumber(3999)); Integer 4 : Roman IV Integer 100 : Roman C Integer 2000 : Roman MM Integer 3,999 : Roman MMMCMXCIX

October 18, 2020

## Java Threads Print Alternative Odd Even Numbers

This article shows how to print Even and Odd numbers alternatively using Java. It uses Two Java threads and a Class with two methods to print even numbers and odd numbers respectively.

### What we are trying to achieve

We want to print even and odd numbers alternatively but using two threads. Essentially it is the interaction between two threads utilizing the wait() and notify() methods. One thread completes a task (printing a single even number) then it is put on wait state so that the other thread can get a chance to do its job (printing odd number) and this goes on until we are done with printing a set of numbers determined by max.
How it will work
• Print Class (Print.java) with two synchronized methods even() and odd() which print even or odd numbers respectively.
• Each method is synchronized so that two threads cannot execute them concurrently.
• Each method first calls notifyAll() to so that other threads that are waiting can be wake up.
• It then prints a number (even or odd) and then calls the wait() method on the current thread so it goes to waiting state.

### Java Code

Print.java
This Class essentially has two synchronized methods. The constructor of this class takes a max number as a parameter. This max number is the limit to which the numbers will be printed. It has two synchronized methods to print even and odd numbers alternatively.
``````class Print {
int max;

public Print(int max) {
this.max = max;
}

public synchronized void even() throws InterruptedException {
for (int i = 0; i <= max; i++) {
notifyAll();
if (i % 2 == 0)
wait();
}
}

public synchronized void odd() throws InterruptedException {
for (int i = 0; i <= max; i++) {
notifyAll();
if (i % 2 != 0)
wait();
}
}
}``````
Here we are creating an instance of Print class and creating two Threads. From the first thread, we are calling print.even() method, from the second thread we are calling print.odd() method.
``````Print print = new Print(10);

@Override
public void run() {
try {
print.even();
} catch (InterruptedException e) {
}
}
});

@Override
public void run() {
try {
print.odd();
} catch (InterruptedException e) {
}
}
});

t1.start();
t2.start();``````
Console Output
Conclusion
• From the odd() or even () method we have to first call notify or notifyAll() first.
• Both odd() or even() method should be synchronized otherwise calling notifyAll() or wait() will throw exception

October 16, 2020

A thread in Java at any point of time exists in any one of the 6 states. This article give a quick introduction of different Thread states and respective methods which results in threads state change.
Following are the states of a Java Thread
• New: Thre thread is just created by using start() method on the tread
• Runnable: Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine but it may be waiting for other resources from the operating system such as a processor.
• Blocked: A thread in the blocked state is waiting for a monitor lock
• Waiting: A thread is in the waiting state due to calling one of the following methods:
Object.wait() with no timeout
LockSupport.park
• Timed Waiting: A thread is in the timed waiting state due to calling one of the following methods with a specified positive waiting time:Thread.sleep (long)
Object.wait (long)
LockSupport.parkNanos
LockSupport.parkUntil
• Terminated: The thread has completed execution

October 09, 2020

## Matrix Rotation in Java

In this article, we will explore a few different ways to rotate a matrix clock by 90 degrees.

## Rotating Matrix to 90 Clockwise

Following is our Matrix.

[    1        2        3    ]

[    4        5        6    ]

[    7        8        9    ]

We will explore multiple ways to rotate this matrix clockwise 90

### With Matrix Transpose

Matrix transpose is a flipped version of the matrix along its diagonal. In short, it is the same as interchanging the rows with columns. For the above matrix the transposed matrix will look like.

[    1        4        7    ]

[    2        5        8    ]

[    3        6        9    ]

Also, the transposed matrix is equivalent to 90 Left rotation of the original array.
RoateMatrixWithTranspose
Here the Rotation of the matrix is done in two steps
1) We transpose the matrix 2) And we interchange the columns
``````public void rotateMatrixRight90Transpose(int[][] mat) {

int m = mat.length;
int n = mat[0].length;

for (int i = 0; i < m; i++) {
for (int j = i; j < n; j++) {
int x = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = x;
System.out.println("IC" + i + ":" + j);
}
}

// swap cols
for (int i = 0; i < m; i++) {
for (int j = 0; j < n / 2; j++) {
// swap mat[i][j] with mat[N-i-1][j]
int temp = mat[i][j];
mat[i][j] = mat[i][n - j - 1];
mat[i][n - j - 1] = temp;
}
}
}``````
Output

Matrix Rotation with Transpose

<= Original Matrix  =>

[    1        2        3    ]

[    4        5        6    ]

[    7        8        9    ]

<= After Transpose =>

[    1        4        7    ]

[    2        5        8    ]

[    3        6        9    ]

<= After Rotation =>

[    7        4        1    ]

[    8        5        2    ]

[    9        6        3    ]

## Matrix Rotation in Single pass

MatrixRotation.java
The following code will rotate the matrix in a single pass.
``````public void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < (n + 1) / 2; i++) {
for (int j = 0; j < n / 2; j++) {
int temp = matrix[n - 1 - j][i];
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1];
matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 - i];
matrix[j][n - 1 - i] = matrix[i][j];
matrix[i][j] = temp;
}
}
}``````
Output

Matrix Rotation with single pass

<= Original Matrix  =>

[    1        2        3    ]

[    4        5        6    ]

[    7        8        9    ]

<= After Rotation =>

[    7        4        1    ]

[    8        5        2    ]

[    9        6        3    ]

October 07, 2020

## Eclipse Google Java Style Guide

This article shows how to use the Google Java style with Eclipse IDE. Every organization has its own style guide, in the open-source community different projects have a slightly different style guide. In this article, we will see how to use the official google style guide in Eclipse IDE.

### Get the Style Guide

Save the style guide which is a XML file to your local drive.

### Open Eclipse Preference

Opening Eclipse settings varies per OS. For example, on macOS open Eclipse -> Preferences.

### Configure save actions to automatically format code while saving files.

In the Preferences menu type “save actions”, and select Java -> Editor -> Save Actions.

## Junit 5 Example : Display Name

September 30, 2020

## JUnit 5 Tutorial : Display name

In JUnit 5, we can use @DisplayName to declare custom display names for test classes and test methods.

### Display Name Example

``````package com.bootng.display;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

public class DisplayCustomNameTest {

@Test
public void test_if_it_will_rain() {
}

@Test
public void test_if_it_will_be_cloudy() {
}

@Test
public void test_if_it_will_be_sunny() {
}

}

``````
Output

### Display CustomName Example

``````package com.bootng.display;
@DisplayName("Vacation Weather Test")
public class DisplayCustNameTest {
@DisplayName("ðŸŒ§")
@Test
public void test_if_it_will_rain() {
}

@DisplayName("ðŸŒ¨")
@Test
public void test_if_it_will_be_cloudy() {
}

@DisplayName("ðŸŒž")
@Test
public void test_if_it_will_be_sunny() {
}
}
``````
Output

### Custom Name Generator Example

We can also use a Custom Name generator to generate the test names. As of Version 5.4 it comes with the following generators out of the box.

DisplayNameGenerator.IndicativeSentences
DisplayNameGenerator.ReplaceUnderscores
DisplayNameGenerator.Simple
DisplayNameGenerator.Standard

Each of the above generators has different implementations of how to generate test name.

In the Following example we are using ReplaceUnderscores.  As a result the test names will be generated by replacing the "_" from respective names.
``````package com.bootng.display;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

@DisplayName("Weather Test DisplayExample ")
@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
public class DisplayGeneratorExampleTest {

@Test
public void test_if_it_will_rain() {
}

@Test
public void test_if_it_will_be_cloudy() {
}

@Test
public void test_if_it_will_be_sunny() {
}
}
``````

Output

## JUnit5 Important Annotations

September 30, 2020

## JUnit5 Important Annotations

Junit 5 comes with some new annotations that were not available in previous releases. Understanding these Annotations will help in writing efficient tests. This article covers some of the most commonly used annotations. In the next section, we will example of those annotations.
The following are some of the important annotations in JUnit 5.

### @Test

@Test : Denotes that a method is a test method. Without this annotation, JUnit will ignore the method

### @ParameterizedTest

Denotes a method to be a parameterized test method. Parameterized tests make it possible to run a test multiple times with different arguments.

### @RepeatedTest

@RepeatedTest : Test methods marked with @RepeatedTest can be executed repeatedly

### @TestMethodOrder

@TestMethodOrder: Helps maintain order in which test methods are executed.

### @DisplayName

@DisplayName : Helps in using a custom name to be printed either in the console or test report for the test method.

### @DisplayNameGeneration

@DisplayNameGeneration : Declares a custom display name generator for the test class

### @BeforeEach

@BeforeEach: Analogous to JUnit 4 @Before. Denotes the annotated method should be executed before each test. The method should not return any value, should not be private.

### @AfterEach

@AfterEach : Analogous to JUnit 4 @After. Denotes the annotated method should be executed after each test. The method should not return any value, should not be private.

### @BeforeAll

@BeforeAll: Denotes that the annotated method should be executed before all @Test, @RepeatedTest, @ParameterizedTest, and @TestFactory methods in the current class; analogous to JUnit 4’s @BeforeClass. Such methods are inherited (unless they are hidden or overridden) and must be static (unless the "per-class" test instance lifecycle is used).

### @AfterAll

@AfterAll: Denotes that the annotated method should be executed after all @Test, @RepeatedTest, @ParameterizedTest, and @TestFactory methods in the current class; analogous to JUnit 4’s @AfterClass. A method marked with @AfterAll is inherited (unless they are hidden or overridden) and must be static.

### @Nested

@Nested:Denotes that the annotated class is a non-static nested test class. @BeforeAll and @AfterAll methods cannot be used directly in a @Nested test class unless the "per-class" test instance lifecycle is used. Such annotations are not inherited.

### @Tag

@Tag: Used to declare tags for filtering tests, either at the class or method level; analogous to test groups in TestNG or Categories in JUnit 4. Such annotations are inherited at the class level but not at the method level.

### @Disabled

@Disabled : Used to disable a test class or test method; analogous to JUnit 4’s @Ignore. Such annotations are not inherited.

### @Timeout

@Timeout: Used to fail a test, test factory, test template, or lifecycle method if its execution exceeds a given duration. Such annotations are inherited.

## JUnit5 Test Suites

September 30, 2020

## JUnit 5 Test Suites

The test suite is a container that has a set of tests that can be executed together. For instance, say we have multiple tests and want to execute all of them or subset of them under certain conditions. Like we want to run all the tests in the integration stage, a subset of tests in the developer environment before pushing code. All these can be done using Test Suite. Using JUnit 5 test suites, we can run tests spread into multiple test classes and different packages. JUnit 5 provides two annotations: @SelectPackages and @SelectClasses to create test suites. Additionally, you can use other annotations for filtering test packages, classes, or even test methods.

## Filtering Tests in Suites

Tests in JUnit5 can be executed with @RunWith. The same annotation is also used for Junit 4. The only difference Is in Junit 5 we pass JUnitPlatform as a parameter. In this article we will go though some sample use cases of creating TestSuite in JUnit 5 and how to filter test classes, test methods in the test suite etc.

### @SelectPackages

With this annotation, we can tell the Test Suite to scan all the mention packages and its sub-packages and execute all the Test Classes. We can also specify a signal package or multiple packages. Following example demonstrates this.
Select a single package
With @SelectPackages we can select test classes only from a specified package or list of packages. In the following example, all the Test classes from package com.bootng will be executed.
``````import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.runner.RunWith;

@RunWith(JUnitPlatform.class)
@SelectPackages({ "com.bootng" })
public class TestSuiteWithPackageSingle {

}``````
Select multiple packages
Similarly, if we want to support multiple packages then we can specify multiple package names. The following example will execute tests from the two packages.
``````@RunWith(JUnitPlatform.class)
@SelectPackages({ "com.bootng.assertions", "com.bootng.display" })
public class TestSuiteWithPackageMultiple {

}``````

### @SelectClasses

Select Two Classes
In this example rather than selecting packages, we can specify individual test classes that we want to include in the Test Suite. In the following example essentially we will have only two Test classes in the Test Suite.
``````@RunWith(JUnitPlatform.class)
@SelectClasses({ DisplayExampleTest.class, DisplayGeneratorExampleTest.class })
public class TestSuiteWithSelectClass {

}
``````

### @IncludePackages and @ExcludePackages

@IncludePackages and @ExcludePackages work only at the specified package level and it won't scan sub-packages. This annotation is used with @SelectPackages annotation to fine-tune the filtering. Son in the following example Test Classes from only com.bootng.assertions will be included.
IncludePackages Example
Here
``````@RunWith(JUnitPlatform.class)
@SelectPackages({ "com.bootng" })
@IncludePackages({ "com.bootng.assertions" })
public class TestSuite_IncludePackage {

}
``````
ExcludePackages Example
Includes all the test form package com.bootng, but excludes tests from sub package com.bootng.assertions.
``````@RunWith(JUnitPlatform.class)
@SelectPackages({ "com.bootng" })
@IncludePackages({ "com.bootng.assertions" })
public class TestSuite_IncludePackage {

}
``````

### @IncludeClassNamePatterns and @ExcludeClassNamePatterns

Rather than filtering the test class from packages, we can also filter them based on the name of the Test Classes. To specify test class names patterns to exclude or include, you can use @IncludeClassNamePatterns and @ExcludeClassNamePatterns annotations.
IncludeClassNamePatterns Example
In this example, we can including only the test whose name ends with "Test" from the package (and sub packages) of com.bootng
``````@RunWith(JUnitPlatform.class)
@SelectPackages({ "com.bootng" })
@IncludeClassNamePatterns("^.*Test*\$")
public class TestSuite_NamePattern {

}
``````

### @IncludeTags and @ExcludeTags

IncludeTags Example
With IncludeTags and Exclude Tags we can filter Classes or Methods that are Tagged with the specified tag. For Instance, the following example, we are scanning package com.bootng.assertions and then only interested in including Test Classes or Test Methods tagged with Weather.
``````@RunWith(JUnitPlatform.class)
@SelectPackages({ "com.bootng.assertions" })
@IncludeTags({ "Weather" })
public class TestSuite_TagInclude {

}``````
ExcludeTags Example
Similar to IncludeTags tag to filter Test Methods or Test Classes but for exclusion. The following example will exclude all the Tests tagged with "Weather"
``````@RunWith(JUnitPlatform.class)
@SelectPackages({ "com.bootng.assertions" })
@ExcludeTags({ "Weather" })
public class TestSuite_TagExclude {

}
``````

## Summary

JUnit 5 provides powerful ways to filter Test cases in Test Suites. We have several options starting from including/excluding a specific packages to include/exclude specific Classes to Include/Exclude specific methods.

## Test Classes and Methods Requirement

September 21, 2020

## Test Classes and Methods Requirement

JUnit 5 is the latest version of Junit. It has a brand new architecture and more capabilities compared to the previous generation of Junit. In this article, we will quickly go through some of the main features and concepts of JUnit 5. In this article we go over the high-level structural requirement for writing Unit Tests. Generally, we write test method to represent a test case or a certain scenario which we want to validate. Such test methods would reside inside a Class. With Junit5 we don't need to mark or annotate the main class with any special JUnit specific annotations. Junit5 will be able to

### Test Class

Any top-level class, static member class, or @Nested class that contains at least one test method. We don't need to annotate the Class, JUnit5 will be able to find test methods defined inside it.
Class Requirement
The Class should contain only one Constructor and the Class should not be an abstract Class.

### Test Method

Any not abstract instance method that is annotated with @Test, @RepeatedTest, @ParameterizedTest, @TestFactory, or @TestTemplate.
Test Method
The test method should not return any value and should not be abstract.

### Lifecycle Method

Any method that is directly annotated or meta-annotated with @BeforeAll, @AfterAll, @BeforeEach, or @AfterEach Lifecycle methods can be inherited from parent class. Lifecycle methods should not be private and should not return any value.
Lifecycle Method
Should not be private and should not return value. @BeforeAll and @AfterAll should be used on a static method

### Example

Following Example shows a Test Class with one test method annotated with @Test and four Lifecylcle emthods
SimpleHelloTest3
``````package com.bootng.start;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;

public class SimpleHelloTest3 {

@BeforeAll
public static void method1() {
System.out.println("method 1");
}

@BeforeEach
public void method2() {
System.out.println("method 2");
}

@AfterAll
public static void method3() {
System.out.println("method 3");
}

@AfterEach
public void method4() {
System.out.println("method 4");
}

@Test
public void test_hello() {
String msg = "hello";
assertEquals(msg, "hello", " message is equal Hello");
System.out.println("");
}

}
``````
Running the above test would output the following. method1 and method2 would be executed before the actual test and then method4 and method3 would be executed.
Console Output
method 1 method 2 test_hello method 4 method 3