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,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,16 @@
## Core Java Lang Syntax
This module contains articles about Java syntax
### Relevant Articles:
- [The Basics of Java Generics](https://www.baeldung.com/java-generics)
- [Java Primitive Conversions](https://www.baeldung.com/java-primitive-conversions)
- [The Java continue and break Keywords](https://www.baeldung.com/java-continue-and-break)
- [A Guide to Creating Objects in Java](https://www.baeldung.com/java-initialization)
- [A Guide to Java Loops](https://www.baeldung.com/java-loops)
- [Varargs in Java](https://www.baeldung.com/java-varargs)
- [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums)
- [Infinite Loops in Java](https://www.baeldung.com/infinite-loops-java)
- [Java Switch Statement](https://www.baeldung.com/java-switch)
- [Breaking Out of Nested Loops](https://www.baeldung.com/java-breaking-out-nested-loop)
- [[More -->]](/core-java-modules/core-java-lang-syntax-2)
@@ -0,0 +1,52 @@
<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>
<artifactId>core-java-lang-syntax</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-lang-syntax</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>
<!-- 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-syntax</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>
@@ -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;
}
}
@@ -0,0 +1,47 @@
package com.baeldung.breakloop;
public class LoopBreaking {
public String simpleBreak() {
String result = "";
for (int outerCounter = 0; outerCounter < 2; outerCounter++) {
result += "outer" + outerCounter;
for (int innerCounter = 0; innerCounter < 2; innerCounter++) {
result += "inner" + innerCounter;
if (innerCounter == 0) {
break;
}
}
}
return result;
}
public String labelBreak() {
String result = "";
myBreakLabel:
for (int outerCounter = 0; outerCounter < 2; outerCounter++) {
result += "outer" + outerCounter;
for (int innerCounter = 0; innerCounter < 2; innerCounter++) {
result += "inner" + innerCounter;
if (innerCounter == 0) {
break myBreakLabel;
}
}
}
return result;
}
public String usingReturn() {
String result = "";
for (int outerCounter = 0; outerCounter < 2; outerCounter++) {
result += "outer" + outerCounter;
for (int innerCounter = 0; innerCounter < 2; innerCounter++) {
result += "inner" + innerCounter;
if (innerCounter == 0) {
return result;
}
}
}
return "failed";
}
}
@@ -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);
}
}
}
@@ -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);
}
@@ -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;
}
}
@@ -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");
}
}
@@ -0,0 +1,45 @@
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;
}
public <T> List<T> genericMethod(List<T> list) {
return list.stream().collect(Collectors.toList());
}
public List<Object> withErasure(List<Object> list) {
return list.stream().collect(Collectors.toList());
}
}
@@ -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");
}
}
@@ -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;
}
}
@@ -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);
}
}
@@ -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;
}
}
@@ -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;
}
}
@@ -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());
}
}
@@ -0,0 +1,25 @@
package com.baeldung.breakloop;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class LoopBreakingUnitTest {
private LoopBreaking loopBreaking = new LoopBreaking();
@Test
void whenUsingBreak_shouldBreakInnerLoop() {
assertEquals("outer0inner0outer1inner0", loopBreaking.simpleBreak());
}
@Test
void whenUsingLabeledBreak_shouldBreakInnerLoopAndOuterLoop() {
assertEquals("outer0inner0", loopBreaking.labelBreak());
}
@Test
void whenUsingReturn_shouldBreakInnerLoopAndOuterLoop() {
assertEquals("outer0inner0", loopBreaking.usingReturn());
}
}
@@ -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);
}
}
@@ -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));
}
}
@@ -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);
}
}
@@ -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 LoopsUnitTest {
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);
}
}
}
}
@@ -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'
}
}
@@ -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));
}
}
@@ -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);
}
}