Bael-624 - Code Review fixes

This commit is contained in:
Kyle Doyle
2019-10-07 22:23:44 -04:00
parent db85c8f275
commit 07859c6e38
20348 changed files with 1637653 additions and 0 deletions
@@ -0,0 +1,25 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml
@@ -0,0 +1,34 @@
## Core Java Lang
This module contains articles about core features in the Java language
### Relevant Articles:
- [Generate equals() and hashCode() with Eclipse](https://www.baeldung.com/java-eclipse-equals-and-hashcode)
- [Iterating Over Enum Values in Java](https://www.baeldung.com/java-enum-iteration)
- [Java Double Brace Initialization](https://www.baeldung.com/java-double-brace-initialization)
- [Guide to the Diamond Operator in Java](https://www.baeldung.com/java-diamond-operator)
- [Comparator and Comparable in Java](https://www.baeldung.com/java-comparator-comparable)
- [The Java continue and break Keywords](https://www.baeldung.com/java-continue-and-break)
- [Nested Classes in Java](https://www.baeldung.com/java-nested-classes)
- [A Guide to Inner Interfaces in Java](https://www.baeldung.com/java-inner-interfaces)
- [Recursion In Java](https://www.baeldung.com/java-recursion)
- [A Guide to the finalize Method in Java](https://www.baeldung.com/java-finalize)
- [Infinite Loops in Java](https://www.baeldung.com/infinite-loops-java)
- [Quick Guide to java.lang.System](https://www.baeldung.com/java-lang-system)
- [Using Java Assertions](https://www.baeldung.com/java-assert)
- [Static and Dynamic Binding in Java](https://www.baeldung.com/java-static-dynamic-binding)
- [Synthetic Constructs in Java](https://www.baeldung.com/java-synthetic)
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
- [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name)
- [Java Compound Operators](https://www.baeldung.com/java-compound-operators)
- [Guide to Java Packages](https://www.baeldung.com/java-packages)
- [The Java Native Keyword and Methods](https://www.baeldung.com/java-native)
- [If-Else Statement in Java](https://www.baeldung.com/java-if-else)
- [Control Structures in Java](https://www.baeldung.com/java-control-structures)
- [Java Interfaces](https://www.baeldung.com/java-interfaces)
- [Attaching Values to Java Enum](https://www.baeldung.com/java-enum-values)
- [Variable Scope in Java](https://www.baeldung.com/java-variable-scope)
- [Java Classes and Objects](https://www.baeldung.com/java-classes-objects)
- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums)
- [[More --> ]](/core-java-modules/core-java-lang-2)
+71
View File
@@ -0,0 +1,71 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-lang</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-lang</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- web -->
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-lang</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<gson.version>2.8.2</gson.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>
@@ -0,0 +1,26 @@
package com.baeldung.assertion;
/**
* Simple demonstration of using Java assert keyword.
*/
public class Assertion {
public static void main(String[] args) {
Assertion assertion = new Assertion();
assertion.setup();
}
public void setup() {
Object conn = getConnection();
assert conn != null : "Connection is null";
// continue with other setup ...
}
// Simulate failure to get a connection; using Object
// to avoid dependencies on JDBC or some other heavy
// 3rd party library
public Object getConnection() {
return null;
}
}
@@ -0,0 +1,23 @@
package com.baeldung.binding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by madhumita.g on 25-07-2018.
*/
public class Animal {
final static Logger logger = LoggerFactory.getLogger(Animal.class);
public void makeNoise() {
logger.info("generic animal noise");
}
public void makeNoise(Integer repetitions) {
while(repetitions != 0) {
logger.info("generic animal noise countdown " + repetitions);
repetitions -= 1;
}
}
}
@@ -0,0 +1,43 @@
package com.baeldung.binding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by madhumita.g on 25-07-2018.
*/
public class AnimalActivity {
final static Logger logger = LoggerFactory.getLogger(AnimalActivity.class);
public static void sleep(Animal animal) {
logger.info("Animal is sleeping");
}
public static void sleep(Cat cat) {
logger.info("Cat is sleeping");
}
public static void main(String[] args) {
Animal animal = new Animal();
//calling methods of animal object
animal.makeNoise();
animal.makeNoise(3);
//assigning a dog object to reference of type Animal
Animal catAnimal = new Cat();
catAnimal.makeNoise();
// calling static function
AnimalActivity.sleep(catAnimal);
return;
}
}
@@ -0,0 +1,18 @@
package com.baeldung.binding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by madhumita.g on 25-07-2018.
*/
public class Cat extends Animal {
final static Logger logger = LoggerFactory.getLogger(Cat.class);
public void makeNoise() {
logger.info("meow");
}
}
@@ -0,0 +1,9 @@
package com.baeldung.className;
public class RetrievingClassName {
public class InnerClass {
}
}
@@ -0,0 +1,51 @@
package com.baeldung.comparable;
public class Player implements Comparable<Player> {
private int ranking;
private String name;
private int age;
public Player(int ranking, String name, int age) {
this.ranking = ranking;
this.name = name;
this.age = age;
}
public int getRanking() {
return ranking;
}
public void setRanking(int ranking) {
this.ranking = ranking;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return this.name;
}
@Override
public int compareTo(Player otherPlayer) {
return (this.getRanking() - otherPlayer.getRanking());
}
}
@@ -0,0 +1,25 @@
package com.baeldung.comparable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PlayerSorter {
public static void main(String[] args) {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 20);
Player player2 = new Player(67, "Roger", 22);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam);
System.out.println("After Sorting : " + footballTeam);
}
}
@@ -0,0 +1,46 @@
package com.baeldung.comparator;
public class Player {
private int ranking;
private String name;
private int age;
public Player(int ranking, String name, int age) {
this.ranking = ranking;
this.name = name;
this.age = age;
}
public int getRanking() {
return ranking;
}
public void setRanking(int ranking) {
this.ranking = ranking;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return this.name;
}
}
@@ -0,0 +1,12 @@
package com.baeldung.comparator;
import java.util.Comparator;
public class PlayerAgeComparator implements Comparator<Player> {
@Override
public int compare(Player firstPlayer, Player secondPlayer) {
return (firstPlayer.getAge() - secondPlayer.getAge());
}
}
@@ -0,0 +1,27 @@
package com.baeldung.comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PlayerAgeSorter {
public static void main(String[] args) {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 22);
Player player2 = new Player(67, "Roger", 20);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
System.out.println("Before Sorting : " + footballTeam);
//Instance of PlayerAgeComparator
PlayerAgeComparator playerComparator = new PlayerAgeComparator();
Collections.sort(footballTeam, playerComparator);
System.out.println("After Sorting by age : " + footballTeam);
}
}
@@ -0,0 +1,12 @@
package com.baeldung.comparator;
import java.util.Comparator;
public class PlayerRankingComparator implements Comparator<Player> {
@Override
public int compare(Player firstPlayer, Player secondPlayer) {
return (firstPlayer.getRanking() - secondPlayer.getRanking());
}
}
@@ -0,0 +1,27 @@
package com.baeldung.comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PlayerRankingSorter {
public static void main(String[] args) {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 22);
Player player2 = new Player(67, "Roger", 20);
Player player3 = new Player(45, "Steven", 40);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
System.out.println("Before Sorting : " + footballTeam);
//Instance of PlayerRankingComparator
PlayerRankingComparator playerComparator = new PlayerRankingComparator();
Collections.sort(footballTeam, playerComparator);
System.out.println("After Sorting by ranking : " + footballTeam);
}
}
@@ -0,0 +1,68 @@
package com.baeldung.controlstructures;
public class ConditionalBranches {
/**
* Multiple if/else/else if statements examples. Shows different syntax usage.
*/
public static void ifElseStatementsExamples() {
int count = 2; // Initial count value.
// Basic syntax. Only one statement follows. No brace usage.
if (count > 1)
System.out.println("Count is higher than 1");
// Basic syntax. More than one statement can be included. Braces are used (recommended syntax).
if (count > 1) {
System.out.println("Count is higher than 1");
System.out.println("Count is equal to: " + count);
}
// If/Else syntax. Two different courses of action can be included.
if (count > 2) {
System.out.println("Count is higher than 2");
} else {
System.out.println("Count is lower or equal than 2");
}
// If/Else/Else If syntax. Three or more courses of action can be included.
if (count > 2) {
System.out.println("Count is higher than 2");
} else if (count <= 0) {
System.out.println("Count is less or equal than zero");
} else {
System.out.println("Count is either equal to one, or two");
}
}
/**
* Ternary Operator example.
* @see ConditionalBranches#ifElseStatementsExamples()
*/
public static void ternaryExample() {
int count = 2;
System.out.println(count > 2 ? "Count is higher than 2" : "Count is lower or equal than 2");
}
/**
* Switch structure example. Shows how to replace multiple if/else statements with one structure.
*/
public static void switchExample() {
int count = 3;
switch (count) {
case 0:
System.out.println("Count is equal to 0");
break;
case 1:
System.out.println("Count is equal to 1");
break;
case 2:
System.out.println("Count is equal to 2");
break;
default:
System.out.println("Count is either negative, or higher than 2");
break;
}
}
}
@@ -0,0 +1,157 @@
package com.baeldung.controlstructures;
public class Loops {
/**
* Dummy method. Only prints a generic message.
*/
private static void methodToRepeat() {
System.out.println("Dummy method.");
}
/**
* Shows how to iterate 50 times with 3 different method/control structures.
*/
public static void repetitionTo50Examples() {
for (int i = 1; i <= 50; i++) {
methodToRepeat();
}
int whileCounter = 1;
while (whileCounter <= 50) {
methodToRepeat();
whileCounter++;
}
int count = 1;
do {
methodToRepeat();
count++;
} while (count < 50);
}
/**
* Splits a sentence in words, and prints each word in a new line.
* @param sentence Sentence to print as independent words.
*/
public static void printWordByWord(String sentence) {
for (String word : sentence.split(" ")) {
System.out.println(word);
}
}
/**
* Prints text an N amount of times. Shows usage of the {@code break} branching statement.
* @param textToPrint Text to repeatedly print.
* @param times Amount to times to print received text.
*/
public static void printTextNTimes(String textToPrint, int times) {
int counter = 1;
while (true) {
System.out.println(textToPrint);
if (counter == times) {
break;
}
}
}
/**
* Prints text an N amount of times, up to 50. Shows usage of the {@code break} branching statement.
* @param textToPrint Text to repeatedly print.
* @param times Amount to times to print received text. If times is higher than 50, textToPrint will only be printed 50 times.
*/
public static void printTextNTimesUpTo50(String textToPrint, int times) {
int counter = 1;
while (counter < 50) {
System.out.println(textToPrint);
if (counter == times) {
break;
}
}
}
/**
* Finds the index of {@code name} in a list
* @param name The name to look for
* @param names The list of names
* @return The index where the name was found or -1 otherwise
*/
public static int findFirstInstanceOfName(String name, String[] names) {
int index = 0;
for ( ; index < names.length; index++) {
if (names[index].equals(name)) {
break;
}
}
return index == names.length ? -1 : index;
}
/**
* Takes several names and makes a list, skipping the specified {@code name}.
*
* @param name The name to skip
* @param names The list of names
* @return The list of names as a single string, missing the specified {@code name}.
*/
public static String makeListSkippingName(String name, String[] names) {
String list = "";
for (int i = 0; i < names.length; i++) {
if (names[i].equals(name)) {
continue;
}
list += names[i];
}
return list;
}
/**
* Prints an specified amount of even numbers. Shows usage of both {@code break} and {@code continue} branching statements.
* @param amountToPrint Amount of even numbers to print.
*/
public static void printEvenNumbers(int amountToPrint) {
if (amountToPrint <= 0) { // Invalid input
return;
}
int iterator = 0;
int amountPrinted = 0;
while (true) {
if (iterator % 2 == 0) { // Is an even number
System.out.println(iterator);
amountPrinted++;
iterator++;
} else {
iterator++;
continue; // Won't print
}
if (amountPrinted == amountToPrint) {
break;
}
}
}
/**
* Prints an specified amount of even numbers, up to 100. Shows usage of both {@code break} and {@code continue} branching statements.
* @param amountToPrint Amount of even numbers to print.
*/
public static void printEvenNumbersToAMaxOf100(int amountToPrint) {
if (amountToPrint <= 0) { // Invalid input
return;
}
int iterator = 0;
int amountPrinted = 0;
while (amountPrinted < 100) {
if (iterator % 2 == 0) { // Is an even number
System.out.println(iterator);
amountPrinted++;
iterator++;
} else {
iterator++;
continue; // Won't print
}
if (amountPrinted == amountToPrint) {
break;
}
}
}
}
@@ -0,0 +1,40 @@
package com.baeldung.doubles;
import java.math.BigDecimal;
public class SplitFloatingPointNumbers {
public static void main(String[] args) {
double doubleNumber = 24.04;
splitUsingFloatingTypes(doubleNumber);
splitUsingString(doubleNumber);
splitUsingBigDecimal(doubleNumber);
}
private static void splitUsingFloatingTypes(double doubleNumber) {
System.out.println("Using Floating Point Arithmetics:");
int intPart = (int) doubleNumber;
System.out.println("Double Number: "+doubleNumber);
System.out.println("Integer Part: "+ intPart);
System.out.println("Decimal Part: "+ (doubleNumber - intPart));
}
private static void splitUsingString(double doubleNumber) {
System.out.println("Using String Operations:");
String doubleAsString = String.valueOf(doubleNumber);
int indexOfDecimal = doubleAsString.indexOf(".");
System.out.println("Double Number: "+doubleNumber);
System.out.println("Integer Part: "+ doubleAsString.substring(0, indexOfDecimal));
System.out.println("Decimal Part: "+ doubleAsString.substring(indexOfDecimal));
}
private static void splitUsingBigDecimal(double doubleNumber) {
System.out.println("Using BigDecimal Operations:");
BigDecimal bigDecimal = new BigDecimal(String.valueOf(doubleNumber));
int intValue = bigDecimal.intValue();
System.out.println("Double Number: "+bigDecimal.toPlainString());
System.out.println("Integer Part: "+intValue);
System.out.println("Decimal Part: "+bigDecimal.subtract(new BigDecimal(intValue)).toPlainString());
}
}
@@ -0,0 +1,17 @@
package com.baeldung.enums.values;
/**
* This is a simple enum of periodic table elements
*/
public enum Element1 {
H,
HE,
LI,
BE,
B,
C,
N,
O,
F,
NE
}
@@ -0,0 +1,52 @@
package com.baeldung.enums.values;
/**
* The simple enum has been enhanced to add the name of the element.
*/
public enum Element2 {
H("Hydrogen"),
HE("Helium"),
LI("Lithium"),
BE("Beryllium"),
B("Boron"),
C("Carbon"),
N("Nitrogen"),
O("Oxygen"),
F("Flourine"),
NE("Neon");
/** a final variable to store the label, which can't be changed */
public final String label;
/**
* A private constructor that sets the label.
* @param label
*/
private Element2(String label) {
this.label = label;
}
/**
* Look up Element2 instances by the label field. This implementation iterates through
* the values() list to find the label.
* @param label The label to look up
* @return The Element2 instance with the label, or null if not found.
*/
public static Element2 valueOfLabel(String label) {
for (Element2 e2 : values()) {
if (e2.label.equals(label)) {
return e2;
}
}
return null;
}
/**
* Override the toString() method to return the label instead of the declared name.
* @return
*/
@Override
public String toString() {
return this.label;
}
}
@@ -0,0 +1,63 @@
package com.baeldung.enums.values;
import java.util.HashMap;
import java.util.Map;
/**
* A Map has been added to cache labels for faster lookup.
*/
public enum Element3 {
H("Hydrogen"),
HE("Helium"),
LI("Lithium"),
BE("Beryllium"),
B("Boron"),
C("Carbon"),
N("Nitrogen"),
O("Oxygen"),
F("Flourine"),
NE("Neon");
/**
* A map to cache labels and their associated Element3 instances.
* Note that this only works if the labels are all unique!
*/
private static final Map<String, Element3> BY_LABEL = new HashMap<>();
/** populate the BY_LABEL cache */
static {
for (Element3 e3 : values()) {
BY_LABEL.put(e3.label, e3);
}
}
/** a final variable to store the label, which can't be changed */
public final String label;
/**
* A private constructor that sets the label.
* @param label
*/
private Element3(String label) {
this.label = label;
}
/**
* Look up Element2 instances by the label field. This implementation finds the
* label in the BY_LABEL cache.
* @param label The label to look up
* @return The Element3 instance with the label, or null if not found.
*/
public static Element3 valueOfLabel(String label) {
return BY_LABEL.get(label);
}
/**
* Override the toString() method to return the label instead of the declared name.
* @return
*/
@Override
public String toString() {
return this.label;
}
}
@@ -0,0 +1,95 @@
package com.baeldung.enums.values;
import java.util.HashMap;
import java.util.Map;
/**
* Multiple fields have been added and the Labeled interface is implemented.
*/
public enum Element4 implements Labeled {
H("Hydrogen", 1, 1.008f),
HE("Helium", 2, 4.0026f),
LI("Lithium", 3, 6.94f),
BE("Beryllium", 4, 9.01722f),
B("Boron", 5, 10.81f),
C("Carbon", 6, 12.011f),
N("Nitrogen", 7, 14.007f),
O("Oxygen", 8, 15.999f),
F("Flourine", 9, 18.998f),
NE("Neon", 10, 20.180f);
/**
* Maps cache labels and their associated Element3 instances.
* Note that this only works if the values are all unique!
*/
private static final Map<String, Element4> BY_LABEL = new HashMap<>();
private static final Map<Integer, Element4> BY_ATOMIC_NUMBER = new HashMap<>();
private static final Map<Float, Element4> BY_ATOMIC_WEIGHT = new HashMap<>();
/** populate the caches */
static {
for (Element4 e4 : values()) {
BY_LABEL.put(e4.label, e4);
BY_ATOMIC_NUMBER.put(e4.atomicNumber, e4);
BY_ATOMIC_WEIGHT.put(e4.atomicWeight, e4);
}
}
/** final variables to store the values, which can't be changed */
public final String label;
public final int atomicNumber;
public final float atomicWeight;
private Element4(String label, int atomicNumber, float atomicWeight) {
this.label = label;
this.atomicNumber = atomicNumber;
this.atomicWeight = atomicWeight;
}
/**
* Implement the Labeled interface.
* @return the label value
*/
@Override
public String label() {
return label;
}
/**
* Look up Element2 instances by the label field. This implementation finds the
* label in the BY_LABEL cache.
* @param label The label to look up
* @return The Element4 instance with the label, or null if not found.
*/
public static Element4 valueOfLabel(String label) {
return BY_LABEL.get(label);
}
/**
* Look up Element2 instances by the atomicNumber field. This implementation finds the
* atomicNUmber in the cache.
* @param number The atomicNumber to look up
* @return The Element4 instance with the label, or null if not found.
*/
public static Element4 valueOfAtomicNumber(int number) {
return BY_ATOMIC_NUMBER.get(number);
}
/**
* Look up Element2 instances by the atomicWeight field. This implementation finds the
* atomic weight in the cache.
* @param weight the atomic weight to look up
* @return The Element4 instance with the label, or null if not found.
*/
public static Element4 valueOfAtomicWeight(float weight) {
return BY_ATOMIC_WEIGHT.get(weight);
}
/**
* Override the toString() method to return the label instead of the declared name.
* @return
*/
@Override
public String toString() {
return this.label;
}
}
@@ -0,0 +1,5 @@
package com.baeldung.enums.values;
public interface Labeled {
String label();
}
@@ -0,0 +1,30 @@
package com.baeldung.finalize;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class CloseableResource implements AutoCloseable {
private BufferedReader reader;
public CloseableResource() {
InputStream input = this.getClass().getClassLoader().getResourceAsStream("file.txt");
reader = new BufferedReader(new InputStreamReader(input));
}
public String readFirstLine() throws IOException {
String firstLine = reader.readLine();
return firstLine;
}
@Override
public void close() {
try {
reader.close();
System.out.println("Closed BufferedReader in the close method");
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,30 @@
package com.baeldung.finalize;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Finalizable {
private BufferedReader reader;
public Finalizable() {
InputStream input = this.getClass().getClassLoader().getResourceAsStream("file.txt");
reader = new BufferedReader(new InputStreamReader(input));
}
public String readFirstLine() throws IOException {
String firstLine = reader.readLine();
return firstLine;
}
@Override
public void finalize() {
try {
reader.close();
System.out.println("Closed BufferedReader in the finalizer");
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,5 @@
package com.baeldung.interfaces;
public interface Box extends HasColor {
int getHeight();
}
@@ -0,0 +1,21 @@
package com.baeldung.interfaces;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class CommaSeparatedCustomers implements Customer.List {
private List<Customer> customers = new ArrayList<Customer>();
@Override
public void Add(Customer customer) {
customers.add(customer);
}
@Override
public String getCustomerNames() {
return customers.stream().map(customer -> customer.getName()).collect(Collectors.joining(","));
}
}
@@ -0,0 +1,19 @@
package com.baeldung.interfaces;
public class Customer {
public interface List {
void Add(Customer customer);
String getCustomerNames();
}
private String name;
public Customer(String name) {
this.name = name;
}
String getName() {
return name;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.interfaces;
public class Employee {
private double salary;
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
@@ -0,0 +1,17 @@
package com.baeldung.interfaces;
import java.util.Comparator;
public class EmployeeSalaryComparator implements Comparator<Employee> {
@Override
public int compare(Employee employeeA, Employee employeeB) {
if (employeeA.getSalary() < employeeB.getSalary()) {
return -1;
} else if (employeeA.getSalary() > employeeB.getSalary()) {
return 1;
} else {
return 0;
}
}
}
@@ -0,0 +1,4 @@
package com.baeldung.interfaces;
public interface HasColor {
}
@@ -0,0 +1,14 @@
package com.baeldung.interfaces.multiinheritance;
public class Car implements Fly,Transform {
@Override
public void fly() {
System.out.println("I can Fly!!");
}
@Override
public void transform() {
System.out.println("I can Transform!!");
}
}
@@ -0,0 +1,6 @@
package com.baeldung.interfaces.multiinheritance;
public interface Fly {
void fly();
}
@@ -0,0 +1,10 @@
package com.baeldung.interfaces.multiinheritance;
public interface Transform {
void transform();
default void printSpecs(){
System.out.println("Transform Specification");
}
}
@@ -0,0 +1,4 @@
package com.baeldung.interfaces.multiinheritance;
public abstract class Vehicle implements Transform {
}
@@ -0,0 +1,9 @@
package com.baeldung.interfaces.polymorphysim;
public class Circle implements Shape {
@Override
public String name() {
return "Circle";
}
}
@@ -0,0 +1,20 @@
package com.baeldung.interfaces.polymorphysim;
import java.util.ArrayList;
import java.util.List;
public class MainTestClass {
public static void main(String[] args) {
List<Shape> shapes = new ArrayList<>();
Shape circleShape = new Circle();
Shape squareShape = new Square();
shapes.add(circleShape);
shapes.add(squareShape);
for (Shape shape : shapes) {
System.out.println(shape.name());
}
}
}
@@ -0,0 +1,6 @@
package com.baeldung.interfaces.polymorphysim;
public interface Shape {
String name();
}
@@ -0,0 +1,9 @@
package com.baeldung.interfaces.polymorphysim;
public class Square implements Shape {
@Override
public String name() {
return "Square";
}
}
@@ -0,0 +1,10 @@
package com.baeldung.nativekeyword;
public class DateTimeUtils {
public native String getSystemTime();
static {
System.loadLibrary("nativedatetimeutils");
}
}
@@ -0,0 +1,11 @@
package com.baeldung.nativekeyword;
import com.baeldung.nativekeyword.DateTimeUtils;
public class NativeMainApp {
public static void main(String[] args) {
DateTimeUtils dateTimeUtils = new DateTimeUtils();
String input = dateTimeUtils.getSystemTime();
System.out.println("System time is : " + input);
}
}
@@ -0,0 +1,51 @@
package com.baeldung.objects;
public class Car {
private String type;
private String model;
private String color;
private int speed;
public Car(String type, String model, String color) {
this.type = type;
this.model = model;
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getSpeed() {
return speed;
}
public int increaseSpeed(int increment) {
if (increment > 0) {
this.speed += increment;
} else {
System.out.println("Increment can't be negative.");
}
return this.speed;
}
public int decreaseSpeed(int decrement) {
if (decrement > 0 && decrement <= this.speed) {
this.speed -= decrement;
} else {
System.out.println("Decrement can't be negative or greater than current speed.");
}
return this.speed;
}
@Override
public String toString() {
return "Car [type=" + type + ", model=" + model + ", color=" + color + ", speed=" + speed + "]";
}
}
@@ -0,0 +1,22 @@
package com.baeldung.packages;
import java.time.LocalDate;
import com.baeldung.packages.domain.TodoItem;
public class TodoApp {
public static void main(String[] args) {
TodoList todoList = new TodoList();
for (int i = 0; i < 3; i++) {
TodoItem item = new TodoItem();
item.setId(Long.valueOf((long)i));
item.setDescription("Todo item " + (i + 1));
item.setDueDate(LocalDate.now().plusDays((long)(i + 1)));
todoList.addTodoItem(item);
}
todoList.getTodoItems().forEach((TodoItem todoItem) -> System.out.println(todoItem.toString()));
}
}
@@ -0,0 +1,27 @@
package com.baeldung.packages;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.packages.domain.TodoItem;
public class TodoList {
private List<TodoItem> todoItems;
public void addTodoItem(TodoItem todoItem) {
if (todoItems == null) {
todoItems = new ArrayList<TodoItem>();
}
todoItems.add(todoItem);
}
public List<TodoItem> getTodoItems() {
return todoItems;
}
public void setTodoItems(List<TodoItem> todoItems) {
this.todoItems = todoItems;
}
}
@@ -0,0 +1,39 @@
package com.baeldung.packages.domain;
import java.time.LocalDate;
public class TodoItem {
private Long id;
private String description;
private LocalDate dueDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDate getDueDate() {
return dueDate;
}
public void setDueDate(LocalDate dueDate) {
this.dueDate = dueDate;
}
@Override
public String toString() {
return "TodoItem [id=" + id + ", description=" + description + ", dueDate=" + dueDate + "]";
}
}
@@ -0,0 +1,27 @@
package com.baeldung.parameterpassing;
public class NonPrimitives {
public static void main(String[] args) {
FooClass a = new FooClass(1);
FooClass b = new FooClass(1);
System.out.printf("Before Modification: a = %d and b = %d ", a.num, b.num);
modify(a, b);
System.out.printf("\nAfter Modification: a = %d and b = %d ", a.num, b.num);
}
public static void modify(FooClass a1, FooClass b1) {
a1.num++;
b1 = new FooClass(1);
b1.num++;
}
}
class FooClass {
public int num;
public FooClass(int num) {
this.num = num;
}
}
@@ -0,0 +1,17 @@
package com.baeldung.parameterpassing;
public class Primitives {
public static void main(String[] args) {
int x = 1;
int y = 2;
System.out.printf("Before Modification: x = %d and y = %d ", x, y);
modify(x, y);
System.out.printf("\nAfter Modification: x = %d and y = %d ", x, y);
}
public static void modify(int x1, int y1) {
x1 = 5;
y1 = 10;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.recursion;
public class BinaryNode {
int value;
BinaryNode left;
BinaryNode right;
public BinaryNode(int value){
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public BinaryNode getLeft() {
return left;
}
public void setLeft(BinaryNode left) {
this.left = left;
}
public BinaryNode getRight() {
return right;
}
public void setRight(BinaryNode right) {
this.right = right;
}
}
@@ -0,0 +1,64 @@
package com.baeldung.recursion;
public class RecursionExample {
public int sum(int n){
if (n >= 1){
return sum(n - 1) + n;
}
return n;
}
public int tailSum(int currentSum, int n){
if (n <= 1) {
return currentSum + n;
}
return tailSum(currentSum + n, n - 1);
}
public int iterativeSum(int n){
int sum = 0;
if(n < 0){
return -1;
}
for(int i=0; i<=n; i++){
sum += i;
}
return sum;
}
public int powerOf10(int n){
if (n == 0){
return 1;
}
return powerOf10(n-1)*10;
}
public int fibonacci(int n){
if (n <=1 ){
return n;
}
return fibonacci(n-1) + fibonacci(n-2);
}
public String toBinary(int n){
if (n <= 1 ){
return String.valueOf(n);
}
return toBinary(n / 2) + String.valueOf(n % 2);
}
public int calculateTreeHeight(BinaryNode root){
if (root!= null){
if (root.getLeft() != null || root.getRight() != null){
return 1 + max(calculateTreeHeight(root.left) , calculateTreeHeight(root.right));
}
}
return 0;
}
public int max(int a,int b){
return a>b ? a:b;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.scope;
public class BracketScopeExample {
public void mathOperationExample() {
Integer sum = 0;
{
Integer number = 2;
sum = sum + number;
}
// compiler error, number cannot be solved as a variable
// number++;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.scope;
public class ClassScopeExample {
Integer amount = 0;
public void exampleMethod() {
amount++;
}
public void anotherExampleMethod() {
Integer anotherAmount = amount + 4;
}
}
@@ -0,0 +1,18 @@
package com.baeldung.scope;
import java.util.Arrays;
import java.util.List;
public class LoopScopeExample {
List<String> listOfNames = Arrays.asList("Joe", "Susan", "Pattrick");
public void iterationOfNames() {
String allNames = "";
for (String name : listOfNames) {
allNames = allNames + " " + name;
}
// compiler error, name cannot be resolved to a variable
// String lastNameUsed = name;
}
}
@@ -0,0 +1,13 @@
package com.baeldung.scope;
public class MethodScopeExample {
public void methodA() {
Integer area = 2;
}
public void methodB() {
// compiler error, area cannot be resolved to a variable
// area = area + 2;
}
}
@@ -0,0 +1,12 @@
package com.baeldung.scope;
public class NestedScopesExample {
String title = "Baeldung";
public void printTitle() {
System.out.println(title);
String title = "John Doe";
System.out.println(title);
}
}
@@ -0,0 +1,23 @@
package com.baeldung.synthetic;
import java.util.Comparator;
/**
* Class which contains a synthetic bridge method.
*
* @author Donato Rimenti
*
*/
public class BridgeMethodDemo implements Comparator<Integer> {
/*
* (non-Javadoc)
*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Integer o1, Integer o2) {
return 0;
}
}
@@ -0,0 +1,34 @@
package com.baeldung.synthetic;
/**
* Wrapper for a class which contains a synthetic constructor.
*
* @author Donato Rimenti
*
*/
public class SyntheticConstructorDemo {
/**
* We need to instantiate the {@link NestedClass} using a private
* constructor from the enclosing instance in order to generate a synthetic
* constructor.
*/
private NestedClass nestedClass = new NestedClass();
/**
* Class which contains a synthetic constructor.
*
* @author Donato Rimenti
*
*/
class NestedClass {
/**
* In order to generate a synthetic constructor, this class must have a
* private constructor.
*/
private NestedClass() {
}
}
}
@@ -0,0 +1,22 @@
package com.baeldung.synthetic;
/**
* Wrapper for a class which contains a synthetic field reference to the outer
* class.
*
* @author Donato Rimenti
*
*/
public class SyntheticFieldDemo {
/**
* Class which contains a synthetic field reference to the outer class.
*
* @author Donato Rimenti
*
*/
class NestedClass {
}
}
@@ -0,0 +1,48 @@
package com.baeldung.synthetic;
/**
* Wrapper for a class which contains two synthetic methods accessors to a
* private field.
*
* @author Donato Rimenti
*
*/
public class SyntheticMethodDemo {
/**
* Class which contains two synthetic methods accessors to a private field.
*
* @author Donato Rimenti
*
*/
class NestedClass {
/**
* Field for which will be generated synthetic methods accessors. It's
* important that this field is private for this purpose.
*/
private String nestedField;
}
/**
* Gets the private nested field. We need to read the nested field in order
* to generate the synthetic getter.
*
* @return the {@link NestedClass#nestedField}
*/
public String getNestedField() {
return new NestedClass().nestedField;
}
/**
* Sets the private nested field. We need to write the nested field in order
* to generate the synthetic setter.
*
* @param nestedField
* the {@link NestedClass#nestedField}
*/
public void setNestedField(String nestedField) {
new NestedClass().nestedField = nestedField;
}
}
@@ -0,0 +1 @@
baeldung.com
@@ -0,0 +1,95 @@
package com.baeldung.binding;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.LoggerFactory;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
/**
*https://gist.github.com/bloodredsun/a041de13e57bf3c6c040
*/
@RunWith(MockitoJUnitRunner.class)
public class AnimalActivityUnitTest {
@Mock
private Appender mockAppender;
@Captor
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;
@Before
public void setup() {
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logger.addAppender(mockAppender);
}
@After
public void teardown() {
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logger.detachAppender(mockAppender);
}
@Test
public void givenAnimalReference__whenRefersAnimalObject_shouldCallFunctionWithAnimalParam() {
Animal animal = new Animal();
AnimalActivity.sleep(animal);
verify(mockAppender).doAppend(captorLoggingEvent.capture());
final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
assertThat(loggingEvent.getLevel(), is(Level.INFO));
assertThat(loggingEvent.getFormattedMessage(),
is("Animal is sleeping"));
}
@Test
public void givenDogReference__whenRefersCatObject_shouldCallFunctionWithAnimalParam() {
Cat cat = new Cat();
AnimalActivity.sleep(cat);
verify(mockAppender).doAppend(captorLoggingEvent.capture());
final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
assertThat(loggingEvent.getLevel(), is(Level.INFO));
assertThat(loggingEvent.getFormattedMessage(),
is("Cat is sleeping"));
}
@Test
public void givenAnimaReference__whenRefersDogObject_shouldCallFunctionWithAnimalParam() {
Animal cat = new Cat();
AnimalActivity.sleep(cat);
verify(mockAppender).doAppend(captorLoggingEvent.capture());
final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
assertThat(loggingEvent.getLevel(), is(Level.INFO));
assertThat(loggingEvent.getFormattedMessage(),
is("Animal is sleeping"));
}
}
@@ -0,0 +1,87 @@
package com.baeldung.binding;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.LoggerFactory;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.List;
/**
* Created by madhumita.g on 01-08-2018.
*/
@RunWith(MockitoJUnitRunner.class)
public class AnimalUnitTest {
@Mock
private Appender mockAppender;
@Captor
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;
@Before
public void setup() {
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logger.addAppender(mockAppender);
}
@After
public void teardown() {
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logger.detachAppender(mockAppender);
}
@Test
public void whenCalledWithoutParameters_shouldCallFunctionMakeNoiseWithoutParameters() {
Animal animal = new Animal();
animal.makeNoise();
verify(mockAppender).doAppend(captorLoggingEvent.capture());
final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
assertThat(loggingEvent.getLevel(), is(Level.INFO));
assertThat(loggingEvent.getFormattedMessage(),
is("generic animal noise"));
}
@Test
public void whenCalledWithParameters_shouldCallFunctionMakeNoiseWithParameters() {
Animal animal = new Animal();
int testValue = 3;
animal.makeNoise(testValue);
verify(mockAppender,times(3)).doAppend(captorLoggingEvent.capture());
final List<LoggingEvent> loggingEvents = captorLoggingEvent.getAllValues();
for(LoggingEvent loggingEvent : loggingEvents)
{
assertThat(loggingEvent.getLevel(), is(Level.INFO));
assertThat(loggingEvent.getFormattedMessage(),
is("generic animal noise countdown "+testValue));
testValue--;
}
}
}
@@ -0,0 +1,62 @@
package com.baeldung.binding;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.Appender;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.LoggerFactory;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
/**
* Created by madhumita.g on 01-08-2018.
*/
@RunWith(MockitoJUnitRunner.class)
public class CatUnitTest {
@Mock
private Appender mockAppender;
@Captor
private ArgumentCaptor<LoggingEvent> captorLoggingEvent;
@Before
public void setup() {
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logger.addAppender(mockAppender);
}
@After
public void teardown() {
final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logger.detachAppender(mockAppender);
}
@Test
public void makeNoiseTest() {
Cat cat = new Cat();
cat.makeNoise();
verify(mockAppender).doAppend(captorLoggingEvent.capture());
final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
assertThat(loggingEvent.getLevel(), is(Level.INFO));
assertThat(loggingEvent.getFormattedMessage(),
is("meow"));
}
}
@@ -0,0 +1,156 @@
package com.baeldung.className;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class RetrievingClassNameUnitTest {
// Retrieving Simple Name
@Test
public void givenRetrievingClassName_whenGetSimpleName_thenRetrievingClassName() {
assertEquals("RetrievingClassName", RetrievingClassName.class.getSimpleName());
}
@Test
public void givenPrimitiveInt_whenGetSimpleName_thenInt() {
assertEquals("int", int.class.getSimpleName());
}
@Test
public void givenRetrievingClassNameArray_whenGetSimpleName_thenRetrievingClassNameWithBrackets() {
assertEquals("RetrievingClassName[]", RetrievingClassName[].class.getSimpleName());
assertEquals("RetrievingClassName[][]", RetrievingClassName[][].class.getSimpleName());
}
@Test
public void givenAnonymousClass_whenGetSimpleName_thenEmptyString() {
assertEquals("", new RetrievingClassName() {}.getClass().getSimpleName());
}
// Retrieving Other Names
// - Primitive Types
@Test
public void givenPrimitiveInt_whenGetName_thenInt() {
assertEquals("int", int.class.getName());
}
@Test
public void givenPrimitiveInt_whenGetTypeName_thenInt() {
assertEquals("int", int.class.getTypeName());
}
@Test
public void givenPrimitiveInt_whenGetCanonicalName_thenInt() {
assertEquals("int", int.class.getCanonicalName());
}
// - Object Types
@Test
public void givenRetrievingClassName_whenGetName_thenCanonicalName() {
assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getName());
}
@Test
public void givenRetrievingClassName_whenGetTypeName_thenCanonicalName() {
assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getTypeName());
}
@Test
public void givenRetrievingClassName_whenGetCanonicalName_thenCanonicalName() {
assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getCanonicalName());
}
// - Inner Classes
@Test
public void givenRetrievingClassNameInnerClass_whenGetName_thenCanonicalNameWithDollarSeparator() {
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass", RetrievingClassName.InnerClass.class.getName());
}
@Test
public void givenRetrievingClassNameInnerClass_whenGetTypeName_thenCanonicalNameWithDollarSeparator() {
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass", RetrievingClassName.InnerClass.class.getTypeName());
}
@Test
public void givenRetrievingClassNameInnerClass_whenGetCanonicalName_thenCanonicalName() {
assertEquals("com.baeldung.className.RetrievingClassName.InnerClass", RetrievingClassName.InnerClass.class.getCanonicalName());
}
// - Anonymous Classes
@Test
public void givenAnonymousClass_whenGetName_thenCallingClassCanonicalNameWithDollarSeparatorAndCountNumber() {
// These are the second and third appearences of an anonymous class in RetrievingClassNameUnitTest, hence $2 and $3 expectations
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$2", new RetrievingClassName() {}.getClass().getName());
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$3", new RetrievingClassName() {}.getClass().getName());
}
@Test
public void givenAnonymousClass_whenGetTypeName_thenCallingClassCanonicalNameWithDollarSeparatorAndCountNumber() {
// These are the fourth and fifth appearences of an anonymous class in RetrievingClassNameUnitTest, hence $4 and $5 expectations
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$4", new RetrievingClassName() {}.getClass().getTypeName());
assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$5", new RetrievingClassName() {}.getClass().getTypeName());
}
@Test
public void givenAnonymousClass_whenGetCanonicalName_thenNull() {
assertNull(new RetrievingClassName() {}.getClass().getCanonicalName());
}
// - Arrays
@Test
public void givenPrimitiveIntArray_whenGetName_thenOpeningBracketsAndPrimitiveIntLetter() {
assertEquals("[I", int[].class.getName());
assertEquals("[[I", int[][].class.getName());
}
@Test
public void givenRetrievingClassNameArray_whenGetName_thenOpeningBracketsLetterLAndRetrievingClassNameGetName() {
assertEquals("[Lcom.baeldung.className.RetrievingClassName;", RetrievingClassName[].class.getName());
assertEquals("[[Lcom.baeldung.className.RetrievingClassName;", RetrievingClassName[][].class.getName());
}
@Test
public void givenRetrievingClassNameInnerClassArray_whenGetName_thenOpeningBracketsLetterLAndRetrievingClassNameInnerClassGetName() {
assertEquals("[Lcom.baeldung.className.RetrievingClassName$InnerClass;", RetrievingClassName.InnerClass[].class.getName());
assertEquals("[[Lcom.baeldung.className.RetrievingClassName$InnerClass;", RetrievingClassName.InnerClass[][].class.getName());
}
@Test
public void givenPrimitiveIntArray_whenGetTypeName_thenPrimitiveIntGetTypeNameWithBrackets() {
assertEquals("int[]", int[].class.getTypeName());
assertEquals("int[][]", int[][].class.getTypeName());
}
@Test
public void givenRetrievingClassNameArray_whenGetTypeName_thenRetrievingClassNameGetTypeNameWithBrackets() {
assertEquals("com.baeldung.className.RetrievingClassName[]", RetrievingClassName[].class.getTypeName());
assertEquals("com.baeldung.className.RetrievingClassName[][]", RetrievingClassName[][].class.getTypeName());
}
@Test
public void givenRetrievingClassNameInnerClassArray_whenGetTypeName_thenRetrievingClassNameInnerClassGetTypeNameWithBrackets() {
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass[]", RetrievingClassName.InnerClass[].class.getTypeName());
assertEquals("com.baeldung.className.RetrievingClassName$InnerClass[][]", RetrievingClassName.InnerClass[][].class.getTypeName());
}
@Test
public void givenPrimitiveIntArray_whenGetCanonicalName_thenPrimitiveIntGetCanonicalNameWithBrackets() {
assertEquals("int[]", int[].class.getCanonicalName());
assertEquals("int[][]", int[][].class.getCanonicalName());
}
@Test
public void givenRetrievingClassNameArray_whenGetCanonicalName_thenRetrievingClassNameGetCanonicalNameWithBrackets() {
assertEquals("com.baeldung.className.RetrievingClassName[]", RetrievingClassName[].class.getCanonicalName());
assertEquals("com.baeldung.className.RetrievingClassName[][]", RetrievingClassName[][].class.getCanonicalName());
}
@Test
public void givenRetrievingClassNameInnerClassArray_whenGetCanonicalName_thenRetrievingClassNameInnerClassGetCanonicalNameWithBrackets() {
assertEquals("com.baeldung.className.RetrievingClassName.InnerClass[]", RetrievingClassName.InnerClass[].class.getCanonicalName());
assertEquals("com.baeldung.className.RetrievingClassName.InnerClass[][]", RetrievingClassName.InnerClass[][].class.getCanonicalName());
}
}
@@ -0,0 +1,29 @@
package com.baeldung.comparable;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
public class ComparableUnitTest {
@Test
public void whenUsingComparable_thenSortedList() {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 20);
Player player2 = new Player(67, "Roger", 22);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
Collections.sort(footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
}
}
@@ -0,0 +1,47 @@
package com.baeldung.comparator;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class ComparatorUnitTest {
List<Player> footballTeam;
@Before
public void setUp() {
footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 20);
Player player2 = new Player(67, "Roger", 22);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
}
@Test
public void whenUsingRankingComparator_thenSortedList() {
PlayerRankingComparator playerComparator = new PlayerRankingComparator();
Collections.sort(footballTeam, playerComparator);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
}
@Test
public void whenUsingAgeComparator_thenSortedList() {
PlayerAgeComparator playerComparator = new PlayerAgeComparator();
Collections.sort(footballTeam, playerComparator);
assertEquals(footballTeam.get(0)
.getName(), "John");
assertEquals(footballTeam.get(2)
.getRanking(), 45);
}
}
@@ -0,0 +1,68 @@
package com.baeldung.comparator;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
public class Java8ComparatorUnitTest {
List<Player> footballTeam;
@Before
public void setUp() {
footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 22);
Player player2 = new Player(67, "Roger", 20);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
}
@Test
public void whenComparing_UsingLambda_thenSorted() {
System.out.println("************** Java 8 Comaparator **************");
Comparator<Player> byRanking = (Player player1, Player player2) -> player1.getRanking() - player2.getRanking();
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byRanking);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
}
@Test
public void whenComparing_UsingComparatorComparing_thenSorted() {
System.out.println("********* Comaparator.comparing method *********");
System.out.println("********* byRanking *********");
Comparator<Player> byRanking = Comparator.comparing(Player::getRanking);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byRanking);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Steven");
assertEquals(footballTeam.get(2)
.getRanking(), 67);
System.out.println("********* byAge *********");
Comparator<Player> byAge = Comparator.comparing(Player::getAge);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam, byAge);
System.out.println("After Sorting : " + footballTeam);
assertEquals(footballTeam.get(0)
.getName(), "Roger");
assertEquals(footballTeam.get(2)
.getRanking(), 45);
}
}
@@ -0,0 +1,111 @@
package com.baeldung.compoundoperators;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CompoundOperatorsUnitTest {
@Test
public void whenAssignmentOperatorIsUsed_thenValueIsAssigned() {
int x = 5;
assertEquals(5, x);
}
@Test
public void whenCompoundAssignmentUsed_thenSameAsSimpleAssignment() {
int a = 3, b = 3, c = -2;
a = a * c; // Simple assignment operator
b *= c; // Compound assignment operator
assertEquals(a, b);
}
@Test
public void whenAssignmentOperatorIsUsed_thenValueIsReturned() {
long x = 1;
long y = (x+=2);
assertEquals(3, y);
assertEquals(y, x);
}
@Test
public void whenCompoundOperatorsAreUsed_thenOperationsArePerformedAndAssigned() {
//Simple assignment
int x = 5; //x is 5
//Incrementation
x += 5; //x is 10
assertEquals(10, x);
//Decrementation
x -= 2; //x is 8
assertEquals(8, x);
//Multiplication
x *= 2; //x is 16
assertEquals(16, x);
//Division
x /= 4; //x is 4
assertEquals(4, x);
//Modulus
x %= 3; //x is 1
assertEquals(1, x);
//Binary AND
x &= 4; //x is 0
assertEquals(0, x);
//Binary exclusive OR
x ^= 4; //x is 4
assertEquals(4, x);
//Binary inclusive OR
x |= 8; //x is 12
assertEquals(12, x);
//Binary Left Shift
x <<= 2; //x is 48
assertEquals(48, x);
//Binary Right Shift
x >>= 2; //x is 12
assertEquals(12, x);
//Shift right zero fill
x >>>= 1; //x is 6
assertEquals(6, x);
}
@Test(expected = NullPointerException.class)
public void whenArrayIsNull_thenThrowNullException() {
int[] numbers = null;
//Trying Incrementation
numbers[2] += 5;
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void whenArrayIndexNotCorrect_thenThrowArrayIndexException() {
int[] numbers = {0, 1};
//Trying Incrementation
numbers[2] += 5;
}
@Test
public void whenArrayIndexIsCorrect_thenPerformOperation() {
int[] numbers = {0, 1};
//Incrementation
numbers[1] += 5;
assertEquals(6, numbers[1]);
}
}
@@ -0,0 +1,48 @@
package com.baeldung.enums.values;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author chris
*/
public class Element1UnitTest {
public Element1UnitTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void whenAccessingToString_thenItShouldEqualName() {
for (Element1 e1 : Element1.values()) {
assertEquals(e1.name(), e1.toString());
}
}
@Test
public void whenCallingValueOf_thenReturnTheCorrectEnum() {
for (Element1 e1 : Element1.values()) {
assertSame(e1, Element1.valueOf(e1.name()));
}
}
}
@@ -0,0 +1,59 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.baeldung.enums.values;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author chris
*/
public class Element2UnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(Element2UnitTest.class);
public Element2UnitTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void whenLocatebyLabel_thenReturnCorrectValue() {
for (Element2 e2 : Element2.values()) {
assertSame(e2, Element2.valueOfLabel(e2.label));
}
}
/**
* Test of toString method, of class Element2.
*/
@Test
public void whenCallingToString_thenReturnLabel() {
for (Element2 e2 : Element2.values()) {
assertEquals(e2.label, e2.toString());
}
}
}
@@ -0,0 +1,57 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.baeldung.enums.values;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author chris
*/
public class Element3UnitTest {
public Element3UnitTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void whenLocatebyLabel_thenReturnCorrectValue() {
for (Element3 e3 : Element3.values()) {
assertSame(e3, Element3.valueOfLabel(e3.label));
}
}
/**
* Test of toString method, of class Element3.
*/
@Test
public void whenCallingToString_thenReturnLabel() {
for (Element3 e3 : Element3.values()) {
assertEquals(e3.label, e3.toString());
}
}
}
@@ -0,0 +1,71 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.baeldung.enums.values;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author chris
*/
public class Element4UnitTest {
public Element4UnitTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void whenLocatebyLabel_thenReturnCorrectValue() {
for (Element4 e4 : Element4.values()) {
assertSame(e4, Element4.valueOfLabel(e4.label));
}
}
@Test
public void whenLocatebyAtmNum_thenReturnCorrectValue() {
for (Element4 e4 : Element4.values()) {
assertSame(e4, Element4.valueOfAtomicNumber(e4.atomicNumber));
}
}
@Test
public void whenLocatebyAtmWt_thenReturnCorrectValue() {
for (Element4 e4 : Element4.values()) {
assertSame(e4, Element4.valueOfAtomicWeight(e4.atomicWeight));
}
}
/**
* Test of toString method, of class Element4.
*/
@Test
public void whenCallingToString_thenReturnLabel() {
for (Element4 e4 : Element4.values()) {
assertEquals(e4.label, e4.toString());
}
}
}
@@ -0,0 +1,23 @@
package com.baeldung.finalize;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
public class FinalizeUnitTest {
@Test
public void whenGC_thenFinalizerExecuted() throws IOException {
String firstLine = new Finalizable().readFirstLine();
Assert.assertEquals("baeldung.com", firstLine);
System.gc();
}
@Test
public void whenTryWResourcesExits_thenResourceClosed() throws IOException {
try (CloseableResource resource = new CloseableResource()) {
String firstLine = resource.readFirstLine();
Assert.assertEquals("baeldung.com", firstLine);
}
}
}
@@ -0,0 +1,18 @@
package com.baeldung.interfaces;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class InnerInterfaceUnitTest {
@Test
public void whenCustomerListJoined_thenReturnsJoinedNames() {
Customer.List customerList = new CommaSeparatedCustomers();
customerList.Add(new Customer("customer1"));
customerList.Add(new Customer("customer2"));
assertEquals("customer1,customer2", customerList.getCustomerNames());
}
}
@@ -0,0 +1,31 @@
package com.baeldung.java.enumiteration;
import java.util.stream.Stream;
public enum DaysOfWeekEnum {
SUNDAY("off"),
MONDAY("working"),
TUESDAY("working"),
WEDNESDAY("working"),
THURSDAY("working"),
FRIDAY("working"),
SATURDAY("off");
private String typeOfDay;
DaysOfWeekEnum(String typeOfDay) {
this.typeOfDay = typeOfDay;
}
public String getTypeOfDay() {
return typeOfDay;
}
public void setTypeOfDay(String typeOfDay) {
this.typeOfDay = typeOfDay;
}
public static Stream<DaysOfWeekEnum> stream() {
return Stream.of(DaysOfWeekEnum.values());
}
}
@@ -0,0 +1,43 @@
package com.baeldung.java.enumiteration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
public class EnumIterationExamples {
public static void main(String[] args) {
System.out.println("Enum iteration using EnumSet:");
EnumSet.allOf(DaysOfWeekEnum.class).forEach(day -> System.out.println(day));
System.out.println("Enum iteration using Stream:");
DaysOfWeekEnum.stream().filter(d -> d.getTypeOfDay().equals("off")).forEach(System.out::println);
System.out.println("Enum iteration using a for loop:");
for (DaysOfWeekEnum day : DaysOfWeekEnum.values()) {
System.out.println(day);
}
System.out.println("Enum iteration using Arrays.asList():");
Arrays.asList(DaysOfWeekEnum.values()).forEach(day -> System.out.println(day));
System.out.println("Add Enum values to ArrayList:");
List<DaysOfWeekEnum> days = new ArrayList<>();
days.add(DaysOfWeekEnum.FRIDAY);
days.add(DaysOfWeekEnum.SATURDAY);
days.add(DaysOfWeekEnum.SUNDAY);
for (DaysOfWeekEnum day : days) {
System.out.println(day);
}
System.out.println("Remove SATURDAY from the list:");
days.remove(DaysOfWeekEnum.SATURDAY);
if (!days.contains(DaysOfWeekEnum.SATURDAY)) {
System.out.println("Saturday is no longer in the list");
}
for (DaysOfWeekEnum day : days) {
System.out.println(day);
}
}
}
@@ -0,0 +1,27 @@
package com.baeldung.nativekeyword;
import static org.junit.Assert.assertNotNull;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
public class DateTimeUtilsManualTest {
private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(DateTimeUtilsManualTest.class);
@BeforeClass
public static void setUpClass() {
System.loadLibrary("msvcr100");
System.loadLibrary("libgcc_s_sjlj-1");
System.loadLibrary("libstdc++-6");
System.loadLibrary("nativedatetimeutils");
}
@Test
public void givenNativeLibsLoaded_thenNativeMethodIsAccessible() {
DateTimeUtils dateTimeUtils = new DateTimeUtils();
LOG.info("System time is : " + dateTimeUtils.getSystemTime());
assertNotNull(dateTimeUtils.getSystemTime());
}
}
@@ -0,0 +1,20 @@
package com.baeldung.nestedclass;
import org.junit.Test;
abstract class SimpleAbstractClass {
abstract void run();
}
public class AnonymousInner {
@Test
public void run() {
SimpleAbstractClass simpleAbstractClass = new SimpleAbstractClass() {
void run() {
System.out.println("Running Anonymous Class...");
}
};
simpleAbstractClass.run();
}
}
@@ -0,0 +1,21 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class Enclosing {
private static int x = 1;
public static class StaticNested {
private void run() {
System.out.println("x = " + x);
}
}
@Test
public void test() {
Enclosing.StaticNested nested = new Enclosing.StaticNested();
nested.run();
}
}
@@ -0,0 +1,22 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class NewEnclosing {
private void run() {
class Local {
void run() {
System.out.println("Welcome to Baeldung!");
}
}
Local local = new Local();
local.run();
}
@Test
public void test() {
NewEnclosing newEnclosing = new NewEnclosing();
newEnclosing.run();
}
}
@@ -0,0 +1,30 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class NewOuter {
int a = 1;
static int b = 2;
public class InnerClass {
int a = 3;
static final int b = 4;
public void run() {
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("NewOuter.this.a = " + NewOuter.this.a);
System.out.println("NewOuter.b = " + NewOuter.b);
System.out.println("NewOuter.this.b = " + NewOuter.this.b);
}
}
@Test
public void test() {
NewOuter outer = new NewOuter();
NewOuter.InnerClass inner = outer.new InnerClass();
inner.run();
}
}
@@ -0,0 +1,20 @@
package com.baeldung.nestedclass;
import org.junit.Test;
public class Outer {
public class Inner {
public void run() {
System.out.println("Calling test...");
}
}
@Test
public void test() {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.run();
}
}
@@ -0,0 +1,38 @@
package com.baeldung.objects;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class CarUnitTest {
private Car car;
@Before
public void setUp() throws Exception {
car = new Car("Ford", "Focus", "red");
}
@Test
public final void when_speedIncreased_then_verifySpeed() {
car.increaseSpeed(30);
assertEquals(30, car.getSpeed());
car.increaseSpeed(20);
assertEquals(50, car.getSpeed());
}
@Test
public final void when_speedDecreased_then_verifySpeed() {
car.increaseSpeed(50);
assertEquals(50, car.getSpeed());
car.decreaseSpeed(30);
assertEquals(20, car.getSpeed());
car.decreaseSpeed(20);
assertEquals(0, car.getSpeed());
}
}
@@ -0,0 +1,23 @@
package com.baeldung.packages;
import static org.junit.Assert.assertEquals;
import java.time.LocalDate;
import org.junit.Test;
import com.baeldung.packages.domain.TodoItem;
public class PackagesUnitTest {
@Test
public void whenTodoItemAdded_ThenSizeIncreases() {
TodoItem todoItem = new TodoItem();
todoItem.setId(1L);
todoItem.setDescription("Test the Todo List");
todoItem.setDueDate(LocalDate.now());
TodoList todoList = new TodoList();
todoList.addTodoItem(todoItem);
assertEquals(1, todoList.getTodoItems().size());
}
}
@@ -0,0 +1,61 @@
package com.baeldung.recursion;
import org.junit.Assert;
import org.junit.Test;
public class RecursionExampleUnitTest {
RecursionExample recursion = new RecursionExample();
@Test
public void testPowerOf10() {
int p0 = recursion.powerOf10(0);
int p1 = recursion.powerOf10(1);
int p4 = recursion.powerOf10(4);
Assert.assertEquals(1, p0);
Assert.assertEquals(10, p1);
Assert.assertEquals(10000, p4);
}
@Test
public void testFibonacci() {
int n0 = recursion.fibonacci(0);
int n1 = recursion.fibonacci(1);
int n7 = recursion.fibonacci(7);
Assert.assertEquals(0, n0);
Assert.assertEquals(1, n1);
Assert.assertEquals(13, n7);
}
@Test
public void testToBinary() {
String b0 = recursion.toBinary(0);
String b1 = recursion.toBinary(1);
String b10 = recursion.toBinary(10);
Assert.assertEquals("0", b0);
Assert.assertEquals("1", b1);
Assert.assertEquals("1010", b10);
}
@Test
public void testCalculateTreeHeight() {
BinaryNode root = new BinaryNode(1);
root.setLeft(new BinaryNode(1));
root.setRight(new BinaryNode(1));
root.getLeft().setLeft(new BinaryNode(1));
root.getLeft().getLeft().setRight(new BinaryNode(1));
root.getLeft().getLeft().getRight().setLeft(new BinaryNode(1));
root.getRight().setLeft(new BinaryNode(1));
root.getRight().getLeft().setRight(new BinaryNode(1));
int height = recursion.calculateTreeHeight(root);
Assert.assertEquals(4, height);
}
}
@@ -0,0 +1,99 @@
package com.baeldung.synthetic;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit test for {@link SyntheticFieldDemo}, {@link SyntheticMethodDemo},
* {@link SyntheticConstructorDemo} and {@link BridgeMethodDemo} classes.
*
* @author Donato Rimenti
*
*/
public class SyntheticUnitTest {
/**
* Tests that the {@link SyntheticMethodDemo.NestedClass} contains two synthetic
* methods.
*/
@Test
public void givenSyntheticMethod_whenIsSinthetic_thenTrue() {
// Checks that the nested class contains exactly two synthetic methods.
Method[] methods = SyntheticMethodDemo.NestedClass.class.getDeclaredMethods();
Assert.assertEquals("This class should contain only two methods", 2, methods.length);
for (Method m : methods) {
System.out.println("Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic());
Assert.assertTrue("All the methods of this class should be synthetic", m.isSynthetic());
}
}
/**
* Tests that {@link SyntheticConstructorDemo.NestedClass} contains a synthetic
* constructor.
*/
@Test
public void givenSyntheticConstructor_whenIsSinthetic_thenTrue() {
// Checks that the nested class contains exactly a synthetic
// constructor.
int syntheticConstructors = 0;
Constructor<?>[] constructors = SyntheticConstructorDemo.NestedClass.class.getDeclaredConstructors();
Assert.assertEquals("This class should contain only two constructors", 2, constructors.length);
for (Constructor<?> c : constructors) {
System.out.println("Constructor: " + c.getName() + ", isSynthetic: " + c.isSynthetic());
// Counts the synthetic constructors.
if (c.isSynthetic()) {
syntheticConstructors++;
}
}
// Checks that there's exactly one synthetic constructor.
Assert.assertEquals(1, syntheticConstructors);
}
/**
* Tests that {@link SyntheticFieldDemo.NestedClass} contains a synthetic field.
*/
@Test
public void givenSyntheticField_whenIsSinthetic_thenTrue() {
// This class should contain exactly one synthetic field.
Field[] fields = SyntheticFieldDemo.NestedClass.class.getDeclaredFields();
Assert.assertEquals("This class should contain only one field", 1, fields.length);
for (Field f : fields) {
System.out.println("Field: " + f.getName() + ", isSynthetic: " + f.isSynthetic());
Assert.assertTrue("All the fields of this class should be synthetic", f.isSynthetic());
}
}
/**
* Tests that {@link BridgeMethodDemo} contains a synthetic bridge method.
*/
@Test
public void givenBridgeMethod_whenIsBridge_thenTrue() {
// This class should contain exactly one synthetic bridge method.
int syntheticMethods = 0;
Method[] methods = BridgeMethodDemo.class.getDeclaredMethods();
for (Method m : methods) {
System.out.println(
"Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic() + ", isBridge: " + m.isBridge());
// Counts the synthetic methods and checks that they are also bridge
// methods.
if (m.isSynthetic()) {
syntheticMethods++;
Assert.assertTrue("The synthetic method in this class should also be a bridge method", m.isBridge());
}
}
// Checks that there's exactly one synthetic bridge method.
Assert.assertEquals("There should be exactly 1 synthetic bridge method in this class", 1, syntheticMethods);
}
}