[BAEL-9555] - Created a core-java-modules folder

This commit is contained in:
amit2103
2019-05-05 17:22:09 +05:30
parent 8b63b0d90a
commit 3bae5e5334
1480 changed files with 25600 additions and 5594 deletions

View File

@@ -0,0 +1,139 @@
package com.baeldung.breakcontinue;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author Santosh
*
*/
public class BreakContinue {
public static int unlabeledBreak() {
String searchName = "Wilson";
int counter = 0;
List<String> names = Arrays.asList("John", "Peter", "Robert", "Wilson", "Anthony", "Donald", "Richard");
for (String name : names) {
counter++;
if (name.equalsIgnoreCase(searchName)) {
break;
}
}
return counter;
}
public static int unlabeledBreakNestedLoops() {
String searchName = "Wilson";
int counter = 0;
Map<String, List<String>> nameMap = new HashMap<>();
nameMap.put("Grade1", Arrays.asList("John", "Peter", "Robert", "Wilson"));
nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Richard", "Arnold"));
nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Stephen", "Ryan"));
Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet()
.iterator();
Entry<String, List<String>> entry = null;
List<String> names = null;
while (iterator.hasNext()) {
entry = iterator.next();
names = entry.getValue();
for (String name : names) {
if (name.equalsIgnoreCase(searchName)) {
counter++;
break;
}
}
}
return counter;
}
public static int labeledBreak() {
String searchName = "Wilson";
int counter = 0;
Map<String, List<String>> nameMap = new HashMap<>();
nameMap.put("Grade1", Arrays.asList("John", "Peter", "Robert", "Wilson"));
nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Richard", "Arnold"));
nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Stephen", "Ryan"));
Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet()
.iterator();
Entry<String, List<String>> entry = null;
List<String> names = null;
compare:
while (iterator.hasNext()) {
entry = iterator.next();
names = entry.getValue();
for (String name : names) {
if (name.equalsIgnoreCase(searchName)) {
counter++;
break compare;
}
}
}
return counter;
}
public static int unlabeledContinue() {
String searchName = "Wilson";
int counter = 0;
Map<String, List<String>> nameMap = new HashMap<>();
nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson"));
nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold"));
nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan"));
Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet()
.iterator();
Entry<String, List<String>> entry = null;
List<String> names = null;
while (iterator.hasNext()) {
entry = iterator.next();
names = entry.getValue();
for (String name : names) {
if (!name.equalsIgnoreCase(searchName)) {
continue;
}
counter++;
}
}
return counter;
}
public static int labeledContinue() {
String searchName = "Wilson";
int counter = 0;
Map<String, List<String>> nameMap = new HashMap<>();
nameMap.put("Grade1", Arrays.asList("John", "Wilson", "Robert", "Wilson"));
nameMap.put("Grade2", Arrays.asList("Anthony", "Donald", "Wilson", "Arnold"));
nameMap.put("Grade3", Arrays.asList("Wilson", "Michael", "Wilson", "Ryan"));
Iterator<Entry<String, List<String>>> iterator = nameMap.entrySet()
.iterator();
Entry<String, List<String>> entry = null;
List<String> names = null;
compare:
while (iterator.hasNext()) {
entry = iterator.next();
names = entry.getValue();
for (String name : names) {
if (name.equalsIgnoreCase(searchName)) {
counter++;
continue compare;
}
}
}
return counter;
}
}

View File

@@ -0,0 +1,88 @@
package com.baeldung.enums;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.List;
import java.util.stream.Collectors;
public class Pizza {
private static EnumSet<PizzaStatusEnum> deliveredPizzaStatuses = EnumSet.of(PizzaStatusEnum.DELIVERED);
private PizzaStatusEnum status;
public enum PizzaStatusEnum {
ORDERED(5) {
@Override
public boolean isOrdered() {
return true;
}
},
READY(2) {
@Override
public boolean isReady() {
return true;
}
},
DELIVERED(0) {
@Override
public boolean isDelivered() {
return true;
}
};
private int timeToDelivery;
public boolean isOrdered() {
return false;
}
public boolean isReady() {
return false;
}
public boolean isDelivered() {
return false;
}
public int getTimeToDelivery() {
return timeToDelivery;
}
PizzaStatusEnum(int timeToDelivery) {
this.timeToDelivery = timeToDelivery;
}
}
public PizzaStatusEnum getStatus() {
return status;
}
public void setStatus(PizzaStatusEnum status) {
this.status = status;
}
public boolean isDeliverable() {
return this.status.isReady();
}
public void printTimeToDeliver() {
System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
}
public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());
}
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
return pzList.stream().collect(Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
}
public void deliver() {
if (isDeliverable()) {
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
this.setStatus(PizzaStatusEnum.DELIVERED);
}
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.enums;
public enum PizzaDeliveryStrategy {
EXPRESS {
@Override
public void deliver(Pizza pz) {
System.out.println("Pizza will be delivered in express mode");
}
},
NORMAL {
@Override
public void deliver(Pizza pz) {
System.out.println("Pizza will be delivered in normal mode");
}
};
public abstract void deliver(Pizza pz);
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.enums;
public enum PizzaDeliverySystemConfiguration {
INSTANCE;
PizzaDeliverySystemConfiguration() {
// Do the configuration initialization which
// involves overriding defaults like delivery strategy
}
private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL;
public static PizzaDeliverySystemConfiguration getInstance() {
return INSTANCE;
}
public PizzaDeliveryStrategy getDeliveryStrategy() {
return deliveryStrategy;
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.generics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Building {
private static final Logger LOGGER = LoggerFactory.getLogger(Building.class);
public void paint() {
LOGGER.info("Painting Building");
}
}

View File

@@ -0,0 +1,38 @@
package com.baeldung.generics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Generics {
// definition of a generic method
public static <T> List<T> fromArrayToList(T[] a) {
return Arrays.stream(a).collect(Collectors.toList());
}
// definition of a generic method
public static <T, G> List<G> fromArrayToList(T[] a, Function<T, G> mapperFunction) {
return Arrays.stream(a).map(mapperFunction).collect(Collectors.toList());
}
// example of a generic method that has Number as an upper bound for T
public static <T extends Number> List<T> fromArrayToListWithUpperBound(T[] a) {
return Arrays.stream(a).collect(Collectors.toList());
}
// example of a generic method with a wild card, this method can be used
// with a list of any subtype of Building
public static void paintAllBuildings(List<? extends Building> buildings) {
buildings.forEach(Building::paint);
}
public static List<Integer> createList(int a) {
List<Integer> list = new ArrayList<>();
list.add(a);
return list;
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.generics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class House extends Building {
private static final Logger LOGGER = LoggerFactory.getLogger(House.class);
public void paint() {
LOGGER.info("Painting House");
}
}

View File

@@ -0,0 +1,53 @@
package com.baeldung.initializationguide;
import java.io.Serializable;
public class User implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
static String forum;
private String name;
private int id;
{
id = 0;
System.out.println("Instance Initializer");
}
static {
forum = "Java";
System.out.println("Static Initializer");
}
public User(String name, int id) {
super();
this.name = name;
this.id = id;
}
public User() {
System.out.println("Constructor");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return this;
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.keyword;
public class Circle extends Round implements Shape {
}

View File

@@ -0,0 +1,4 @@
package com.baeldung.keyword;
public class Ring extends Round {
}

View File

@@ -0,0 +1,4 @@
package com.baeldung.keyword;
public class Round {
}

View File

@@ -0,0 +1,4 @@
package com.baeldung.keyword;
public interface Shape {
}

View File

@@ -0,0 +1,4 @@
package com.baeldung.keyword;
public class Triangle implements Shape {
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.loops;
public class InfiniteLoops {
public void infiniteLoopUsingWhile() {
while (true) {
System.out.println("Infinite loop using while");
}
}
public void infiniteLoopUsingFor() {
for (;;) {
System.out.println("Infinite loop using for");
}
}
public void infiniteLoopUsingDoWhile() {
do {
System.out.println("Infinite loop using do-while");
} while (true);
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.loops;
public class LoopsInJava {
public int[] simple_for_loop() {
int[] arr = new int[5];
for (int i = 0; i < 5; i++) {
arr[i] = i;
System.out.println("Simple for loop: i - " + i);
}
return arr;
}
public int[] enhanced_for_each_loop() {
int[] intArr = { 0, 1, 2, 3, 4 };
int[] arr = new int[5];
for (int num : intArr) {
arr[num] = num;
System.out.println("Enhanced for-each loop: i - " + num);
}
return arr;
}
public int[] while_loop() {
int i = 0;
int[] arr = new int[5];
while (i < 5) {
arr[i] = i;
System.out.println("While loop: i - " + i++);
}
return arr;
}
public int[] do_while_loop() {
int i = 0;
int[] arr = new int[5];
do {
arr[i] = i;
System.out.println("Do-While loop: i - " + i++);
} while (i < 5);
return arr;
}
}

View File

@@ -0,0 +1,70 @@
package com.baeldung.switchstatement;
public class SwitchStatement {
public String exampleOfIF(String animal) {
String result;
if (animal.equals("DOG") || animal.equals("CAT")) {
result = "domestic animal";
} else if (animal.equals("TIGER")) {
result = "wild animal";
} else {
result = "unknown animal";
}
return result;
}
public String exampleOfSwitch(String animal) {
String result;
switch (animal) {
case "DOG":
case "CAT":
result = "domestic animal";
break;
case "TIGER":
result = "wild animal";
break;
default:
result = "unknown animal";
break;
}
return result;
}
public String forgetBreakInSwitch(String animal) {
String result;
switch (animal) {
case "DOG":
System.out.println("domestic animal");
result = "domestic animal";
default:
System.out.println("unknown animal");
result = "unknown animal";
}
return result;
}
public String constantCaseValue(String animal) {
String result = "";
final String dog = "DOG";
switch (animal) {
case dog:
result = "domestic animal";
}
return result;
}
}

View File

@@ -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!
}
}
}

View File

@@ -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();
}
}

View File

@@ -0,0 +1,7 @@
package com.baeldung.system;
public class EnvironmentVariables {
public String getPath() {
return System.getenv("PATH");
}
}

View File

@@ -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");
}
}

View File

@@ -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()
}
}

View File

@@ -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"));
}
}

View File

@@ -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: ");
}
}

View File

@@ -0,0 +1,39 @@
package com.baeldung.breakcontinue;
import static com.baeldung.breakcontinue.BreakContinue.labeledBreak;
import static com.baeldung.breakcontinue.BreakContinue.labeledContinue;
import static com.baeldung.breakcontinue.BreakContinue.unlabeledBreak;
import static com.baeldung.breakcontinue.BreakContinue.unlabeledBreakNestedLoops;
import static com.baeldung.breakcontinue.BreakContinue.unlabeledContinue;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class BreakContinueUnitTest {
@Test
public void whenUnlabeledBreak_ThenEqual() {
assertEquals(4, unlabeledBreak());
}
@Test
public void whenUnlabeledBreakNestedLoops_ThenEqual() {
assertEquals(2, unlabeledBreakNestedLoops());
}
@Test
public void whenLabeledBreak_ThenEqual() {
assertEquals(1, labeledBreak());
}
@Test
public void whenUnlabeledContinue_ThenEqual() {
assertEquals(5, unlabeledContinue());
}
@Test
public void whenLabeledContinue_ThenEqual() {
assertEquals(3, labeledContinue());
}
}

View File

@@ -0,0 +1,79 @@
package com.baeldung.enums;
import com.baeldung.enums.Pizza.PizzaStatusEnum;
import org.junit.Test;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import static junit.framework.TestCase.assertTrue;
public class PizzaUnitTest {
@Test
public void givenPizaOrder_whenReady_thenDeliverable() {
Pizza testPz = new Pizza();
testPz.setStatus(Pizza.PizzaStatusEnum.READY);
assertTrue(testPz.isDeliverable());
}
@Test
public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
List<Pizza> pzList = new ArrayList<>();
Pizza pz1 = new Pizza();
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
Pizza pz2 = new Pizza();
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz3 = new Pizza();
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz4 = new Pizza();
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
pzList.add(pz1);
pzList.add(pz2);
pzList.add(pz3);
pzList.add(pz4);
List<Pizza> undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
assertTrue(undeliveredPzs.size() == 3);
}
@Test
public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
List<Pizza> pzList = new ArrayList<>();
Pizza pz1 = new Pizza();
pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
Pizza pz2 = new Pizza();
pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz3 = new Pizza();
pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz4 = new Pizza();
pz4.setStatus(Pizza.PizzaStatusEnum.READY);
pzList.add(pz1);
pzList.add(pz2);
pzList.add(pz3);
pzList.add(pz4);
EnumMap<Pizza.PizzaStatusEnum, List<Pizza>> map = Pizza.groupPizzaByStatus(pzList);
assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1);
assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2);
assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1);
}
@Test
public void whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
Pizza pz = new Pizza();
pz.setStatus(Pizza.PizzaStatusEnum.READY);
pz.deliver();
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
}
}

View File

@@ -0,0 +1,78 @@
package com.baeldung.generics;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
public class GenericsUnitTest {
// testing the generic method with Integer
@Test
public void givenArrayOfIntegers_thanListOfIntegersReturnedOK() {
Integer[] intArray = { 1, 2, 3, 4, 5 };
List<Integer> list = Generics.fromArrayToList(intArray);
assertThat(list, hasItems(intArray));
}
// testing the generic method with Integer and String type
@Test
public void givenArrayOfIntegers_thanListOfStringReturnedOK() {
Integer[] intArray = { 1, 2, 3, 4, 5 };
List<String> stringList = Generics.fromArrayToList(intArray, Object::toString);
assertThat(stringList, hasItems("1", "2", "3", "4", "5"));
}
// testing the generic method with String
@Test
public void givenArrayOfStrings_thanListOfStringsReturnedOK() {
String[] stringArray = { "hello1", "hello2", "hello3", "hello4", "hello5" };
List<String> list = Generics.fromArrayToList(stringArray);
assertThat(list, hasItems(stringArray));
}
// testing the generic method with Number as upper bound with Integer
// if we test fromArrayToListWithUpperBound with any type that doesn't
// extend Number it will fail to compile
@Test
public void givenArrayOfIntegersAndNumberUpperBound_thanListOfIntegersReturnedOK() {
Integer[] intArray = { 1, 2, 3, 4, 5 };
List<Integer> list = Generics.fromArrayToListWithUpperBound(intArray);
assertThat(list, hasItems(intArray));
}
// testing paintAllBuildings method with a subtype of Building, the method
// will work with all subtypes of Building
@Test
public void givenSubTypeOfWildCardBoundedGenericType_thanPaintingOK() {
try {
List<Building> subBuildingsList = new ArrayList<>();
subBuildingsList.add(new Building());
subBuildingsList.add(new House());
// prints
// Painting Building
// Painting House
Generics.paintAllBuildings(subBuildingsList);
} catch (Exception e) {
fail();
}
}
@Test
public void givenAnInt_whenAddedToAGenericIntegerList_thenAListItemCanBeAssignedToAnInt() {
int number = 7;
List<Integer> list = Generics.createList(number);
int otherNumber = list.get(0);
assertThat(otherNumber, is(number));
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.initializationguide;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import java.lang.reflect.InvocationTargetException;
public class UserUnitTest {
@Test
public void givenUserInstance_whenIntializedWithNew_thenInstanceIsNotNull() {
User user = new User("Alice", 1);
assertThat(user).isNotNull();
}
@Test
public void givenUserInstance_whenInitializedWithReflection_thenInstanceIsNotNull() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
User user = User.class.getConstructor(String.class, int.class)
.newInstance("Alice", 2);
assertThat(user).isNotNull();
}
@Test
public void givenUserInstance_whenCopiedWithClone_thenExactMatchIsCreated() throws CloneNotSupportedException {
User user = new User("Alice", 3);
User clonedUser = (User) user.clone();
assertThat(clonedUser).isEqualTo(user);
}
@Test
public void givenUserInstance_whenValuesAreNotInitialized_thenUserNameAndIdReturnDefault() {
User user = new User();
assertThat(user.getName()).isNull();
assertThat(user.getId() == 0);
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.java.diamond;
public class Car<T extends Engine> implements Vehicle<T> {
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.java.diamond;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
public class DiamondOperatorUnitTest {
@Test
public void whenCreateCarUsingDiamondOperator_thenSuccess() {
Car<Diesel> myCar = new Car<>();
assertNotNull(myCar);
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.java.diamond;
public class Diesel implements Engine {
@Override
public void start() {
System.out.println("Started Diesel...");
}
}

View File

@@ -0,0 +1,6 @@
package com.baeldung.java.diamond;
public interface Engine {
void start();
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.java.diamond;
public interface Vehicle<T extends Engine> {
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.java.doublebrace;
import org.junit.Test;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toSet;
import static org.junit.Assert.assertTrue;
public class DoubleBraceUnitTest {
@Test
public void whenInitializeSetWithoutDoubleBraces_containsElements() {
final Set<String> countries = new HashSet<>();
countries.add("India");
countries.add("USSR");
countries.add("USA");
assertTrue(countries.contains("India"));
}
@Test
public void whenInitializeSetWithDoubleBraces_containsElements() {
final Set<String> countries = new HashSet<String>() {
{
add("India");
add("USSR");
add("USA");
}
};
assertTrue(countries.contains("India"));
}
@Test
public void whenInitializeUnmodifiableSetWithDoubleBrace_containsElements() {
Set<String> countries = Stream.of("India", "USSR", "USA")
.collect(collectingAndThen(toSet(), Collections::unmodifiableSet));
assertTrue(countries.contains("India"));
}
}

View File

@@ -0,0 +1,55 @@
package com.baeldung.keyword.test;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import com.baeldung.keyword.Circle;
import com.baeldung.keyword.Ring;
import com.baeldung.keyword.Round;
import com.baeldung.keyword.Shape;
import com.baeldung.keyword.Triangle;
public class InstanceOfUnitTest {
@Test
public void giveWhenInstanceIsCorrect_thenReturnTrue() {
Ring ring = new Ring();
Assert.assertTrue("ring is instance of Round ", ring instanceof Round);
}
@Test
public void giveWhenObjectIsInstanceOfType_thenReturnTrue() {
Circle circle = new Circle();
Assert.assertTrue("circle is instance of Circle ", circle instanceof Circle);
}
@Test
public void giveWhenInstanceIsOfSubtype_thenReturnTrue() {
Circle circle = new Circle();
Assert.assertTrue("circle is instance of Round", circle instanceof Round);
}
@Test
public void giveWhenTypeIsInterface_thenReturnTrue() {
Circle circle = new Circle();
Assert.assertTrue("circle is instance of Shape", circle instanceof Shape);
}
@Test
public void giveWhenTypeIsOfObjectType_thenReturnTrue() {
Thread thread = new Thread();
Assert.assertTrue("thread is instance of Object", thread instanceof Object);
}
@Test
public void giveWhenInstanceValueIsNull_thenReturnFalse() {
Circle circle = null;
Assert.assertFalse("circle is instance of Round", circle instanceof Round);
}
@Test
public void giveWhenComparingClassInDiffHierarchy_thenCompilationError() {
// Assert.assertFalse("circle is instance of Triangle", circle instanceof Triangle);
}
}

View File

@@ -0,0 +1,107 @@
package com.baeldung.loops;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class WhenUsingLoops {
private LoopsInJava loops = new LoopsInJava();
private static List<String> list = new ArrayList<>();
private static Set<String> set = new HashSet<>();
private static Map<String, Integer> map = new HashMap<>();
@BeforeClass
public static void setUp() {
list.add("One");
list.add("Two");
list.add("Three");
set.add("Four");
set.add("Five");
set.add("Six");
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
}
@Test
public void shouldRunForLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.simple_for_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void shouldRunEnhancedForeachLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.enhanced_for_each_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void shouldRunWhileLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.while_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void shouldRunDoWhileLoop() {
int[] expected = { 0, 1, 2, 3, 4 };
int[] actual = loops.do_while_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void whenUsingSimpleFor_shouldIterateList() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateList() {
for (String item : list) {
System.out.println(item);
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateSet() {
for (String item : set) {
System.out.println(item);
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateMap() {
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + " - " + "Value: " + entry.getValue());
}
}
@Test
public void whenUsingSimpleFor_shouldRunLabelledLoop() {
aa: for (int i = 1; i <= 3; i++) {
if (i == 1)
continue;
bb: for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break aa;
}
System.out.println(i + " " + j);
}
}
}
}

View File

@@ -0,0 +1,54 @@
package com.baeldung.modulo;
import org.junit.Test;
import static org.assertj.core.api.Java6Assertions.*;
public class ModuloUnitTest {
@Test
public void whenIntegerDivision_thenLosesRemainder(){
assertThat(11 / 4).isEqualTo(2);
}
@Test
public void whenDoubleDivision_thenKeepsRemainder(){
assertThat(11 / 4.0).isEqualTo(2.75);
}
@Test
public void whenModulo_thenReturnsRemainder(){
assertThat(11 % 4).isEqualTo(3);
}
@Test(expected = ArithmeticException.class)
public void whenDivisionByZero_thenArithmeticException(){
double result = 1 / 0;
}
@Test(expected = ArithmeticException.class)
public void whenModuloByZero_thenArithmeticException(){
double result = 1 % 0;
}
@Test
public void whenDivisorIsOddAndModulusIs2_thenResultIs1(){
assertThat(3 % 2).isEqualTo(1);
}
@Test
public void whenDivisorIsEvenAndModulusIs2_thenResultIs0(){
assertThat(4 % 2).isEqualTo(0);
}
@Test
public void whenItemsIsAddedToCircularQueue_thenNoArrayIndexOutOfBounds(){
int QUEUE_CAPACITY= 10;
int[] circularQueue = new int[QUEUE_CAPACITY];
int itemsInserted = 0;
for (int value = 0; value < 1000; value++) {
int writeIndex = ++itemsInserted % QUEUE_CAPACITY;
circularQueue[writeIndex] = value;
}
}
}

View File

@@ -0,0 +1,126 @@
package com.baeldung.primitiveconversion;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
public class PrimitiveConversionsJUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(PrimitiveConversionsJUnitTest.class);
@Test
public void givenDataWithLessBits_whenAttributingToLargerSizeVariable_thenNoSpecialNotation() {
int myInt = 127;
long myLong = myInt;
assertEquals(127L, myLong);
float myFloat = myLong;
assertEquals(127.0f, myFloat, 0.00001f);
double myDouble = myLong;
assertEquals(127.0, myDouble,0.00001);
}
@Test
public void givenDataWithMoreBits_whenAttributingToSmallerSizeVariable_thenCastOperatorNeeded() {
long myLong = 127L;
double myDouble = 127.0;
float myFloat = (float) myDouble;
assertEquals(127.0f, myFloat, 0.00001f);
int myInt = (int) myLong;
assertEquals(127, myInt);
byte myByte = (byte) myInt;
assertEquals( ((byte)127), myByte);
}
@Test
public void givenPrimitiveData_whenAssiginingToWrapper_thenAutomaticBoxingHappens(){
int myInt = 127;
Integer myIntegerReference = myInt;
assertEquals(new Integer("127"), myIntegerReference);
}
@Test
public void givenWrapperObjectData_whenAssiginingToPrimitive_thenAutomaticUnboxingHappens(){
Integer myIntegerReference = new Integer("127");
int myOtherInt = myIntegerReference;
assertEquals(127, myOtherInt);
}
@Test
public void givenByteValue_whenConvertingToChar_thenWidenAndNarrowTakesPlace(){
byte myLargeValueByte = (byte) 130; //0b10000010
LOG.debug("{}", myLargeValueByte); //0b10000010 -126
assertEquals( -126, myLargeValueByte);
int myLargeValueInt = myLargeValueByte;
LOG.debug("{}", myLargeValueInt); //0b11111111 11111111 11111111 10000010 -126
assertEquals( -126, myLargeValueInt);
char myLargeValueChar = (char) myLargeValueByte;
LOG.debug("{}", myLargeValueChar);//0b11111111 10000010 unsigned 0xFF82
assertEquals(0xFF82, myLargeValueChar);
myLargeValueInt = myLargeValueChar;
LOG.debug("{}", myLargeValueInt); //0b11111111 10000010 65410
assertEquals(65410, myLargeValueInt);
byte myOtherByte = (byte) myLargeValueInt;
LOG.debug("{}", myOtherByte); //0b10000010 -126
assertEquals( -126, myOtherByte);
char myLargeValueChar2 = 130; //This is an int not a byte!
LOG.debug("{}", myLargeValueChar2);//0b00000000 10000010 unsigned 0x0082
assertEquals(0x0082, myLargeValueChar2);
int myLargeValueInt2 = myLargeValueChar2;
LOG.debug("{}", myLargeValueInt2); //0b00000000 10000010 130
assertEquals(130, myLargeValueInt2);
byte myOtherByte2 = (byte) myLargeValueInt2;
LOG.debug("{}", myOtherByte2); //0b10000010 -126
assertEquals( -126, myOtherByte2);
}
@Test
public void givenString_whenParsingWithWrappers_thenValuesAreReturned(){
String myString = "127";
byte myNewByte = Byte.parseByte(myString);
assertEquals( ((byte)127), myNewByte);
short myNewShort = Short.parseShort(myString);
assertEquals( ((short)127), myNewShort);
int myNewInt = Integer.parseInt(myString);
assertEquals( 127, myNewInt);
long myNewLong = Long.parseLong(myString);
assertEquals( 127L, myNewLong);
float myNewFloat = Float.parseFloat(myString);
assertEquals( 127.0f, myNewFloat, 0.00001f);
double myNewDouble = Double.parseDouble(myString);
assertEquals( 127.0, myNewDouble, 0.00001f);
boolean myNewBoolean = Boolean.parseBoolean(myString);
assertEquals( false, myNewBoolean); //numbers are not true!
char myNewChar = myString.charAt(0);
assertEquals( 49, myNewChar); //the value of '1'
}
}

View File

@@ -0,0 +1,38 @@
package com.baeldung.switchstatement;
import org.junit.Test;
import org.junit.Assert;
public class SwitchStatementUnitTest {
private SwitchStatement s = new SwitchStatement();
@Test
public void whenDog_thenDomesticAnimal() {
String animal = "DOG";
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
}
@Test
public void whenNoBreaks_thenGoThroughBlocks() {
String animal = "DOG";
Assert.assertEquals("unknown animal", s.forgetBreakInSwitch(animal));
}
@Test(expected=NullPointerException.class)
public void whenSwitchAgumentIsNull_thenNullPointerException() {
String animal = null;
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
}
@Test
public void whenCompareStrings_thenByEqual() {
String animal = new String("DOG");
Assert.assertEquals("domestic animal", s.exampleOfSwitch(animal));
}
}

View File

@@ -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());
}
}

View File

@@ -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());
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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());
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.ternaryoperator;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class TernaryOperatorUnitTest {
@Test
public void givenACondition_whenUsingTernaryOperator_thenItEvaluatesConditionAndReturnsAValue() {
int number = 10;
String msg = number > 10 ? "Number is greater than 10" : "Number is less than or equal to 10";
assertThat(msg).isEqualTo("Number is less than or equal to 10");
}
@Test
public void givenATrueCondition_whenUsingTernaryOperator_thenOnlyExpression1IsEvaluated() {
int exp1 = 0, exp2 = 0;
int result = 12 > 10 ? ++exp1 : ++exp2;
assertThat(exp1).isEqualTo(1);
assertThat(exp2).isEqualTo(0);
assertThat(result).isEqualTo(1);
}
@Test
public void givenAFalseCondition_whenUsingTernaryOperator_thenOnlyExpression2IsEvaluated() {
int exp1 = 0, exp2 = 0;
int result = 8 > 10 ? ++exp1 : ++exp2;
assertThat(exp1).isEqualTo(0);
assertThat(exp2).isEqualTo(1);
assertThat(result).isEqualTo(1);
}
@Test
public void givenANestedCondition_whenUsingTernaryOperator_thenCorrectValueIsReturned() {
int number = 6;
String msg = number > 10 ? "Number is greater than 10" : number > 5 ? "Number is greater than 5" : "Number is less than or equal to 5";
assertThat(msg).isEqualTo("Number is greater than 5");
}
}

View File

@@ -0,0 +1,60 @@
package com.baeldung.varargs;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class FormatterUnitTest {
private final static String FORMAT = "%s %s %s";
@Test
public void givenNoArgument_thenEmptyAndTwoSpacesAreReturned() {
String actualResult = format();
assertThat(actualResult, is("empty "));
}
@Test
public void givenOneArgument_thenResultHasTwoTrailingSpace() {
String actualResult = format("baeldung");
assertThat(actualResult, is("baeldung "));
}
@Test
public void givenTwoArguments_thenOneTrailingSpaceExists() {
String actualResult = format("baeldung", "rocks");
assertThat(actualResult, is("baeldung rocks "));
}
@Test
public void givenMoreThanThreeArguments_thenTheFirstThreeAreUsed() {
String actualResult = formatWithVarArgs("baeldung", "rocks", "java", "and", "spring");
assertThat(actualResult, is("baeldung rocks java"));
}
public String format() {
return format("empty", "");
}
public String format(String value) {
return format(value, "");
}
public String format(String val1, String val2) {
return String.format(FORMAT, val1, val2, "");
}
public String formatWithVarArgs(String... values) {
if (values.length == 0) {
return "no arguments given";
}
return String.format(FORMAT, values);
}
}