Merge branch 'master' of https://github.com/eugenp/tutorials into JAVA-3060

This commit is contained in:
chaos2418
2022-01-05 18:46:23 +05:30
340 changed files with 4434 additions and 800 deletions
+1
View File
@@ -6,4 +6,5 @@ This module contains articles about Apache POI
- [Adding a Column to an Excel Sheet Using Apache POI](https://www.baeldung.com/java-excel-add-column)
- [Add an Image to a Cell in an Excel File With Java](https://www.baeldung.com/java-add-image-excel)
- [Numeric Format Using POI](https://www.baeldung.com/apache-poi-numeric-format)
- More articles: [[<-- prev]](/apache-poi)
@@ -0,0 +1,19 @@
package com.baeldung.poi.excel.newcolumn.numeric;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
public class ExcelNumericFormat {
public static void applyNumericFormat(Workbook outWorkbook, Row row, Cell cell, Double value, String styleFormat) {
CellStyle style = outWorkbook.createCellStyle();
DataFormat format = outWorkbook.createDataFormat();
style.setDataFormat(format.getFormat(styleFormat));
cell.setCellValue(value);
cell.setCellStyle(style);
}
}
@@ -0,0 +1,105 @@
package com.baeldung.poi.excel.newcolumn.numeric;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
public class NumberCellValueUnitTest {
@Test
public void decimalDisplay_whenAddedDouble_thenNumericCellCreated() throws IOException {
File file = new File("number_test.xlsx");
try (Workbook outWorkbook = new XSSFWorkbook()) {
Sheet sheet = outWorkbook.createSheet("Numeric Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
ExcelNumericFormat.applyNumericFormat(outWorkbook, row, cell, 10.251, "0.00");
FileOutputStream fileOut = new FileOutputStream(file);
outWorkbook.write(fileOut);
fileOut.close();
}
try (Workbook inWorkbook = new XSSFWorkbook("number_test.xlsx")) {
Sheet sheet = inWorkbook.cloneSheet(0);
Row row = sheet.getRow(0);
Assertions.assertEquals(10.251, row.getCell(0)
.getNumericCellValue());
file.delete();
}
}
@Test
public void decimalRoundedDisplay_whenAddedDouble_thenNumericCellCreated() throws IOException {
File file = new File("number_test.xlsx");
try (Workbook outWorkbook = new XSSFWorkbook()) {
Sheet sheet = outWorkbook.createSheet("Numeric Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
ExcelNumericFormat.applyNumericFormat(outWorkbook, row, cell, 10.251123, "#,##0.0000");
FileOutputStream fileOut = new FileOutputStream(file);
outWorkbook.write(fileOut);
fileOut.close();
}
try (Workbook inWorkbook = new XSSFWorkbook("number_test.xlsx")) {
Sheet sheet = inWorkbook.cloneSheet(0);
Row row = sheet.getRow(0);
Assertions.assertEquals(10.251123, row.getCell(0)
.getNumericCellValue());
file.delete();
}
}
@Test
public void decimalDisplayInXLS_whenAddedDouble_thenNumericCellCreated() throws IOException {
File file = new File("number_test.xls");
try (Workbook outWorkbook = new HSSFWorkbook()) {
Sheet sheet = outWorkbook.createSheet("Numeric Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
ExcelNumericFormat.applyNumericFormat(outWorkbook, row, cell, 10.251, "0.00");
FileOutputStream fileOut = new FileOutputStream(file);
outWorkbook.write(fileOut);
fileOut.close();
}
try (Workbook inWorkbook = new HSSFWorkbook(new FileInputStream(file))) {
Sheet sheet = inWorkbook.cloneSheet(0);
Row row = sheet.getRow(0);
Assertions.assertEquals(10.251, row.getCell(0)
.getNumericCellValue());
file.delete();
}
}
@Test
public void decimalValue_whenAddedDouble_thenNumericCellCreated() throws IOException {
File file = new File("number_test.xlsx");
try (Workbook outWorkbook = new XSSFWorkbook()) {
Sheet sheet = outWorkbook.createSheet("Numeric Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
DecimalFormat df = new DecimalFormat("#,###.##");
ExcelNumericFormat.applyNumericFormat(outWorkbook, row, cell, Double.valueOf(df.format(10.251)), "#,###.##");
FileOutputStream fileOut = new FileOutputStream(file);
outWorkbook.write(fileOut);
fileOut.close();
}
try (Workbook inWorkbook = new XSSFWorkbook("number_test.xlsx")) {
Sheet sheet = inWorkbook.cloneSheet(0);
Row row = sheet.getRow(0);
Assertions.assertEquals(10.25, row.getCell(0)
.getNumericCellValue());
file.delete();
}
}
}
@@ -2,7 +2,6 @@ package com.baeldung.poi.excel.multilinetext;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
public class MultilineText {
public void formatMultilineText(Cell cell, int cellNumber) {
@@ -111,7 +111,7 @@
<feign-core.version>11.2</feign-core.version>
<guice.version>5.0.1</guice.version>
<system-stubs-junit4.version>1.2.0</system-stubs-junit4.version>
<mockito-core.version>3.3.0</mockito-core.version>
<mockito-core.version>4.1.0</mockito-core.version>
<assertj-core.version>3.19.0</assertj-core.version>
<junit-jupiter.version>5.8.1</junit-jupiter.version>
</properties>
-7
View File
@@ -20,12 +20,6 @@
<artifactId>aws-java-sdk</artifactId>
<version>${aws-java-sdk.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
@@ -111,7 +105,6 @@
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
<gson.version>2.8.0</gson.version>
<aws-java-sdk.version>1.11.290</aws-java-sdk.version>
<mockito-core.version>2.21.0</mockito-core.version>
<dynamodblocal.version>1.11.86</dynamodblocal.version>
<dynamodblocal.repository.url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</dynamodblocal.repository.url>
<commons-codec-version>1.10.L001</commons-codec-version>
@@ -9,3 +9,4 @@ This module contains articles about Java 11 core features
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features)
- [Getting the Java Version at Runtime](https://www.baeldung.com/get-java-version-runtime)
- [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service)
- [Java HTTPS Client Certificate Authentication](https://www.baeldung.com/java-https-client-certificate-authentication)
@@ -2,12 +2,21 @@ package com.baeldung.java9.modules;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.junit.Assert.*;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.lang.module.ModuleDescriptor;
import java.lang.module.ModuleDescriptor.*;
import java.lang.module.ModuleDescriptor.Builder;
import java.lang.module.ModuleDescriptor.Exports;
import java.lang.module.ModuleDescriptor.Opens;
import java.lang.module.ModuleDescriptor.Provides;
import java.lang.module.ModuleDescriptor.Requires;
import java.sql.Date;
import java.sql.Driver;
import java.util.HashMap;
@@ -16,7 +25,7 @@ import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import org.junit.Ignore;
public class ModuleAPIUnitTest {
@@ -28,14 +37,9 @@ public class ModuleAPIUnitTest {
@Before
public void setUp() {
Class<HashMap> hashMapClass = HashMap.class;
javaBaseModule = hashMapClass.getModule();
Class<Date> dateClass = Date.class;
javaSqlModule = dateClass.getModule();
Class<Person> personClass = Person.class;
module = personClass.getModule();
javaBaseModule = HashMap.class.getModule();
javaSqlModule = Date.class.getModule();
module = Person.class.getModule();
}
@Test
@@ -111,7 +115,6 @@ public class ModuleAPIUnitTest {
}
@Test
@Ignore // fixing in http://team.baeldung.com/browse/JAVA-8679
public void givenModules_whenAccessingModuleDescriptorProvides_thenProvidesAreReturned() {
Set<Provides> javaBaseProvides = javaBaseModule.getDescriptor().provides();
Set<Provides> javaSqlProvides = javaSqlModule.getDescriptor().provides();
@@ -120,7 +123,7 @@ public class ModuleAPIUnitTest {
.map(Provides::service)
.collect(Collectors.toSet());
assertThat(javaBaseProvidesService, contains("java.nio.file.spi.FileSystemProvider"));
assertThat(javaBaseProvidesService, hasItem("java.nio.file.spi.FileSystemProvider"));
assertThat(javaSqlProvides, empty());
}
@@ -132,15 +135,14 @@ public class ModuleAPIUnitTest {
.map(Exports::source)
.collect(Collectors.toSet());
assertThat(javaSqlExportsSource, hasItems("java.sql", "javax.sql"));
assertThat(javaSqlExportsSource, hasItems("java.sql", "javax.sql"));
}
@Test
public void givenModules_whenAccessingModuleDescriptorUses_thenUsesAreReturned() {
Set<String> javaBaseUses = javaBaseModule.getDescriptor().uses();
Set<String> javaSqlUses = javaSqlModule.getDescriptor().uses();
assertThat(javaSqlUses, contains("java.sql.Driver"));
assertThat(javaSqlUses, hasItem("java.sql.Driver"));
}
@Test
@@ -17,22 +17,45 @@ public class MapIteration {
System.out.println("Iterating Keys of Map Using KeySet");
mapIteration.iterateKeys(map);
System.out.println("Iterating Values of Map Using values()");
mapIteration.iterateValues(map);
System.out.println("Iterating Map Using Entry Set");
mapIteration.iterateUsingEntrySet(map);
System.out.println("Iterating Using Iterator and Map Entry");
mapIteration.iterateUsingIteratorAndEntry(map);
System.out.println("Iterating Using Iterator and KeySet");
mapIteration.iterateUsingIteratorAndKeySet(map);
System.out.println("Iterating values Using Iterator and values()");
mapIteration.iterateUsingIteratorAndValues(map);
System.out.println("Iterating Using KeySet and For Each");
mapIteration.iterateUsingKeySetAndForeach(map);
System.out.println("Iterating Map Using Lambda Expression");
mapIteration.iterateUsingLambda(map);
System.out.println("Iterating Map By Keys Using Lambda Expression");
mapIteration.iterateByKeysUsingLambda(map);
System.out.println("Iterating values Using Lambda Expression");
mapIteration.iterateValuesUsingLambda(map);
System.out.println("Iterating Using Stream API");
mapIteration.iterateUsingStreamAPI(map);
}
public void iterateUsingIteratorAndValues(Map<String, Integer> map) {
Iterator<Integer> iterator = map.values().iterator();
while (iterator.hasNext()) {
Integer value = iterator.next();
System.out.println("value :" + value);
}
}
public void iterateUsingEntrySet(Map<String, Integer> map) {
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
@@ -43,6 +66,14 @@ public class MapIteration {
map.forEach((k, v) -> System.out.println((k + ":" + v)));
}
public void iterateByKeysUsingLambda(Map<String, Integer> map) {
map.keySet().forEach(k -> System.out.println((k + ":" + map.get(k))));
}
public void iterateValuesUsingLambda(Map<String, Integer> map) {
map.values().forEach(v -> System.out.println(("value: " + v)));
}
public void iterateUsingIteratorAndEntry(Map<String, Integer> map) {
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet()
.iterator();
@@ -52,6 +83,14 @@ public class MapIteration {
}
}
public void iterateUsingIteratorAndKeySet(Map<String, Integer> map) {
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println(key + ":" + map.get(key));
}
}
public void iterateUsingKeySetAndForeach(Map<String, Integer> map) {
for (String key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
@@ -68,7 +107,12 @@ public class MapIteration {
for (String key : map.keySet()) {
System.out.println(key);
}
}
public void iterateValues(Map<String, Integer> map) {
for (Integer value : map.values()) {
System.out.println(value);
}
}
}
@@ -0,0 +1,47 @@
package com.baeldung.volatilekeywordthreadsafety;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
public class VolatileVarNotThreadSafe {
private static final Logger LOG = LoggerFactory.getLogger(VolatileVarNotThreadSafe.class);
private static volatile int count = 0;
private static final int MAX_LIMIT = 1000;
public static void increment() {
count++;
}
public static int getCount() {
return count;
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for(int index=0; index<MAX_LIMIT; index++) {
increment();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for(int index=0; index<MAX_LIMIT; index++) {
increment();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
LOG.info("value of counter variable: "+count);
}
}
@@ -0,0 +1,13 @@
package com.baeldung.volatilekeywordthreadsafety;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class VolatileVarNotThreadSafeUnitTest {
@Test
public void whenCalledMainMethod_thenIncrementCount() throws InterruptedException {
VolatileVarNotThreadSafe.main(null);
Assertions.assertTrue(VolatileVarNotThreadSafe.getCount() > 0);
}
}
@@ -24,6 +24,22 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<compilerArgs>
<!-- Comment the arg below to print complete stack trace information -->
<!-- <arg>-g:none</arg>-->
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<h2.version>1.4.191</h2.version>
</properties>
@@ -0,0 +1,25 @@
package com.baeldung.unknownsourcestacktrace;
import com.baeldung.unknownsourcestacktrace.dto.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private static final int SHORT_NAME_LIMIT = 10;
public static void main(String[] args) {
User user = new User();
user.setName("Tom");
logger.info(getGreetingMessage(user.getName()));
}
private static String getGreetingMessage(String name) {
return "Welcome " + getShortenedName(name) + "!";
}
private static String getShortenedName(String name) {
return name.substring(0, SHORT_NAME_LIMIT);
}
}
@@ -0,0 +1,13 @@
package com.baeldung.unknownsourcestacktrace.dto;
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -5,4 +5,5 @@ This module contains articles about core Java input and output (IO)
### Relevant Articles:
- [Java File Separator vs File Path Separator](https://www.baeldung.com/java-file-vs-file-path-separator)
- [Simulate touch Command in Java](https://www.baeldung.com/java-simulate-touch-command)
- [[<-- Prev]](/core-java-modules/core-java-io-3)
@@ -0,0 +1,45 @@
package com.baeldung.iostreams;
import java.io.*;
import java.util.List;
import java.util.Vector;
public class InputSequenceHandler {
private SequenceInputStream sequenceInputStream;
public InputSequenceHandler(Vector<InputStream> inputStreams) {
sequenceInputStream = new SequenceInputStream(inputStreams.elements());
}
public InputSequenceHandler(String file1, String file2) throws FileNotFoundException {
sequenceInputStream = new SequenceInputStream(new FileInputStream(file1), new FileInputStream(file2));
}
public InputSequenceHandler(List<String> fileNames) throws FileNotFoundException {
Vector<InputStream> inputStreams = new Vector<>();
for (String fileName: fileNames) {
inputStreams.add(new FileInputStream(fileName));
}
sequenceInputStream = new SequenceInputStream(inputStreams.elements());
}
public int read() throws IOException {
return sequenceInputStream.read();
}
public String readAsString() throws IOException {
StringBuilder stringBuilder = new StringBuilder();
int readByte;
while ((readByte = sequenceInputStream.read()) != -1) {
stringBuilder.append((char) readByte);
}
return stringBuilder.toString();
}
public void close() throws IOException {
sequenceInputStream.close();
}
}
@@ -0,0 +1,77 @@
package com.baeldung.iostreams;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class InputSequenceUnitTest {
private static final String FILE1 = "iostreams/File1.txt";
private static final String FILE2 = "iostreams/File2.txt";
private static final String FILE3 = "iostreams/File3.txt";
private static final String FILE1_AND_FILE2_CONTENT = "InputSequenceUnitTest";
private static final String ALL_FILES_CONTENT = "InputSequenceUnitTest is Success";
@Test
public void givenTwoFiles_readAsString() throws URISyntaxException, IOException {
String file1 = Paths.get(ClassLoader.getSystemResource(FILE1).toURI()).toString();
String file2 = Paths.get(ClassLoader.getSystemResource(FILE2).toURI()).toString();
InputSequenceHandler inputSequenceHandler = new InputSequenceHandler(file1, file2);
String stringValue = inputSequenceHandler.readAsString();
inputSequenceHandler.close();
assertEquals(stringValue, FILE1_AND_FILE2_CONTENT);
}
@Test
public void givenFileList_readAsString() throws URISyntaxException, IOException {
List<String> filesList = new ArrayList<>();
filesList.add(Paths.get(ClassLoader.getSystemResource(FILE1).toURI()).toString());
filesList.add(Paths.get(ClassLoader.getSystemResource(FILE2).toURI()).toString());
filesList.add(Paths.get(ClassLoader.getSystemResource(FILE3).toURI()).toString());
InputSequenceHandler inputSequenceHandler = new InputSequenceHandler(filesList);
String stringValue = inputSequenceHandler.readAsString();
inputSequenceHandler.close();
assertEquals(stringValue, ALL_FILES_CONTENT);
}
@Test
public void givenVectorOfInputStreams_readAsString() throws IOException {
String[] strings = {"Testing", "Leads", "to", "failure",
"and", "failure", "leads", "to", "understanding"};
Vector<InputStream> inputStreamVector = new Vector<>();
StringBuilder stringBuilder = new StringBuilder();
for (String string: strings) {
inputStreamVector.add(new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8)));
stringBuilder.append(string);
}
InputSequenceHandler inputSequenceHandler = new InputSequenceHandler(inputStreamVector);
String combinedString = inputSequenceHandler.readAsString();
inputSequenceHandler.close();
assertEquals(stringBuilder.toString(), combinedString);
}
@Test
public void givenTwoStrings_readCombinedValue() throws IOException {
InputStream first = new ByteArrayInputStream("One".getBytes());
InputStream second = new ByteArrayInputStream("Magic".getBytes());
SequenceInputStream sequenceInputStream = new SequenceInputStream(first, second);
StringBuilder stringBuilder = new StringBuilder();
int byteValue;
while ((byteValue = sequenceInputStream.read()) != -1) {
stringBuilder.append((char) byteValue);
}
assertEquals("OneMagic", stringBuilder.toString());
}
}
@@ -0,0 +1 @@
InputSequence
@@ -0,0 +1 @@
UnitTest
@@ -0,0 +1 @@
is Success
@@ -9,3 +9,4 @@ This module contains article about constructors in Java
- [Private Constructors in Java](https://www.baeldung.com/java-private-constructors)
- [Throwing Exceptions in Constructors](https://www.baeldung.com/java-constructors-exceptions)
- [Constructors in Java Abstract Classes](https://www.baeldung.com/java-abstract-classes-constructors)
- [Java Implicit Super Constructor is Undefined Error](https://www.baeldung.com/java-implicit-super-constructor-is-undefined-error)
@@ -5,4 +5,4 @@ This module contains articles about types in Java
### Relevant Articles:
- [Convert an Array of Primitives to an Array of Objects](https://www.baeldung.com/java-primitive-array-to-object-array)
- [Check if an Enum Value Exists in Java](https://www.baeldung.com/java-find-enum-by-criteria)
- [Check if an Enum Value Exists in Java](https://www.baeldung.com/java-search-enum-values)
@@ -15,6 +15,11 @@
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
@@ -0,0 +1,78 @@
package com.baeldung.getbit;
import org.junit.Test;
import java.math.BigInteger;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class GetABitFromIntegralValueUnitTest {
@Test
public void givenAByte_whenUsingAHardCodedMask_thenGetBitValue() {
byte val1 = 0b0110_0100;
byte val2 = 0b0110_0010;
byte mask = 0b0000_0100;
boolean isSet1 = (val1 & mask) > 0;
boolean isSet2 = (val2 & mask) > 0;
assertTrue(isSet1);
assertFalse(isSet2);
}
@Test
public void givenAnIntValue_whenUsingACalculatedMask_thenGetBitValue() {
int val = 0b0110_0100;
int pos = 2;
int mask = 1 << pos;
boolean isSet = (val & mask) > 0;
assertTrue(isSet);
}
@Test
public void givenAnIntValue_whenUsingALeftShiftedValue1_thenGetBitValue() {
int val = 0b0110_0100;
int pos = 2;
boolean isSet = ((val << (31 - pos)) < 0);
assertTrue(isSet);
}
@Test
public void givenAnIntValue_whenUsingALeftShiftedValue2_thenGetBitValue() {
int val = 0b0110_0100;
int pos = 2;
boolean isSet = ((val << (~pos & 31)) < 0);
assertTrue(isSet);
}
@Test
public void givenAnIntValue_whenUsingALeftShiftedValue3_thenGetBitValue() {
int val = 0b0110_0100;
int pos = 2;
boolean isSet = ((val << ~pos) < 0);
assertTrue(isSet);
}
@Test
public void givenAnIntValue_whenUsingARightShiftedValue_thenGetBitValue() {
int val = 0b0110_0100;
int pos = 2;
boolean isSet = ((val >> pos) & 1) == 1;
assertTrue(isSet);
}
@Test
public void givenAnIntValue_whenUsingBigInteger_thenGetBitValue() {
int val = 0b0110_0100;
int pos = 2;
boolean isSet = BigInteger.valueOf(val).testBit(pos);
assertTrue(isSet);
}
}
@@ -0,0 +1,35 @@
package com.baeldung.serialization;
import java.io.Serializable;
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
private long id;
private volatile String name;
private Address address;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
@@ -29,7 +29,7 @@ public class MySerializationUtils {
public static boolean isSerializable(Class<?> it) {
boolean serializable = it.isPrimitive() || it.isInterface() || Serializable.class.isAssignableFrom(it);
if (!serializable) {
return serializable;
return false;
}
Field[] declaredFields = it.getDeclaredFields();
for (Field field : declaredFields) {
@@ -37,8 +37,10 @@ public class MySerializationUtils {
continue;
}
Class<?> fieldType = field.getType();
return isSerializable(fieldType);
if (!isSerializable(fieldType)) {
return false;
}
}
return serializable;
return true;
}
}
@@ -107,5 +107,7 @@ public class SerializationUnitTest {
assertFalse(MySerializationUtils.isSerializable(Address.class));
assertTrue(MySerializationUtils.isSerializable(Person.class));
assertTrue(MySerializationUtils.isSerializable(Integer.class));
assertFalse(MySerializationUtils.isSerializable(Customer.class));
assertTrue(MySerializationUtils.isSerializable(Employee.class));
}
}
@@ -0,0 +1,187 @@
package com.baeldung.stringtofloat;
import org.junit.jupiter.api.Test;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class StringToFloatConversionUnitTest {
@Test
public void givenFloat_whenStringConcatenation_thenReturnString() {
Float givenFloat = 1.25f;
String result = givenFloat + "";
assertEquals("1.25", result);
}
@Test
public void givenFloatPrimitive_whenStringConcatenation_thenReturnString() {
float givenFloat = 1.25f;
String result = givenFloat + "";
assertEquals("1.25", result);
}
@Test
public void givenNullFloat_whenStringConcatenation_thenReturnNullString() {
Float givenFloat = null;
String result = givenFloat + "";
assertEquals("null", result);
}
@Test
public void givenFloat_whenToString_thenReturnString() {
Float givenFloat = 1.25f;
String result = Float.toString(givenFloat);
assertEquals("1.25", result);
}
@Test
public void givenNullFloat_whenToString_thenThrowNullPointerException() {
Float givenFloat = null;
assertThrows(NullPointerException.class, () -> Float.toString(givenFloat));
}
@Test
public void givenFloat_whenValueOf_thenReturnString() {
Float givenFloat = 1.25f;
String result = String.valueOf(givenFloat);
assertEquals("1.25", result);
}
@Test
public void givenNullFloat_whenValueOf_thenReturnNullString() {
Float givenFloat = null;
String result = String.valueOf(givenFloat);
assertEquals("null", result);
}
@Test
public void givenFloat_whenDecimalFormat_thenReturnString() {
Float givenFloat = 1.25f;
String result = new DecimalFormat("#.0000").format(givenFloat);
assertEquals("1.2500", result);
}
@Test
public void givenFloat_whenDecimalFormat_thenReturnWholeNumberString() {
Float givenFloat = 1.0025f;
String result = new DecimalFormat("#.##").format(givenFloat);
assertEquals("1", result);
}
@Test
public void givenNullFloat_whenDecimalFormat_thenThrowIllegalArgumentException() {
Float givenFloat = null;
assertThrows(IllegalArgumentException.class, () -> new DecimalFormat("#.000").format(givenFloat));
}
@Test
public void givenFloat_whenStringFormat_thenReturnString() {
Float givenFloat = 1.25f;
String result = String.format("%f", givenFloat);
assertEquals("1.250000", result);
}
@Test
public void givenFloat_whenStringFormatWithDecimalLimit_thenReturnRoundedString() {
Float givenFloat = 1.256f;
String result = String.format("%.2f", givenFloat);
assertEquals("1.26", result);
}
@Test
public void givenNullFloat_whenStringFormatWithDecimalLimit_thenReturnNullString() {
Float givenFloat = null;
String result = String.format("%f", givenFloat);
assertEquals("null", result);
}
@Test
public void givenString_whenParseFloat_thenReturnFloat() {
String givenString = "1.25";
float result = Float.parseFloat(givenString);
assertEquals(1.25f, result);
}
@Test
public void givenNullString_whenParseFloat_thenThrowNullPointerException() {
String givenString = null;
assertThrows(NullPointerException.class, () -> Float.parseFloat(givenString));
}
@Test
public void givenNonParsableString_whenParseFloat_thenThrowNumberFormatException() {
String givenString = "1.23x";
assertThrows(NumberFormatException.class, () -> Float.parseFloat(givenString));
}
@Test
public void givenString_whenValueOf_thenReturnFloat() {
String givenString = "1.25";
Float result = Float.valueOf(givenString);
assertEquals(1.25f, result);
}
@Test
public void givenNonParsableString_whenValueOf_thenThrowNumberFormatException() {
String givenString = "1.25x";
assertThrows(NumberFormatException.class, () -> Float.valueOf(givenString));
}
@Test
public void givenString_whenConstructor_thenReturnFloat() {
String givenString = "1.25";
Float result = new Float(givenString);
assertEquals(1.25f, result);
}
@Test
public void givenString_whenDecimalFormat_thenReturnFloat() throws ParseException {
String givenString = "1,250";
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
DecimalFormat decimalFormat = new DecimalFormat("#.000");
decimalFormat.setDecimalFormatSymbols(symbols);
Float result = decimalFormat.parse(givenString).floatValue();
assertEquals(1.25f, result);
}
}
@@ -0,0 +1,51 @@
package com.baeldung.split;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
public class SplitStringEveryNthChar {
public static List<String> usingSplitMethod(String text, int n) {
String[] results = text.split("(?<=\\G.{" + n + "})");
return Arrays.asList(results);
}
public static List<String> usingSubstringMethod(String text, int n) {
List<String> results = new ArrayList<>();
int length = text.length();
for (int i = 0; i < length; i += n) {
results.add(text.substring(i, Math.min(length, i + n)));
}
return results;
}
public static List<String> usingPattern(String text, int n) {
List<String> results = new ArrayList<>();
Pattern pattern = Pattern.compile(".{1," + n + "}");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String match = text.substring(matcher.start(), matcher.end());
results.add(match);
}
return results;
}
public static List<String> usingGuava(String text, int n) {
Iterable<String> parts = Splitter.fixedLength(n)
.split(text);
return ImmutableList.copyOf(parts);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.equalsvscontentequals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class StringEqualsVsContentEqualsUnitTest {
String actualString = "baeldung";
String identicalString = "baeldung";
CharSequence identicalStringInstance = "baeldung";
CharSequence identicalStringBufferInstance = new StringBuffer("baeldung");
@Test
public void whenIdenticalTestString_thenBothTrue() {
assertTrue(actualString.equals(identicalString));
assertTrue(actualString.contentEquals(identicalString));
}
@Test
public void whenSameContentButDifferentType_thenEqualsIsFalseAndContentEqualsIsTrue() {
assertTrue(actualString.equals(identicalStringInstance));
assertTrue(actualString.contentEquals(identicalStringInstance));
assertFalse(actualString.equals(identicalStringBufferInstance));
assertTrue(actualString.contentEquals(identicalStringBufferInstance));
}
}

Some files were not shown because too many files have changed in this diff Show More