Fixed conflicts
This commit is contained in:
@@ -9,4 +9,5 @@ This module contains articles about the Java List collection
|
||||
- [List of Primitive Integer Values in Java](https://www.baeldung.com/java-list-primitive-int)
|
||||
- [Performance Comparison of Primitive Lists in Java](https://www.baeldung.com/java-list-primitive-performance)
|
||||
- [Filtering a Java Collection by a List](https://www.baeldung.com/java-filter-collection-by-list)
|
||||
- [How to Count Duplicate Elements in Arraylist](https://www.baeldung.com/java-count-duplicate-elements-arraylist)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-collections-list-2)
|
||||
|
||||
@@ -14,11 +14,18 @@
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>core-java-concurrency-advanced-3</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
@@ -28,6 +35,8 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.commonissues;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class CollectionsConcurrencyIssues {
|
||||
|
||||
private void putIfAbsentList_NonAtomicOperation_ProneToConcurrencyIssues() {
|
||||
List<String> list = Collections.synchronizedList(new ArrayList<>());
|
||||
if (!list.contains("foo")) {
|
||||
list.add("foo");
|
||||
}
|
||||
}
|
||||
|
||||
private void putIfAbsentList_AtomicOperation_ThreadSafe() {
|
||||
List<String> list = Collections.synchronizedList(new ArrayList<>());
|
||||
synchronized (list) {
|
||||
if (!list.contains("foo")) {
|
||||
list.add("foo");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void putIfAbsentMap_NonAtomicOperation_ProneToConcurrencyIssues() {
|
||||
Map<String, String> map = new ConcurrentHashMap<>();
|
||||
if (!map.containsKey("foo")) {
|
||||
map.put("foo", "bar");
|
||||
}
|
||||
}
|
||||
|
||||
private void putIfAbsentMap_AtomicOperation_BetterApproach() {
|
||||
Map<String, String> map = new ConcurrentHashMap<>();
|
||||
synchronized (map) {
|
||||
if (!map.containsKey("foo")) {
|
||||
map.put("foo", "bar");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void putIfAbsentMap_AtomicOperation_BestApproach() {
|
||||
Map<String, String> map = new ConcurrentHashMap<>();
|
||||
map.putIfAbsent("foo", "bar");
|
||||
}
|
||||
|
||||
private void computeIfAbsentMap_AtomicOperation() {
|
||||
Map<String, String> map = new ConcurrentHashMap<>();
|
||||
map.computeIfAbsent("foo", key -> key + "bar");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.commonissues;
|
||||
|
||||
class Counter {
|
||||
private int counter = 0;
|
||||
|
||||
public void increment() {
|
||||
counter++;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return counter;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.commonissues;
|
||||
|
||||
public class DeadlockExample {
|
||||
|
||||
public static Object lock1 = new Object();
|
||||
public static Object lock2 = new Object();
|
||||
|
||||
public static void main(String args[]) {
|
||||
Thread threadA = new Thread(() -> {
|
||||
synchronized (lock1) {
|
||||
System.out.println("ThreadA: Holding lock 1...");
|
||||
sleep();
|
||||
System.out.println("ThreadA: Waiting for lock 2...");
|
||||
|
||||
synchronized (lock2) {
|
||||
System.out.println("ThreadA: Holding lock 1 & 2...");
|
||||
}
|
||||
}
|
||||
});
|
||||
Thread threadB = new Thread(() -> {
|
||||
synchronized (lock2) {
|
||||
System.out.println("ThreadB: Holding lock 2...");
|
||||
sleep();
|
||||
System.out.println("ThreadB: Waiting for lock 1...");
|
||||
|
||||
synchronized (lock1) {
|
||||
System.out.println("ThreadB: Holding lock 1 & 2...");
|
||||
}
|
||||
}
|
||||
});
|
||||
threadA.start();
|
||||
threadB.start();
|
||||
}
|
||||
|
||||
private static void sleep() {
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.commonissues;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
public class SimpleDateFormatThreadUnsafetyExample {
|
||||
|
||||
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
|
||||
|
||||
public static void main(String[] args) {
|
||||
String dateStr = "2019-10-29T11:12:21";
|
||||
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(10);
|
||||
|
||||
for (int i = 0; i < 20; i++) {
|
||||
executorService.submit(() -> parseDate(dateStr));
|
||||
}
|
||||
|
||||
executorService.shutdown();
|
||||
}
|
||||
|
||||
private static void parseDate(String dateStr) {
|
||||
try {
|
||||
Date date = simpleDateFormat.parse(dateStr);
|
||||
System.out.println("Successfully Parsed Date " + date);
|
||||
} catch (ParseException e) {
|
||||
System.out.println("ParseError " + e.getMessage());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.commonissues;
|
||||
|
||||
class SynchronizedCounter {
|
||||
private int counter = 0;
|
||||
|
||||
public synchronized void increment() {
|
||||
counter++;
|
||||
}
|
||||
|
||||
public synchronized int getValue() {
|
||||
return counter;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.commonissues;
|
||||
|
||||
class SynchronizedVolatileCounter {
|
||||
private volatile int counter = 0;
|
||||
|
||||
public synchronized void increment() {
|
||||
counter++;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return counter;
|
||||
}
|
||||
}
|
||||
3
core-java-modules/core-java-date-operations/README.md
Normal file
3
core-java-modules/core-java-date-operations/README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
- [Get the Current Date Prior to Java 8](https://www.baeldung.com/java-get-the-current-date-legacy)
|
||||
- [Skipping Weekends While Adding Days to LocalDate in Java 8](https://www.baeldung.com/java-localdate-add-days-skip-weekends)
|
||||
@@ -13,3 +13,4 @@ This module contains articles about the Date and Time API introduced with Java 8
|
||||
- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
|
||||
- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone)
|
||||
- [Comparing Dates in Java](https://www.baeldung.com/java-comparing-dates)
|
||||
- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates)
|
||||
|
||||
@@ -17,3 +17,4 @@ This module contains articles about core java exceptions
|
||||
- [Common Java Exceptions](https://www.baeldung.com/java-common-exceptions)
|
||||
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
|
||||
- [How to Find an Exception’s Root Cause in Java](https://www.baeldung.com/java-exception-root-cause)
|
||||
- [Is It a Bad Practice to Catch Throwable?](https://www.baeldung.com/java-catch-throwable-bad-practice)
|
||||
|
||||
@@ -5,4 +5,5 @@ This module contains articles about core features in the Java language
|
||||
### Relevant Articles:
|
||||
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
|
||||
- [Command-Line Arguments in Java](https://www.baeldung.com/java-command-line-arguments)
|
||||
- [What is a POJO Class?](https://www.baeldung.com/java-pojo-class)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-lang)
|
||||
|
||||
@@ -6,3 +6,4 @@
|
||||
- [Java 8 Math New Methods](https://www.baeldung.com/java-8-math)
|
||||
- [Java 8 Unsigned Arithmetic Support](https://www.baeldung.com/java-unsigned-arithmetic)
|
||||
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
|
||||
- [The strictfp Keyword in Java](https://www.baeldung.com/java-strictfp)
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.calculator.basic;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class BasicCalculatorIfElse {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.println("---------------------------------- \n" + "Welcome to Basic Calculator \n" + "----------------------------------");
|
||||
System.out.println("Following operations are supported : \n" + "1. Addition (+) \n" + "2. Subtraction (-) \n" + "3. Multiplication (* OR x) \n" + "4. Division (/) \n");
|
||||
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
try {
|
||||
System.out.println("Enter an operator: (+ OR - OR * OR /) ");
|
||||
char operation = scanner.next()
|
||||
.charAt(0);
|
||||
|
||||
if (!(operation == '+' || operation == '-' || operation == '*' || operation == 'x' || operation == '/')) {
|
||||
System.err.println("Invalid Operator. Please use only + or - or * or /");
|
||||
}
|
||||
|
||||
System.out.println("Enter First Number: ");
|
||||
double num1 = scanner.nextDouble();
|
||||
|
||||
System.out.println("Enter Second Number: ");
|
||||
double num2 = scanner.nextDouble();
|
||||
|
||||
if (operation == '/' && num2 == 0.0) {
|
||||
System.err.println("Second Number cannot be zero for Division operation.");
|
||||
}
|
||||
|
||||
if (operation == '+') {
|
||||
System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
|
||||
} else if (operation == '-') {
|
||||
System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));
|
||||
} else if (operation == '*' || operation == 'x') {
|
||||
System.out.println(num1 + " x " + num2 + " = " + (num1 * num2));
|
||||
} else if (operation == '/') {
|
||||
System.out.println(num1 + " / " + num2 + " = " + (num1 / num2));
|
||||
} else {
|
||||
System.err.println("Invalid Operator Specified.");
|
||||
}
|
||||
} catch (InputMismatchException exc) {
|
||||
System.err.println(exc.getMessage());
|
||||
} finally {
|
||||
scanner.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.calculator.basic;
|
||||
|
||||
import java.util.InputMismatchException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class BasicCalculatorSwitchCase {
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.println("---------------------------------- \n" + "Welcome to Basic Calculator \n" + "----------------------------------");
|
||||
System.out.println("Following operations are supported : \n" + "1. Addition (+) \n" + "2. Subtraction (-) \n" + "3. Multiplication (* OR x) \n" + "4. Division (/) \n");
|
||||
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
try {
|
||||
System.out.println("Enter an operator: (+ OR - OR * OR /) ");
|
||||
char operation = scanner.next()
|
||||
.charAt(0);
|
||||
|
||||
if (!(operation == '+' || operation == '-' || operation == '*' || operation == 'x' || operation == '/')) {
|
||||
System.err.println("Invalid Operator. Please use only + or - or * or /");
|
||||
}
|
||||
|
||||
System.out.println("Enter First Number: ");
|
||||
double num1 = scanner.nextDouble();
|
||||
|
||||
System.out.println("Enter Second Number: ");
|
||||
double num2 = scanner.nextDouble();
|
||||
|
||||
if (operation == '/' && num2 == 0.0) {
|
||||
System.err.println("Second Number cannot be zero for Division operation.");
|
||||
}
|
||||
|
||||
switch (operation) {
|
||||
case '+':
|
||||
System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
|
||||
break;
|
||||
case '-':
|
||||
System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));
|
||||
break;
|
||||
case '*':
|
||||
System.out.println(num1 + " x " + num2 + " = " + (num1 * num2));
|
||||
break;
|
||||
case 'x':
|
||||
System.out.println(num1 + " x " + num2 + " = " + (num1 * num2));
|
||||
break;
|
||||
case '/':
|
||||
System.out.println(num1 + " / " + num2 + " = " + (num1 / num2));
|
||||
break;
|
||||
default:
|
||||
System.err.println("Invalid Operator Specified.");
|
||||
break;
|
||||
}
|
||||
} catch (InputMismatchException exc) {
|
||||
System.err.println(exc.getMessage());
|
||||
} finally {
|
||||
scanner.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.overflow;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public class Overflow {
|
||||
|
||||
public static void showIntegerOverflow() {
|
||||
|
||||
int value = Integer.MAX_VALUE-1;
|
||||
|
||||
for(int i = 0; i < 4; i++, value++) {
|
||||
System.out.println(value);
|
||||
}
|
||||
}
|
||||
|
||||
public static void noOverflowWithBigInteger() {
|
||||
|
||||
BigInteger largeValue = new BigInteger(Integer.MAX_VALUE + "");
|
||||
for(int i = 0; i < 4; i++) {
|
||||
System.out.println(largeValue);
|
||||
largeValue = largeValue.add(BigInteger.ONE);
|
||||
}
|
||||
}
|
||||
|
||||
public static void exceptionWithAddExact() {
|
||||
|
||||
int value = Integer.MAX_VALUE-1;
|
||||
for(int i = 0; i < 4; i++) {
|
||||
System.out.println(value);
|
||||
value = Math.addExact(value, 1);
|
||||
}
|
||||
}
|
||||
|
||||
public static int addExact(int x, int y) {
|
||||
|
||||
int r = x + y;
|
||||
if (((x ^ r) & (y ^ r)) < 0) {
|
||||
throw new ArithmeticException("int overflow");
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
public static void demonstrateUnderflow() {
|
||||
|
||||
for(int i = 1073; i <= 1076; i++) {
|
||||
System.out.println("2^" + i + " = " + Math.pow(2, -i));
|
||||
}
|
||||
}
|
||||
|
||||
public static double powExact(double base, double exponent)
|
||||
{
|
||||
if(base == 0.0) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
double result = Math.pow(base, exponent);
|
||||
|
||||
if(result == Double.POSITIVE_INFINITY ) {
|
||||
throw new ArithmeticException("Double overflow resulting in POSITIVE_INFINITY");
|
||||
} else if(result == Double.NEGATIVE_INFINITY) {
|
||||
throw new ArithmeticException("Double overflow resulting in NEGATIVE_INFINITY");
|
||||
} else if(Double.compare(-0.0f, result) == 0) {
|
||||
throw new ArithmeticException("Double overflow resulting in negative zero");
|
||||
} else if(Double.compare(+0.0f, result) == 0) {
|
||||
throw new ArithmeticException("Double overflow resulting in positive zero");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.math;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class OverflowUnitTest {
|
||||
|
||||
@Test
|
||||
public void positive_and_negative_zero_are_not_always_equal() {
|
||||
|
||||
double a = +0f;
|
||||
double b = -0f;
|
||||
|
||||
assertTrue(a == b);
|
||||
|
||||
assertTrue(1/a == Double.POSITIVE_INFINITY);
|
||||
assertTrue(1/b == Double.NEGATIVE_INFINITY);
|
||||
|
||||
assertTrue(1/a != 1/b);
|
||||
}
|
||||
}
|
||||
@@ -8,4 +8,5 @@ This module contains articles about the Stream API in Java.
|
||||
- [The Difference Between Collection.stream().forEach() and Collection.forEach()](https://www.baeldung.com/java-collection-stream-foreach)
|
||||
- [Guide to Java 8’s Collectors](https://www.baeldung.com/java-8-collectors)
|
||||
- [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams)
|
||||
- More articles: [[<-- prev>]](/../core-java-streams-2)
|
||||
- [Debugging Java 8 Streams with IntelliJ](https://www.baeldung.com/intellij-debugging-java-streams)
|
||||
- More articles: [[<-- prev>]](/../core-java-streams-2)
|
||||
|
||||
@@ -58,7 +58,7 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<commons-lang3.version>3.8.1</commons-lang3.version>
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
</properties>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package com.baeldung.isnumeric;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
@@ -14,6 +17,8 @@ import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
public class Benchmarking {
|
||||
private static final TestMode MODE = TestMode.DIVERS;
|
||||
|
||||
public static void main(String[] args) throws RunnerException {
|
||||
Options opt = new OptionsBuilder().include(Benchmarking.class.getSimpleName())
|
||||
.forks(1)
|
||||
@@ -22,52 +27,89 @@ public class Benchmarking {
|
||||
new Runner(opt).run();
|
||||
}
|
||||
|
||||
private static final IsNumeric subject = new IsNumeric();
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class ExecutionPlan {
|
||||
public String number = Integer.toString(Integer.MAX_VALUE);
|
||||
public boolean isNumber = false;
|
||||
public IsNumeric isNumeric = new IsNumeric();
|
||||
private final Map<String, Boolean> testPlan = testPlan();
|
||||
|
||||
void validate(Function<String, Boolean> functionUnderTest) {
|
||||
testPlan.forEach((key, value) -> {
|
||||
Boolean result = functionUnderTest.apply(key);
|
||||
|
||||
assertEquals(value, result, key);
|
||||
});
|
||||
}
|
||||
|
||||
private void assertEquals(Boolean expectedResult, Boolean result, String input) {
|
||||
if (result != expectedResult) {
|
||||
throw new IllegalStateException("The output does not match the expected output, for input: " + input);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Boolean> testPlan() {
|
||||
HashMap<String, Boolean> plan = new HashMap<>();
|
||||
plan.put(Integer.toString(Integer.MAX_VALUE), true);
|
||||
|
||||
if (MODE == TestMode.SIMPLE) {
|
||||
return plan;
|
||||
}
|
||||
|
||||
plan.put("x0", false);
|
||||
plan.put("0..005", false);
|
||||
plan.put("--11", false);
|
||||
plan.put("test", false);
|
||||
plan.put(null, false);
|
||||
for (int i = 0; i < 94; i++) {
|
||||
plan.put(Integer.toString(i), true);
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingCoreJava(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingCoreJava(plan.number);
|
||||
plan.validate(subject::usingCoreJava);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingRegularExpressions(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingRegularExpressions(plan.number);
|
||||
plan.validate(subject::usingPreCompiledRegularExpressions);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingNumberUtils_isCreatable(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingNumberUtils_isCreatable(plan.number);
|
||||
plan.validate(subject::usingNumberUtils_isCreatable);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingNumberUtils_isParsable(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingNumberUtils_isParsable(plan.number);
|
||||
plan.validate(subject::usingNumberUtils_isParsable);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingStringUtils_isNumeric(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingStringUtils_isNumeric(plan.number);
|
||||
plan.validate(subject::usingStringUtils_isNumeric);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingStringUtils_isNumericSpace(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingStringUtils_isNumericSpace(plan.number);
|
||||
plan.validate(subject::usingStringUtils_isNumericSpace);
|
||||
}
|
||||
|
||||
private enum TestMode {
|
||||
SIMPLE, DIVERS
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.isnumeric;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
public class CheckIntegerInput {
|
||||
|
||||
public static void main(String[] args) {
|
||||
try (Scanner scanner = new Scanner(System.in)) {
|
||||
System.out.println("Enter an integer : ");
|
||||
|
||||
if (scanner.hasNextInt()) {
|
||||
System.out.println("You entered : " + scanner.nextInt());
|
||||
} else {
|
||||
System.out.println("The input is not an integer");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,33 @@
|
||||
package com.baeldung.isnumeric;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
|
||||
public class IsNumeric {
|
||||
private final Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");
|
||||
|
||||
public boolean usingCoreJava(String strNum) {
|
||||
if (strNum == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
Double.parseDouble(strNum);
|
||||
} catch (NumberFormatException | NullPointerException nfe) {
|
||||
} catch (NumberFormatException nfe) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean usingRegularExpressions(String strNum) {
|
||||
return strNum.matches("-?\\d+(\\.\\d+)?");
|
||||
public boolean usingPreCompiledRegularExpressions(String strNum) {
|
||||
if (strNum == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return pattern.matcher(strNum)
|
||||
.matches();
|
||||
}
|
||||
|
||||
public boolean usingNumberUtils_isCreatable(String strNum) {
|
||||
|
||||
@@ -13,8 +13,8 @@ public class IsNumericDriver {
|
||||
boolean res = isNumeric.usingCoreJava("1001");
|
||||
LOG.info("Using Core Java : " + res);
|
||||
|
||||
res = isNumeric.usingRegularExpressions("1001");
|
||||
LOG.info("Using Regular Expressions : " + res);
|
||||
res = isNumeric.usingPreCompiledRegularExpressions("1001");
|
||||
LOG.info("Using Pre-compiled Regular Expressions : " + res);
|
||||
|
||||
res = isNumeric.usingNumberUtils_isCreatable("1001");
|
||||
LOG.info("Using NumberUtils.isCreatable : " + res);
|
||||
|
||||
@@ -6,9 +6,13 @@ import org.junit.Test;
|
||||
|
||||
public class CoreJavaIsNumericUnitTest {
|
||||
public static boolean isNumeric(String strNum) {
|
||||
if (strNum == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
double d = Double.parseDouble(strNum);
|
||||
} catch (NumberFormatException | NullPointerException nfe) {
|
||||
Double.parseDouble(strNum);
|
||||
} catch (NumberFormatException nfe) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -2,11 +2,19 @@ package com.baeldung.isnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RegularExpressionsUnitTest {
|
||||
public static boolean isNumeric(String strNum) {
|
||||
return strNum.matches("-?\\d+(\\.\\d+)?");
|
||||
private final Pattern pattern = Pattern.compile("-?\\d+(\\.\\d+)?");
|
||||
|
||||
public boolean isNumeric(String strNum) {
|
||||
if (strNum == null) {
|
||||
return false;
|
||||
}
|
||||
return pattern.matcher(strNum)
|
||||
.matches();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -17,6 +25,7 @@ public class RegularExpressionsUnitTest {
|
||||
assertThat(isNumeric("-200")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(isNumeric(null)).isFalse();
|
||||
assertThat(isNumeric("abc")).isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user