Merge branch 'eugenp:master' into master
This commit is contained in:
commit
a142cc0a1a
|
@ -4,6 +4,4 @@ This module contains articles about Apache CXF
|
|||
|
||||
## Relevant Articles:
|
||||
|
||||
- [Apache CXF Support for RESTful Web Services](https://www.baeldung.com/apache-cxf-rest-api)
|
||||
- [A Guide to Apache CXF with Spring](https://www.baeldung.com/apache-cxf-with-spring)
|
||||
- [Introduction to Apache CXF](https://www.baeldung.com/introduction-to-apache-cxf)
|
||||
- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf)
|
||||
|
|
|
@ -1,2 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [Introduction to Apache CXF](http://www.baeldung.com/introduction-to-apache-cxf)
|
||||
- [Introduction to Apache CXF](https://www.baeldung.com/introduction-to-apache-cxf)
|
||||
|
|
|
@ -19,7 +19,7 @@
|
|||
<dependency>
|
||||
<groupId>org.axonframework</groupId>
|
||||
<artifactId>axon-bom</artifactId>
|
||||
<version>${axon.version}</version>
|
||||
<version>${axon-bom.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
|
@ -57,7 +57,7 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<axon.version>4.5.0</axon.version>
|
||||
<axon-bom.version>4.5.13</axon-bom.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.httpclient.parameters;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class HttpClientParametersLiveTest {
|
||||
|
||||
private static HttpClient client;
|
||||
|
||||
@BeforeAll
|
||||
public static void setUp() {
|
||||
client = HttpClient.newHttpClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenQueryParams_whenGetRequest_thenResponseOk() throws IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.version(HttpClient.Version.HTTP_2)
|
||||
.uri(URI.create("https://postman-echo.com/get?param1=value1¶m2=value2"))
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertEquals(response.statusCode(), 200);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenQueryParams_whenGetRequestWithDefaultConfiguration_thenResponseOk() throws IOException, InterruptedException {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create("https://postman-echo.com/get?param1=value1¶m2=value2"))
|
||||
.build();
|
||||
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
assertEquals(response.statusCode(), 200);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.bealdung.java9.finalizers;
|
||||
|
||||
import java.lang.ref.Cleaner;
|
||||
|
||||
class CleaningDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
final Cleaner cleaner = Cleaner.create();
|
||||
try (Order order = new Order(cleaner)) {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
order.register(new Product(i), i);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("Error: " + e);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.bealdung.java9.finalizers;
|
||||
|
||||
import java.lang.ref.Cleaner;
|
||||
|
||||
class Order implements AutoCloseable {
|
||||
|
||||
private final Cleaner cleaner;
|
||||
private Cleaner.Cleanable cleanable;
|
||||
|
||||
public Order(Cleaner cleaner) {
|
||||
this.cleaner = cleaner;
|
||||
}
|
||||
|
||||
public void register(Product product, int id) {
|
||||
this.cleanable = cleaner.register(product, new CleaningAction(id));
|
||||
}
|
||||
|
||||
public void close() {
|
||||
cleanable.clean();
|
||||
System.out.println("Cleanable closed");
|
||||
}
|
||||
|
||||
static class CleaningAction implements Runnable {
|
||||
|
||||
private final int id;
|
||||
|
||||
public CleaningAction(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.printf("Object with id %s is garbage collected. %n", id);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.bealdung.java9.finalizers;
|
||||
|
||||
class Product {
|
||||
private final int id;
|
||||
|
||||
public Product(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.bealdung.java9.finalizers;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileReader;
|
||||
|
||||
class Resource implements AutoCloseable {
|
||||
|
||||
final BufferedReader reader;
|
||||
|
||||
public Resource(String filename) throws FileNotFoundException {
|
||||
reader = new BufferedReader(new FileReader(filename));
|
||||
}
|
||||
|
||||
public long getLineNumber() {
|
||||
return reader.lines()
|
||||
.count();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws Exception {
|
||||
reader.close();
|
||||
System.out.println("BufferedReader resource closed");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.bealdung.java9.finalizers;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class FinalizeUnitTest {
|
||||
|
||||
@Test
|
||||
void givenFilename_whenGetLineNumber_thenReturnCorrectNumber() throws IOException {
|
||||
final File tmpFile = File.createTempFile("test", ".tmp");
|
||||
final BufferedWriter writer = new BufferedWriter(new FileWriter(tmpFile));
|
||||
writer.write("Baeldung");
|
||||
writer.close();
|
||||
|
||||
long lineNumber = 0;
|
||||
try (Resource resource = new Resource(tmpFile.getAbsolutePath())) {
|
||||
lineNumber = resource.getLineNumber();
|
||||
} catch (Exception e) {
|
||||
System.err.println("Error " + e);
|
||||
}
|
||||
|
||||
assertEquals(1, lineNumber);
|
||||
}
|
||||
}
|
|
@ -13,5 +13,4 @@ This module contains articles about the Java List collection
|
|||
- [Finding the Differences Between Two Lists in Java](https://www.baeldung.com/java-lists-difference)
|
||||
- [List vs. ArrayList in Java](https://www.baeldung.com/java-list-vs-arraylist)
|
||||
- [How to Store HashMap<String, ArrayList> Inside a List](https://www.baeldung.com/java-hashmap-inside-list)
|
||||
- [Working With a List of Lists in Java](https://www.baeldung.com/java-list-of-lists)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-collections-list-2)
|
||||
|
|
|
@ -5,4 +5,5 @@ This module contains articles about the Java List collection
|
|||
### Relevant Articles:
|
||||
- [Working With a List of Lists in Java](https://www.baeldung.com/java-list-of-lists)
|
||||
- [Reverse an ArrayList in Java](https://www.baeldung.com/java-reverse-arraylist)
|
||||
- [Sort a List Alphabetically in Java](https://www.baeldung.com/java-sort-list-alphabetically)
|
||||
- [[<-- Prev]](/core-java-modules/core-java-collections-list-3)
|
||||
|
|
|
@ -1,23 +0,0 @@
|
|||
package com.baeldung.exceptions.sneakythrows;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
|
||||
public class SneakyRunnable implements Runnable {
|
||||
|
||||
@SneakyThrows
|
||||
public void run() {
|
||||
try {
|
||||
throw new InterruptedException();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
new SneakyRunnable().run();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,25 +0,0 @@
|
|||
package com.baeldung.exceptions.sneakythrows;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class SneakyThrows {
|
||||
|
||||
|
||||
public static <E extends Throwable> void sneakyThrow(Throwable e) throws E {
|
||||
throw (E) e;
|
||||
}
|
||||
|
||||
public static void throwsSneakyIOException() {
|
||||
sneakyThrow(new IOException("sneaky"));
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
throwsSneakyIOException();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.exceptions.sneakythrows;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
|
||||
public class SneakyThrowsExamples {
|
||||
|
||||
public static <E extends Throwable> void sneakyThrow(Throwable e) throws E {
|
||||
throw (E) e;
|
||||
}
|
||||
|
||||
public static void throwSneakyIOException() {
|
||||
sneakyThrow(new IOException("sneaky"));
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
public static void throwSneakyIOExceptionUsingLombok() {
|
||||
throw new IOException("lombok sneaky");
|
||||
}
|
||||
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
package com.baeldung.exceptions.sneakythrows;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class SneakyRunnableUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCallSneakyRunnableMethod_thenThrowException() {
|
||||
try {
|
||||
new SneakyRunnable().run();
|
||||
} catch (Exception e) {
|
||||
assertEquals(InterruptedException.class, e.getStackTrace());
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.exceptions.sneakythrows;
|
||||
|
||||
import static com.baeldung.exceptions.sneakythrows.SneakyThrowsExamples.throwSneakyIOException;
|
||||
import static com.baeldung.exceptions.sneakythrows.SneakyThrowsExamples.throwSneakyIOExceptionUsingLombok;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class SneakyThrowsExamplesUnitTest {
|
||||
|
||||
@Test
|
||||
public void throwSneakyIOException_IOExceptionShouldBeThrown() {
|
||||
assertThatThrownBy(() -> throwSneakyIOException())
|
||||
.isInstanceOf(IOException.class)
|
||||
.hasMessage("sneaky")
|
||||
.hasStackTraceContaining("SneakyThrowsExamples.throwSneakyIOException");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void throwSneakyIOExceptionUsingLombok_IOExceptionShouldBeThrown() {
|
||||
assertThatThrownBy(() -> throwSneakyIOExceptionUsingLombok())
|
||||
.isInstanceOf(IOException.class)
|
||||
.hasMessage("lombok sneaky")
|
||||
.hasStackTraceContaining("SneakyThrowsExamples.throwSneakyIOExceptionUsingLombok");
|
||||
}
|
||||
}
|
|
@ -1,18 +0,0 @@
|
|||
package com.baeldung.exceptions.sneakythrows;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class SneakyThrowsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCallSneakyMethod_thenThrowSneakyException() {
|
||||
try {
|
||||
SneakyThrows.throwsSneakyIOException();
|
||||
} catch (Exception ex) {
|
||||
assertEquals("sneaky", ex.getMessage().toString());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,45 @@
|
|||
package com.baeldung.threebool;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class ThreeBooleans {
|
||||
public static boolean twoOrMoreAreTrueByLoop(boolean a, boolean b, boolean c) {
|
||||
int count = 0;
|
||||
for (boolean i : new Boolean[] { a, b, c }) {
|
||||
count += i ? 1 : 0;
|
||||
if (count >= 2)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean xOrMoreAreTrueByLoop(boolean[] booleans, int x) {
|
||||
int count = 0;
|
||||
for (boolean i : booleans) {
|
||||
count += i ? 1 : 0;
|
||||
if (count >= x)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean twoOrMoreAreTrueBySum(boolean a, boolean b, boolean c) {
|
||||
return (a ? 1 : 0) + (b ? 1 : 0) + (c ? 1 : 0) >= 2;
|
||||
}
|
||||
|
||||
public static boolean xOrMoreAreTrueBySum(Boolean[] booleans, int x) {
|
||||
return Arrays.stream(booleans).mapToInt(b -> Boolean.TRUE.equals(b) ? 1 : 0).sum() >= x;
|
||||
}
|
||||
|
||||
public static boolean twoorMoreAreTrueByKarnaughMap(boolean a, boolean b, boolean c) {
|
||||
return (c && (a || b)) || (a && b);
|
||||
}
|
||||
|
||||
public static boolean twoOrMoreAreTrueByOperators(boolean a, boolean b, boolean c) {
|
||||
return (a && b) || (a && c) || (b && c);
|
||||
}
|
||||
|
||||
public static boolean twoOrMoreAreTrueByXor(boolean a, boolean b, boolean c) {
|
||||
return a ^ b ? c : a;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung.threebool;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ThreeBooleansUnitTest {
|
||||
// @formatter:off
|
||||
private static final Map<boolean[], Boolean> TEST_CASES_AND_EXPECTED = ImmutableMap.of(
|
||||
new boolean[]{true, true, true}, true,
|
||||
new boolean[]{true, true, false}, true,
|
||||
new boolean[]{true, false, false}, false,
|
||||
new boolean[]{false, false, false}, false
|
||||
);
|
||||
// @formatter:on
|
||||
|
||||
@Test
|
||||
void given3Booleans_whenCallingTwoOrMoreAreTrueByLoop_thenGetExpectedResult() {
|
||||
TEST_CASES_AND_EXPECTED.forEach((array, expected) -> assertThat(ThreeBooleans.twoOrMoreAreTrueByLoop(array[0], array[1], array[2])).isEqualTo(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
void given3Booleans_whenCallingTwoOrMoreAreTrueByCounting_thenGetExpectedResult() {
|
||||
TEST_CASES_AND_EXPECTED.forEach((array, expected) -> assertThat(ThreeBooleans.twoOrMoreAreTrueBySum(array[0], array[1], array[2])).isEqualTo(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
void given3Booleans_whenCallingTwoOrMoreAreTrueByKarnaughMap_thenGetExpectedResult() {
|
||||
TEST_CASES_AND_EXPECTED.forEach((array, expected) -> assertThat(ThreeBooleans.twoorMoreAreTrueByKarnaughMap(array[0], array[1], array[2])).isEqualTo(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
void given3Booleans_whenCallingTwoOrMoreAreTrueByOperators_thenGetExpectedResult() {
|
||||
TEST_CASES_AND_EXPECTED.forEach((array, expected) -> assertThat(ThreeBooleans.twoOrMoreAreTrueByOperators(array[0], array[1], array[2])).isEqualTo(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
void given3Booleans_whenCallingTwoOrMoreAreTrueByXor_thenGetExpectedResult() {
|
||||
TEST_CASES_AND_EXPECTED.forEach((array, expected) -> assertThat(ThreeBooleans.twoOrMoreAreTrueByXor(array[0], array[1], array[2])).isEqualTo(expected));
|
||||
}
|
||||
|
||||
}
|
|
@ -47,6 +47,25 @@
|
|||
<compilerArgument>-parameters</compilerArgument>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<version>0.8.8</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>report</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.reflection.privatemethods;
|
||||
|
||||
public class Utils {
|
||||
|
||||
public static Integer validateAndDouble(Integer input) {
|
||||
if (input == null) {
|
||||
throw new IllegalArgumentException("input should not be null");
|
||||
}
|
||||
return doubleInteger(input);
|
||||
}
|
||||
|
||||
private static Integer doubleInteger(Integer input) {
|
||||
if (input == null) {
|
||||
return null;
|
||||
}
|
||||
return 2 * input;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package com.baeldung.reflection.privatemethods;
|
||||
|
||||
import static com.baeldung.reflection.privatemethods.Utils.validateAndDouble;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class UtilsUnitTest {
|
||||
|
||||
// Let's start with the tests of the public API
|
||||
@Test
|
||||
void givenNull_WhenValidateAndDouble_ThenThrows() {
|
||||
assertThrows(IllegalArgumentException.class, () -> validateAndDouble(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenANonNullInteger_WhenValidateAndDouble_ThenDoublesIt() {
|
||||
assertEquals(4, validateAndDouble(2));
|
||||
}
|
||||
|
||||
// Further on, let's test the private method
|
||||
@Test
|
||||
void givenNull_WhenDoubleInteger_ThenNull() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
|
||||
assertEquals(null, getDoubleIntegerMethod().invoke(null, new Integer[] { null }));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenANonNullInteger_WhenDoubleInteger_ThenDoubleIt() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
|
||||
assertEquals(74, getDoubleIntegerMethod().invoke(null, 37));
|
||||
}
|
||||
|
||||
private Method getDoubleIntegerMethod() throws NoSuchMethodException {
|
||||
Method method = Utils.class.getDeclaredMethod("doubleInteger", Integer.class);
|
||||
method.setAccessible(true);
|
||||
return method;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,73 @@
|
|||
package com.baeldung.stringtointeger;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StringToIntegerUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenValidNumericStringIsPassed_thenShouldConvertToPrimitiveInt() {
|
||||
assertEquals(11, Integer.parseInt("11"));
|
||||
assertEquals(11, Integer.parseInt("+11"));
|
||||
assertEquals(-11, Integer.parseInt("-11"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidNumericStringWithRadixIsPassed_thenShouldConvertToPrimitiveInt() {
|
||||
assertEquals(17, Integer.parseInt("11", 16));
|
||||
assertEquals(10, Integer.parseInt("A", 16));
|
||||
assertEquals(7, Integer.parseInt("7", 8));
|
||||
}
|
||||
|
||||
// public static int parseInt(CharSequence s, int beginIndex, int endIndex, int radix) throws NumberFormatException
|
||||
// This method is available in JDK 9 and above
|
||||
// @Test
|
||||
// public void whenValidNumericStringWithRadixAndSubstringIsPassed_thenShouldConvertToPrimitiveInt() {
|
||||
// assertEquals(5, Integer.parseInt("100101", 3, 6, 2));
|
||||
// assertEquals(101, Integer.parseInt("100101", 3, 6, 10));
|
||||
// }
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void whenInValidNumericStringIsPassed_thenShouldThrowNumberFormatException() {
|
||||
int number = Integer.parseInt("abcd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidNumericStringIsPassed_thenShouldConvertToInteger() {
|
||||
Integer expectedNumber = 11;
|
||||
Integer expectedNegativeNumber = -11;
|
||||
|
||||
assertEquals(expectedNumber, Integer.valueOf("11"));
|
||||
assertEquals(expectedNumber, Integer.valueOf("+11"));
|
||||
assertEquals(expectedNegativeNumber, Integer.valueOf("-11"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNumberIsPassed_thenShouldConvertToInteger() {
|
||||
Integer expectedNumber = 11;
|
||||
Integer expectedNegativeNumber = -11;
|
||||
Integer expectedUnicodeValue = 65;
|
||||
|
||||
assertEquals(expectedNumber, Integer.valueOf(11));
|
||||
assertEquals(expectedNumber, Integer.valueOf(+11));
|
||||
assertEquals(expectedNegativeNumber, Integer.valueOf(-11));
|
||||
assertEquals(expectedUnicodeValue, Integer.valueOf('A'));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenValidNumericStringWithRadixIsPassed_thenShouldConvertToInetger() {
|
||||
Integer expectedNumber1 = 17;
|
||||
Integer expectedNumber2 = 10;
|
||||
Integer expectedNumber3 = 7;
|
||||
|
||||
assertEquals(expectedNumber1, Integer.valueOf("11", 16));
|
||||
assertEquals(expectedNumber2, Integer.valueOf("A", 16));
|
||||
assertEquals(expectedNumber3, Integer.valueOf("7", 8));
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
public void whenInvalidValueOfNumericStringPassed_thenShouldThrowException() {
|
||||
Integer number = Integer.valueOf("abcd");
|
||||
}
|
||||
}
|
|
@ -13,4 +13,4 @@ This module contains articles about numbers in Java.
|
|||
- [Binary Numbers in Java](https://www.baeldung.com/java-binary-numbers)
|
||||
- [Finding the Least Common Multiple in Java](https://www.baeldung.com/java-least-common-multiple)
|
||||
- [Binary Numbers in Java](https://www.baeldung.com/java-binary-numbers)
|
||||
- More articles: [[<-- prev]](/java-numbers) [[next -->]](/java-numbers-3)
|
||||
- More articles: [[<-- prev]](../java-numbers) [[next -->]](../java-numbers-3)
|
|
@ -9,10 +9,9 @@
|
|||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
|
@ -1,140 +1,140 @@
|
|||
package com.baeldung.binarynumbers;
|
||||
|
||||
public class BinaryNumbers {
|
||||
|
||||
/**
|
||||
* This method takes a decimal number and convert it into a binary number.
|
||||
* example:- input:10, output:1010
|
||||
*
|
||||
* @param decimalNumber
|
||||
* @return binary number
|
||||
*/
|
||||
public Integer convertDecimalToBinary(Integer decimalNumber) {
|
||||
|
||||
if (decimalNumber == 0) {
|
||||
return decimalNumber;
|
||||
}
|
||||
|
||||
StringBuilder binaryNumber = new StringBuilder();
|
||||
Integer quotient = decimalNumber;
|
||||
|
||||
while (quotient > 0) {
|
||||
|
||||
int remainder = quotient % 2;
|
||||
binaryNumber.append(remainder);
|
||||
quotient /= 2;
|
||||
}
|
||||
|
||||
binaryNumber = binaryNumber.reverse();
|
||||
return Integer.valueOf(binaryNumber.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* This method takes a binary number and convert it into a decimal number.
|
||||
* example:- input:101, output:5
|
||||
*
|
||||
* @param binary number
|
||||
* @return decimal Number
|
||||
*/
|
||||
public Integer convertBinaryToDecimal(Integer binaryNumber) {
|
||||
|
||||
Integer decimalNumber = 0;
|
||||
Integer base = 1;
|
||||
|
||||
while (binaryNumber > 0) {
|
||||
|
||||
int lastDigit = binaryNumber % 10;
|
||||
binaryNumber = binaryNumber / 10;
|
||||
|
||||
decimalNumber += lastDigit * base;
|
||||
base = base * 2;
|
||||
}
|
||||
return decimalNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method accepts two binary numbers and returns sum of input numbers.
|
||||
* Example:- firstNum: 101, secondNum: 100, output: 1001
|
||||
*
|
||||
* @param firstNum
|
||||
* @param secondNum
|
||||
* @return addition of input numbers
|
||||
*/
|
||||
public Integer addBinaryNumber(Integer firstNum, Integer secondNum) {
|
||||
|
||||
StringBuilder output = new StringBuilder();
|
||||
|
||||
int carry = 0;
|
||||
int temp;
|
||||
|
||||
while (firstNum != 0 || secondNum != 0) {
|
||||
|
||||
temp = (firstNum % 10 + secondNum % 10 + carry) % 2;
|
||||
output.append(temp);
|
||||
|
||||
carry = (firstNum % 10 + secondNum % 10 + carry) / 2;
|
||||
|
||||
firstNum = firstNum / 10;
|
||||
secondNum = secondNum / 10;
|
||||
}
|
||||
|
||||
if (carry != 0) {
|
||||
output.append(carry);
|
||||
}
|
||||
|
||||
return Integer.valueOf(output.reverse()
|
||||
.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* This method takes two binary number as input and subtract second number from the first number.
|
||||
* example:- firstNum: 1000, secondNum: 11, output: 101
|
||||
* @param firstNum
|
||||
* @param secondNum
|
||||
* @return Result of subtraction of secondNum from first
|
||||
*/
|
||||
public Integer substractBinaryNumber(Integer firstNum, Integer secondNum) {
|
||||
|
||||
int onesComplement = Integer.valueOf(getOnesComplement(secondNum));
|
||||
StringBuilder output = new StringBuilder();
|
||||
int carry = 0;
|
||||
int temp;
|
||||
|
||||
while (firstNum != 0 || onesComplement != 0) {
|
||||
|
||||
temp = (firstNum % 10 + onesComplement % 10 + carry) % 2;
|
||||
output.append(temp);
|
||||
|
||||
carry = (firstNum % 10 + onesComplement % 10 + carry) / 2;
|
||||
|
||||
firstNum = firstNum / 10;
|
||||
onesComplement = onesComplement / 10;
|
||||
}
|
||||
|
||||
String additionOfFirstNumAndOnesComplement = output.reverse()
|
||||
.toString();
|
||||
|
||||
if (carry == 1) {
|
||||
return addBinaryNumber(Integer.valueOf(additionOfFirstNumAndOnesComplement), carry);
|
||||
} else {
|
||||
return getOnesComplement(Integer.valueOf(additionOfFirstNumAndOnesComplement));
|
||||
}
|
||||
}
|
||||
|
||||
public Integer getOnesComplement(Integer num) {
|
||||
|
||||
StringBuilder onesComplement = new StringBuilder();
|
||||
while (num > 0) {
|
||||
int lastDigit = num % 10;
|
||||
if (lastDigit == 0) {
|
||||
onesComplement.append(1);
|
||||
} else {
|
||||
onesComplement.append(0);
|
||||
}
|
||||
num = num / 10;
|
||||
}
|
||||
return Integer.valueOf(onesComplement.reverse()
|
||||
.toString());
|
||||
}
|
||||
|
||||
package com.baeldung.binarynumbers;
|
||||
|
||||
public class BinaryNumbers {
|
||||
|
||||
/**
|
||||
* This method takes a decimal number and convert it into a binary number.
|
||||
* example:- input:10, output:1010
|
||||
*
|
||||
* @param decimalNumber
|
||||
* @return binary number
|
||||
*/
|
||||
public Integer convertDecimalToBinary(Integer decimalNumber) {
|
||||
|
||||
if (decimalNumber == 0) {
|
||||
return decimalNumber;
|
||||
}
|
||||
|
||||
StringBuilder binaryNumber = new StringBuilder();
|
||||
Integer quotient = decimalNumber;
|
||||
|
||||
while (quotient > 0) {
|
||||
|
||||
int remainder = quotient % 2;
|
||||
binaryNumber.append(remainder);
|
||||
quotient /= 2;
|
||||
}
|
||||
|
||||
binaryNumber = binaryNumber.reverse();
|
||||
return Integer.valueOf(binaryNumber.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* This method takes a binary number and convert it into a decimal number.
|
||||
* example:- input:101, output:5
|
||||
*
|
||||
* @param binary number
|
||||
* @return decimal Number
|
||||
*/
|
||||
public Integer convertBinaryToDecimal(Integer binaryNumber) {
|
||||
|
||||
Integer decimalNumber = 0;
|
||||
Integer base = 1;
|
||||
|
||||
while (binaryNumber > 0) {
|
||||
|
||||
int lastDigit = binaryNumber % 10;
|
||||
binaryNumber = binaryNumber / 10;
|
||||
|
||||
decimalNumber += lastDigit * base;
|
||||
base = base * 2;
|
||||
}
|
||||
return decimalNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method accepts two binary numbers and returns sum of input numbers.
|
||||
* Example:- firstNum: 101, secondNum: 100, output: 1001
|
||||
*
|
||||
* @param firstNum
|
||||
* @param secondNum
|
||||
* @return addition of input numbers
|
||||
*/
|
||||
public Integer addBinaryNumber(Integer firstNum, Integer secondNum) {
|
||||
|
||||
StringBuilder output = new StringBuilder();
|
||||
|
||||
int carry = 0;
|
||||
int temp;
|
||||
|
||||
while (firstNum != 0 || secondNum != 0) {
|
||||
|
||||
temp = (firstNum % 10 + secondNum % 10 + carry) % 2;
|
||||
output.append(temp);
|
||||
|
||||
carry = (firstNum % 10 + secondNum % 10 + carry) / 2;
|
||||
|
||||
firstNum = firstNum / 10;
|
||||
secondNum = secondNum / 10;
|
||||
}
|
||||
|
||||
if (carry != 0) {
|
||||
output.append(carry);
|
||||
}
|
||||
|
||||
return Integer.valueOf(output.reverse()
|
||||
.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* This method takes two binary number as input and subtract second number from the first number.
|
||||
* example:- firstNum: 1000, secondNum: 11, output: 101
|
||||
* @param firstNum
|
||||
* @param secondNum
|
||||
* @return Result of subtraction of secondNum from first
|
||||
*/
|
||||
public Integer substractBinaryNumber(Integer firstNum, Integer secondNum) {
|
||||
|
||||
int onesComplement = Integer.valueOf(getOnesComplement(secondNum));
|
||||
StringBuilder output = new StringBuilder();
|
||||
int carry = 0;
|
||||
int temp;
|
||||
|
||||
while (firstNum != 0 || onesComplement != 0) {
|
||||
|
||||
temp = (firstNum % 10 + onesComplement % 10 + carry) % 2;
|
||||
output.append(temp);
|
||||
|
||||
carry = (firstNum % 10 + onesComplement % 10 + carry) / 2;
|
||||
|
||||
firstNum = firstNum / 10;
|
||||
onesComplement = onesComplement / 10;
|
||||
}
|
||||
|
||||
String additionOfFirstNumAndOnesComplement = output.reverse()
|
||||
.toString();
|
||||
|
||||
if (carry == 1) {
|
||||
return addBinaryNumber(Integer.valueOf(additionOfFirstNumAndOnesComplement), carry);
|
||||
} else {
|
||||
return getOnesComplement(Integer.valueOf(additionOfFirstNumAndOnesComplement));
|
||||
}
|
||||
}
|
||||
|
||||
public Integer getOnesComplement(Integer num) {
|
||||
|
||||
StringBuilder onesComplement = new StringBuilder();
|
||||
while (num > 0) {
|
||||
int lastDigit = num % 10;
|
||||
if (lastDigit == 0) {
|
||||
onesComplement.append(1);
|
||||
} else {
|
||||
onesComplement.append(0);
|
||||
}
|
||||
num = num / 10;
|
||||
}
|
||||
return Integer.valueOf(onesComplement.reverse()
|
||||
.toString());
|
||||
}
|
||||
|
||||
}
|
|
@ -1,73 +1,73 @@
|
|||
package com.baeldung.binarynumbers;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class BinaryNumbersUnitTest {
|
||||
|
||||
private BinaryNumbers binaryNumbers = new BinaryNumbers();
|
||||
|
||||
@Test
|
||||
public void given_decimalNumber_then_returnBinaryNumber() {
|
||||
assertEquals(Integer.valueOf(1000), binaryNumbers.convertDecimalToBinary(8));
|
||||
assertEquals(Integer.valueOf(10100), binaryNumbers.convertDecimalToBinary(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_decimalNumber_then_convertToBinaryNumber() {
|
||||
assertEquals("1000", Integer.toBinaryString(8));
|
||||
assertEquals("10100", Integer.toBinaryString(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_binaryNumber_then_ConvertToDecimalNumber() {
|
||||
assertEquals(8, Integer.parseInt("1000", 2));
|
||||
assertEquals(20, Integer.parseInt("10100", 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_binaryNumber_then_returnDecimalNumber() {
|
||||
assertEquals(Integer.valueOf(8), binaryNumbers.convertBinaryToDecimal(1000));
|
||||
assertEquals(Integer.valueOf(20), binaryNumbers.convertBinaryToDecimal(10100));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_twoBinaryNumber_then_returnAddition() {
|
||||
// adding 4 and 10
|
||||
assertEquals(Integer.valueOf(1110), binaryNumbers.addBinaryNumber(100, 1010));
|
||||
|
||||
// adding 26 and 14
|
||||
assertEquals(Integer.valueOf(101000), binaryNumbers.addBinaryNumber(11010, 1110));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_twoBinaryNumber_then_returnSubtraction() {
|
||||
// subtracting 16 from 25
|
||||
assertEquals(Integer.valueOf(1001), binaryNumbers.substractBinaryNumber(11001, 10000));
|
||||
|
||||
// subtracting 29 from 16, the output here is negative
|
||||
assertEquals(Integer.valueOf(1101), binaryNumbers.substractBinaryNumber(10000, 11101));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_binaryLiteral_thenReturnDecimalValue() {
|
||||
|
||||
byte five = 0b101;
|
||||
assertEquals((byte) 5, five);
|
||||
|
||||
short three = 0b11;
|
||||
assertEquals((short) 3, three);
|
||||
|
||||
int nine = 0B1001;
|
||||
assertEquals(9, nine);
|
||||
|
||||
long twentyNine = 0B11101;
|
||||
assertEquals(29, twentyNine);
|
||||
|
||||
int minusThirtySeven = -0B100101;
|
||||
assertEquals(-37, minusThirtySeven);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
package com.baeldung.binarynumbers;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class BinaryNumbersUnitTest {
|
||||
|
||||
private BinaryNumbers binaryNumbers = new BinaryNumbers();
|
||||
|
||||
@Test
|
||||
public void given_decimalNumber_then_returnBinaryNumber() {
|
||||
assertEquals(Integer.valueOf(1000), binaryNumbers.convertDecimalToBinary(8));
|
||||
assertEquals(Integer.valueOf(10100), binaryNumbers.convertDecimalToBinary(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_decimalNumber_then_convertToBinaryNumber() {
|
||||
assertEquals("1000", Integer.toBinaryString(8));
|
||||
assertEquals("10100", Integer.toBinaryString(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_binaryNumber_then_ConvertToDecimalNumber() {
|
||||
assertEquals(8, Integer.parseInt("1000", 2));
|
||||
assertEquals(20, Integer.parseInt("10100", 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_binaryNumber_then_returnDecimalNumber() {
|
||||
assertEquals(Integer.valueOf(8), binaryNumbers.convertBinaryToDecimal(1000));
|
||||
assertEquals(Integer.valueOf(20), binaryNumbers.convertBinaryToDecimal(10100));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_twoBinaryNumber_then_returnAddition() {
|
||||
// adding 4 and 10
|
||||
assertEquals(Integer.valueOf(1110), binaryNumbers.addBinaryNumber(100, 1010));
|
||||
|
||||
// adding 26 and 14
|
||||
assertEquals(Integer.valueOf(101000), binaryNumbers.addBinaryNumber(11010, 1110));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_twoBinaryNumber_then_returnSubtraction() {
|
||||
// subtracting 16 from 25
|
||||
assertEquals(Integer.valueOf(1001), binaryNumbers.substractBinaryNumber(11001, 10000));
|
||||
|
||||
// subtracting 29 from 16, the output here is negative
|
||||
assertEquals(Integer.valueOf(1101), binaryNumbers.substractBinaryNumber(10000, 11101));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given_binaryLiteral_thenReturnDecimalValue() {
|
||||
|
||||
byte five = 0b101;
|
||||
assertEquals((byte) 5, five);
|
||||
|
||||
short three = 0b11;
|
||||
assertEquals((short) 3, three);
|
||||
|
||||
int nine = 0B1001;
|
||||
assertEquals(9, nine);
|
||||
|
||||
long twentyNine = 0B11101;
|
||||
assertEquals(29, twentyNine);
|
||||
|
||||
int minusThirtySeven = -0B100101;
|
||||
assertEquals(-37, minusThirtySeven);
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -14,4 +14,4 @@ This module contains articles about numbers in Java.
|
|||
- [Print an Integer in Binary Format in Java](https://www.baeldung.com/java-print-integer-binary)
|
||||
- [Number Formatting in Java](https://www.baeldung.com/java-number-formatting)
|
||||
- [Division by Zero in Java: Exception, Infinity, or Not a Number](https://www.baeldung.com/java-division-by-zero)
|
||||
- More articles: [[<-- prev]](/java-numbers-2)
|
||||
- More articles: [[<-- prev]](../java-numbers-2) [[next -->]](../java-numbers-4)
|
|
@ -7,10 +7,9 @@
|
|||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
|
@ -9,3 +9,5 @@
|
|||
- [Convert boolean to int in Java](https://www.baeldung.com/java-boolean-to-int)
|
||||
- [Generate a Random Value From an Enum](https://www.baeldung.com/java-enum-random-value)
|
||||
- [Reverse a Number in Java](https://www.baeldung.com/java-reverse-number)
|
||||
- [Check if BigDecimal Value Is Zero](https://www.baeldung.com/java-bigdecimal-zero)
|
||||
- More articles: [[<-- prev]](../java-numbers-3)
|
|
@ -7,10 +7,9 @@
|
|||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.bigdecimalzero;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class BigDecimalZeroChkUnitTest {
|
||||
private static final BigDecimal BD1 = new BigDecimal("0");
|
||||
private static final BigDecimal BD2 = new BigDecimal("0.0000");
|
||||
|
||||
@Test
|
||||
void givenBD_whenCheckedWithEquals_shouldCheckedAsZero() {
|
||||
assertThat(BigDecimal.ZERO.equals(BD1)).isTrue();
|
||||
|
||||
// in the article, we show the failure of the assertion below
|
||||
// assertThat(BigDecimal.ZERO.equals(BD2)).isTrue();
|
||||
|
||||
assertThat(BigDecimal.ZERO.equals(BD2)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBD_whenCheckedWithCompareTo_shouldCheckedAsZero() {
|
||||
assertThat(BigDecimal.ZERO.compareTo(BD1)).isSameAs(0);
|
||||
assertThat(BigDecimal.ZERO.compareTo(BD2)).isSameAs(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBD_whenCheckedWithSignum_shouldCheckedAsZero() {
|
||||
assertThat(BD1.signum()).isSameAs(0);
|
||||
assertThat(BD2.signum()).isSameAs(0);
|
||||
}
|
||||
}
|
|
@ -13,4 +13,4 @@ This module contains articles about numbers in Java.
|
|||
- [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string)
|
||||
- [Changing the Order in a Sum Operation Can Produce Different Results?](https://www.baeldung.com/java-floating-point-sum-order)
|
||||
- [Using Math.sin with Degrees](https://www.baeldung.com/java-math-sin-degrees)
|
||||
- More articles: [[next -->]](/../java-numbers-2)
|
||||
- More articles: [[next -->]](../java-numbers-2)
|
|
@ -9,10 +9,9 @@
|
|||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<groupId>com.baeldung.core-java-modules</groupId>
|
||||
<artifactId>core-java-modules</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
|
@ -1,51 +1,51 @@
|
|||
package com.baeldung.maths;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class FloatingPointArithmetic {
|
||||
public static void main(String[] args) {
|
||||
|
||||
double a = 13.22;
|
||||
double b = 4.88;
|
||||
double c = 21.45;
|
||||
|
||||
System.out.println("a = " + a);
|
||||
System.out.println("b = " + b);
|
||||
System.out.println("c = " + c);
|
||||
|
||||
double sum_ab = a + b;
|
||||
System.out.println("a + b = " + sum_ab);
|
||||
|
||||
double abc = a + b + c;
|
||||
System.out.println("a + b + c = " + abc);
|
||||
|
||||
double ab_c = sum_ab + c;
|
||||
System.out.println("ab + c = " + ab_c);
|
||||
|
||||
double sum_ac = a + c;
|
||||
System.out.println("a + c = " + sum_ac);
|
||||
|
||||
double acb = a + c + b;
|
||||
System.out.println("a + c + b = " + acb);
|
||||
|
||||
double ac_b = sum_ac + b;
|
||||
System.out.println("ac + b = " + ac_b);
|
||||
|
||||
double ab = 18.1;
|
||||
double ac = 34.67;
|
||||
double sum_ab_c = ab + c;
|
||||
double sum_ac_b = ac + b;
|
||||
System.out.println("ab + c = " + sum_ab_c);
|
||||
System.out.println("ac + b = " + sum_ac_b);
|
||||
|
||||
BigDecimal d = new BigDecimal(String.valueOf(a));
|
||||
BigDecimal e = new BigDecimal(String.valueOf(b));
|
||||
BigDecimal f = new BigDecimal(String.valueOf(c));
|
||||
|
||||
BigDecimal def = d.add(e).add(f);
|
||||
BigDecimal dfe = d.add(f).add(e);
|
||||
|
||||
System.out.println("d + e + f = " + def);
|
||||
System.out.println("d + f + e = " + dfe);
|
||||
}
|
||||
}
|
||||
package com.baeldung.maths;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class FloatingPointArithmetic {
|
||||
public static void main(String[] args) {
|
||||
|
||||
double a = 13.22;
|
||||
double b = 4.88;
|
||||
double c = 21.45;
|
||||
|
||||
System.out.println("a = " + a);
|
||||
System.out.println("b = " + b);
|
||||
System.out.println("c = " + c);
|
||||
|
||||
double sum_ab = a + b;
|
||||
System.out.println("a + b = " + sum_ab);
|
||||
|
||||
double abc = a + b + c;
|
||||
System.out.println("a + b + c = " + abc);
|
||||
|
||||
double ab_c = sum_ab + c;
|
||||
System.out.println("ab + c = " + ab_c);
|
||||
|
||||
double sum_ac = a + c;
|
||||
System.out.println("a + c = " + sum_ac);
|
||||
|
||||
double acb = a + c + b;
|
||||
System.out.println("a + c + b = " + acb);
|
||||
|
||||
double ac_b = sum_ac + b;
|
||||
System.out.println("ac + b = " + ac_b);
|
||||
|
||||
double ab = 18.1;
|
||||
double ac = 34.67;
|
||||
double sum_ab_c = ab + c;
|
||||
double sum_ac_b = ac + b;
|
||||
System.out.println("ab + c = " + sum_ab_c);
|
||||
System.out.println("ac + b = " + sum_ac_b);
|
||||
|
||||
BigDecimal d = new BigDecimal(String.valueOf(a));
|
||||
BigDecimal e = new BigDecimal(String.valueOf(b));
|
||||
BigDecimal f = new BigDecimal(String.valueOf(c));
|
||||
|
||||
BigDecimal def = d.add(e).add(f);
|
||||
BigDecimal dfe = d.add(f).add(e);
|
||||
|
||||
System.out.println("d + e + f = " + def);
|
||||
System.out.println("d + f + e = " + dfe);
|
||||
}
|
||||
}
|
|
@ -1,67 +1,67 @@
|
|||
package com.baeldung.numberofdigits;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
|
||||
public class Benchmarking {
|
||||
public static void main(String[] args) throws RunnerException, IOException {
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
}
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class ExecutionPlan {
|
||||
public int number = Integer.MAX_VALUE;
|
||||
public int length = 0;
|
||||
public NumberOfDigits numberOfDigits= new NumberOfDigits();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void stringBasedSolution(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.stringBasedSolution(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void logarithmicApproach(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.logarithmicApproach(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void repeatedMultiplication(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.repeatedMultiplication(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void shiftOperators(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.shiftOperators(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void dividingWithPowersOf2(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.dividingWithPowersOf2(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void divideAndConquer(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.divideAndConquer(plan.number);
|
||||
}
|
||||
}
|
||||
package com.baeldung.numberofdigits;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
|
||||
public class Benchmarking {
|
||||
public static void main(String[] args) throws RunnerException, IOException {
|
||||
org.openjdk.jmh.Main.main(args);
|
||||
}
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class ExecutionPlan {
|
||||
public int number = Integer.MAX_VALUE;
|
||||
public int length = 0;
|
||||
public NumberOfDigits numberOfDigits= new NumberOfDigits();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void stringBasedSolution(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.stringBasedSolution(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void logarithmicApproach(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.logarithmicApproach(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void repeatedMultiplication(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.repeatedMultiplication(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void shiftOperators(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.shiftOperators(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void dividingWithPowersOf2(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.dividingWithPowersOf2(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void divideAndConquer(ExecutionPlan plan) {
|
||||
plan.length = plan.numberOfDigits.divideAndConquer(plan.number);
|
||||
}
|
||||
}
|
|
@ -1,97 +1,97 @@
|
|||
package com.baeldung.numberofdigits;
|
||||
|
||||
public class NumberOfDigits {
|
||||
public int stringBasedSolution(int number) {
|
||||
int length = String.valueOf(number).length();
|
||||
return length;
|
||||
}
|
||||
|
||||
public int logarithmicApproach(int number) {
|
||||
int length = (int) Math.log10(number) + 1;
|
||||
return length;
|
||||
}
|
||||
|
||||
public int repeatedMultiplication(int number) {
|
||||
int length = 0;
|
||||
long temp = 1;
|
||||
while(temp <= number) {
|
||||
length++;
|
||||
temp *= 10;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
public int shiftOperators(int number) {
|
||||
int length = 0;
|
||||
long temp = 1;
|
||||
while(temp <= number) {
|
||||
length++;
|
||||
temp = (temp << 3) + (temp << 1);
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
public int dividingWithPowersOf2(int number) {
|
||||
int length = 1;
|
||||
if (number >= 100000000) {
|
||||
length += 8;
|
||||
number /= 100000000;
|
||||
}
|
||||
if (number >= 10000) {
|
||||
length += 4;
|
||||
number /= 10000;
|
||||
}
|
||||
if (number >= 100) {
|
||||
length += 2;
|
||||
number /= 100;
|
||||
}
|
||||
if (number >= 10) {
|
||||
length += 1;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
public int divideAndConquer(int number) {
|
||||
if (number < 100000){
|
||||
// 5 digits or less
|
||||
if (number < 100){
|
||||
// 1 or 2
|
||||
if (number < 10)
|
||||
return 1;
|
||||
else
|
||||
return 2;
|
||||
}else{
|
||||
// 3 to 5 digits
|
||||
if (number < 1000)
|
||||
return 3;
|
||||
else{
|
||||
// 4 or 5 digits
|
||||
if (number < 10000)
|
||||
return 4;
|
||||
else
|
||||
return 5;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 6 digits or more
|
||||
if (number < 10000000) {
|
||||
// 6 or 7 digits
|
||||
if (number < 1000000)
|
||||
return 6;
|
||||
else
|
||||
return 7;
|
||||
} else {
|
||||
// 8 to 10 digits
|
||||
if (number < 100000000)
|
||||
return 8;
|
||||
else {
|
||||
// 9 or 10 digits
|
||||
if (number < 1000000000)
|
||||
return 9;
|
||||
else
|
||||
return 10;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
package com.baeldung.numberofdigits;
|
||||
|
||||
public class NumberOfDigits {
|
||||
public int stringBasedSolution(int number) {
|
||||
int length = String.valueOf(number).length();
|
||||
return length;
|
||||
}
|
||||
|
||||
public int logarithmicApproach(int number) {
|
||||
int length = (int) Math.log10(number) + 1;
|
||||
return length;
|
||||
}
|
||||
|
||||
public int repeatedMultiplication(int number) {
|
||||
int length = 0;
|
||||
long temp = 1;
|
||||
while(temp <= number) {
|
||||
length++;
|
||||
temp *= 10;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
public int shiftOperators(int number) {
|
||||
int length = 0;
|
||||
long temp = 1;
|
||||
while(temp <= number) {
|
||||
length++;
|
||||
temp = (temp << 3) + (temp << 1);
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
public int dividingWithPowersOf2(int number) {
|
||||
int length = 1;
|
||||
if (number >= 100000000) {
|
||||
length += 8;
|
||||
number /= 100000000;
|
||||
}
|
||||
if (number >= 10000) {
|
||||
length += 4;
|
||||
number /= 10000;
|
||||
}
|
||||
if (number >= 100) {
|
||||
length += 2;
|
||||
number /= 100;
|
||||
}
|
||||
if (number >= 10) {
|
||||
length += 1;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
|
||||
public int divideAndConquer(int number) {
|
||||
if (number < 100000){
|
||||
// 5 digits or less
|
||||
if (number < 100){
|
||||
// 1 or 2
|
||||
if (number < 10)
|
||||
return 1;
|
||||
else
|
||||
return 2;
|
||||
}else{
|
||||
// 3 to 5 digits
|
||||
if (number < 1000)
|
||||
return 3;
|
||||
else{
|
||||
// 4 or 5 digits
|
||||
if (number < 10000)
|
||||
return 4;
|
||||
else
|
||||
return 5;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 6 digits or more
|
||||
if (number < 10000000) {
|
||||
// 6 or 7 digits
|
||||
if (number < 1000000)
|
||||
return 6;
|
||||
else
|
||||
return 7;
|
||||
} else {
|
||||
// 8 to 10 digits
|
||||
if (number < 100000000)
|
||||
return 8;
|
||||
else {
|
||||
// 9 or 10 digits
|
||||
if (number < 1000000000)
|
||||
return 9;
|
||||
else
|
||||
return 10;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,35 +1,35 @@
|
|||
package com.baeldung.numberofdigits;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
public class NumberOfDigitsDriver {
|
||||
private static NumberOfDigits numberOfDigits;
|
||||
|
||||
private static Logger LOG = Logger.getLogger(NumberOfDigitsDriver.class);
|
||||
|
||||
static {
|
||||
numberOfDigits = new NumberOfDigits();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
LOG.info("Testing all methods...");
|
||||
|
||||
long length = numberOfDigits.stringBasedSolution(602);
|
||||
LOG.info("String Based Solution : " + length);
|
||||
|
||||
length = numberOfDigits.logarithmicApproach(602);
|
||||
LOG.info("Logarithmic Approach : " + length);
|
||||
|
||||
length = numberOfDigits.repeatedMultiplication(602);
|
||||
LOG.info("Repeated Multiplication : " + length);
|
||||
|
||||
length = numberOfDigits.shiftOperators(602);
|
||||
LOG.info("Shift Operators : " + length);
|
||||
|
||||
length = numberOfDigits.dividingWithPowersOf2(602);
|
||||
LOG.info("Dividing with Powers of 2 : " + length);
|
||||
|
||||
length = numberOfDigits.divideAndConquer(602);
|
||||
LOG.info("Divide And Conquer : " + length);
|
||||
}
|
||||
package com.baeldung.numberofdigits;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
public class NumberOfDigitsDriver {
|
||||
private static NumberOfDigits numberOfDigits;
|
||||
|
||||
private static Logger LOG = Logger.getLogger(NumberOfDigitsDriver.class);
|
||||
|
||||
static {
|
||||
numberOfDigits = new NumberOfDigits();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
LOG.info("Testing all methods...");
|
||||
|
||||
long length = numberOfDigits.stringBasedSolution(602);
|
||||
LOG.info("String Based Solution : " + length);
|
||||
|
||||
length = numberOfDigits.logarithmicApproach(602);
|
||||
LOG.info("Logarithmic Approach : " + length);
|
||||
|
||||
length = numberOfDigits.repeatedMultiplication(602);
|
||||
LOG.info("Repeated Multiplication : " + length);
|
||||
|
||||
length = numberOfDigits.shiftOperators(602);
|
||||
LOG.info("Shift Operators : " + length);
|
||||
|
||||
length = numberOfDigits.dividingWithPowersOf2(602);
|
||||
LOG.info("Dividing with Powers of 2 : " + length);
|
||||
|
||||
length = numberOfDigits.divideAndConquer(602);
|
||||
LOG.info("Divide And Conquer : " + length);
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue