This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
@@ -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,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,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,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,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,17 @@
package com.baeldung.system;
import java.awt.event.WindowEvent;
/**
* Note: This class is not meant for unit-testing since it uses system
* features at low level and that it uses 'System' gc() which suggests
* JVM for garbage collection. But the usage below demonstrates how the
* method can be used.
*/
public class ChatWindow {
public void windowStateChanged(WindowEvent event) {
if (event.getNewState() == WindowEvent.WINDOW_DEACTIVATED ) {
System.gc(); // if it ends up running, great!
}
}
}
@@ -0,0 +1,16 @@
package com.baeldung.system;
import java.util.Date;
public class DateTimeService {
// One hour from now
public long nowPlusOneHour() {
return System.currentTimeMillis() + 3600 * 1000L;
}
// Human-readable format
public String nowPrettyPrinted() {
return new Date(System.currentTimeMillis()).toString();
}
}
@@ -0,0 +1,7 @@
package com.baeldung.system;
public class EnvironmentVariables {
public String getPath() {
return System.getenv("PATH");
}
}
@@ -0,0 +1,18 @@
package com.baeldung.system;
/**
* Note: This class is not meant for unit-testing since it uses system
* features at low level and that it uses 'System' standard error stream
* methods to show output on screen. Also unit-tests in CI environments
* don't have console output for user to see messages. But the usage below
* demonstrates how the methods can be used.
*/
public class SystemErrDemo {
public static void main(String[] args) {
// Print without 'hitting' return
System.err.print("some inline error message");
// Print and then 'hit' return
System.err.println("an error message having new line at the end");
}
}
@@ -0,0 +1,24 @@
package com.baeldung.system;
/**
* Note: This class is not meant for unit-testing since it uses system
* features at low level and that it uses 'System' exit() which will
* exit the JVM. Also unit-tests in CI environments are not meant to
* exit unit tests like that. But the usage below demonstrates how the
* method can be used.
*/
public class SystemExitDemo {
public static void main(String[] args) {
boolean error = false;
// do something and set error value
if (error) {
System.exit(1); // error case exit
} else {
System.exit(0); // normal case exit
}
// Will not do anything after exit()
}
}
@@ -0,0 +1,25 @@
package com.baeldung.system;
import java.io.FileNotFoundException;
import java.io.PrintStream;
/**
* Note: This class is not meant for unit-testing since it uses system
* features at low level and that it uses 'System' standard output stream
* methods to show output on screen. Also unit-tests in CI environments
* don't have console output for user to see messages. But the usage below
* demonstrates how the methods can be used.
*/
public class SystemOutDemo {
public static void main(String[] args) throws FileNotFoundException {
// Print without 'hitting' return
System.out.print("some inline message");
// Print and then 'hit' return
System.out.println("a message having new line at the end");
// Changes output stream to send messages to file.
System.setOut(new PrintStream("file.txt"));
}
}
@@ -0,0 +1,35 @@
package com.baeldung.system;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Note: This class is not meant for unit-testing since it uses system
* features at low level and that it uses 'System' standard input stream
* methods to read text from user. Also unit-tests in CI environments
* don't have console input for user to type in text. But the usage below
* demonstrates how the methods can be used.
*/
public class UserCredentials {
public String readUsername(int length) throws IOException {
byte[] name = new byte[length];
System.in.read(name, 0, length); // by default, from the console
return new String(name);
}
public String readUsername() throws IOException {
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
return reader.readLine();
}
public String readUsernameWithPrompt() {
Console console = System.console();
return console == null ? null : // Console not available
console.readLine("%s", "Enter your name: ");
}
}
@@ -0,0 +1 @@
baeldung.com
@@ -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,31 @@
package com.baeldung.enums.iteration;
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.enums.iteration;
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,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,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);
}
}
@@ -0,0 +1,15 @@
package com.baeldung.system;
import org.junit.Assert;
import org.junit.Test;
public class DateTimeServiceUnitTest {
@Test
public void givenClass_whenCalledMethods_thenNotNullInResult() {
DateTimeService dateTimeService = new DateTimeService();
Assert.assertNotNull(dateTimeService.nowPlusOneHour());
Assert.assertNotNull(dateTimeService.nowPrettyPrinted());
}
}
@@ -0,0 +1,14 @@
package com.baeldung.system;
import org.junit.Assert;
import org.junit.Test;
public class EnvironmentVariablesUnitTest {
@Test
public void givenEnvVars_whenReadPath_thenGetValueinResult() {
EnvironmentVariables environmentVariables = new EnvironmentVariables();
Assert.assertNotNull(environmentVariables.getPath());
}
}
@@ -0,0 +1,27 @@
package com.baeldung.system;
import org.junit.Assert;
import org.junit.Test;
public class SystemArrayCopyUnitTest {
@Test
public void givenTwoArraysAB_whenUseArrayCopy_thenArrayCopiedFromAToBInResult() {
int[] a = {34, 22, 44, 2, 55, 3};
int[] b = new int[a.length];
// copy all elements from a to b
System.arraycopy(a, 0, b, 0, a.length);
Assert.assertArrayEquals(a, b);
}
@Test
public void givenTwoArraysAB_whenUseArrayCopyPosition_thenArrayCopiedFromAToBInResult() {
int[] a = {34, 22, 44, 2, 55, 3};
int[] b = new int[a.length];
// copy 2 elements from a, starting at a[1] to b, starting at b[3]
System.arraycopy(a, 1, b, 3, 2);
Assert.assertArrayEquals(new int[] {0, 0, 0, 22, 44, 0}, b);
}
}
@@ -0,0 +1,16 @@
package com.baeldung.system;
import org.junit.Assert;
import org.junit.Test;
public class SystemNanoUnitTest {
@Test
public void givenSystem_whenCalledNanoTime_thenGivesTimeinResult() {
long startTime = System.nanoTime();
// do something that takes time
long endTime = System.nanoTime();
Assert.assertTrue(endTime - startTime < 10000);
}
}
@@ -0,0 +1,56 @@
package com.baeldung.system;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Properties;
public class SystemPropertiesUnitTest {
@Test
public void givenSystem_whenCalledGetProperty_thenReturnPropertyinResult() {
Assert.assertNotNull(System.getProperty("java.vm.vendor"));
}
@Test
public void givenSystem_whenCalledSetProperty_thenSetPropertyasResult() {
// set a particular property
System.setProperty("abckey", "abcvaluefoo");
Assert.assertEquals("abcvaluefoo", System.getProperty("abckey"));
}
@Test
public void givenSystem_whenCalledClearProperty_thenDeletePropertyasResult() {
// Delete a property
System.clearProperty("abckey");
Assert.assertNull(System.getProperty("abckey"));
}
@Test
public void givenSystem_whenCalledGetPropertyDefaultValue_thenReturnPropertyinResult() {
System.clearProperty("dbHost");
String myKey = System.getProperty("dbHost", "db.host.com");
Assert.assertEquals("db.host.com", myKey);
}
@Test
public void givenSystem_whenCalledGetProperties_thenReturnPropertiesinResult() {
Properties properties = System.getProperties();
Assert.assertNotNull(properties);
}
@Test
@Ignore
public void givenSystem_whenCalledClearProperties_thenDeleteAllPropertiesasResult() {
// Clears all system properties. Use with care!
System.getProperties().clear();
Assert.assertTrue(System.getProperties().isEmpty());
}
}