This commit is contained in:
Chirag Dewan 2019-08-04 13:19:52 +05:30
commit b467ee6ac2
293 changed files with 3253 additions and 510 deletions

View File

@ -0,0 +1,24 @@
package com.baeldung.files;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner;
public class Main {
private static final String INPUT_FILE_NAME = "src/main/resources/input.txt";
public static void main(String... args) throws Exception {
System.out.printf("Total Number of Lines Using BufferedReader: %s%n", getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME));
System.out.printf("Total Number of Lines Using LineNumberReader: %s%n", getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME));
System.out.printf("Total Number of Lines Using Scanner: %s%n", getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME));
System.out.printf("Total Number of Lines Using NIO Files: %s%n", getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME));
System.out.printf("Total Number of Lines Using NIO FileChannel: %s%n", getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME));
System.out.printf("Total Number of Lines Using Apache Commons IO: %s%n", getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME));
System.out.printf("Total Number of Lines Using NIO Google Guava: %s%n", getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME));
}
}

View File

@ -0,0 +1,112 @@
package com.baeldung.files;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Stream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
public class NumberOfLineFinder {
public static int getTotalNumberOfLinesUsingBufferedReader(String fileName) {
int lines = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
while (reader.readLine() != null) {
lines++;
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingLineNumberReader(String fileName) {
int lines = 0;
try (LineNumberReader reader = new LineNumberReader(new FileReader(fileName))) {
reader.skip(Integer.MAX_VALUE);
lines = reader.getLineNumber() + 1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingScanner(String fileName) {
int lines = 0;
try (Scanner scanner = new Scanner(new FileReader(fileName))) {
while (scanner.hasNextLine()) {
scanner.nextLine();
lines++;
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingNIOFiles(String fileName) {
int lines = 0;
try (Stream<String> fileStream = Files.lines(Paths.get(fileName))) {
lines = (int) fileStream.count();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingNIOFileChannel(String fileName) {
int lines = 1;
try (FileChannel channel = FileChannel.open(Paths.get(fileName), StandardOpenOption.READ)) {
ByteBuffer byteBuffer = channel.map(MapMode.READ_ONLY, 0, channel.size());
while (byteBuffer.hasRemaining()) {
byte currentChar = byteBuffer.get();
if (currentChar == '\n') {
lines++;
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingApacheCommonsIO(String fileName) {
int lines = 0;
try {
LineIterator lineIterator = FileUtils.lineIterator(new File(fileName));
while (lineIterator.hasNext()) {
lineIterator.nextLine();
lines++;
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
public static int getTotalNumberOfLinesUsingGoogleGuava(String fileName) {
int lines = 0;
try {
List<String> lineItems = com.google.common.io.Files.readLines(Paths.get(fileName)
.toFile(), Charset.defaultCharset());
lines = lineItems.size();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return lines;
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.file;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingApacheCommonsIO;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingBufferedReader;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingGoogleGuava;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingLineNumberReader;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFileChannel;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingNIOFiles;
import static com.baeldung.files.NumberOfLineFinder.getTotalNumberOfLinesUsingScanner;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class NumberOfLineFinderUnitTest {
private static final String INPUT_FILE_NAME = "src/main/resources/input.txt";
private static final int ACTUAL_LINE_COUNT = 45;
@Test
public void whenUsingBufferedReader_thenReturnTotalNumberOfLines() {
int lines = getTotalNumberOfLinesUsingBufferedReader(INPUT_FILE_NAME);
assertEquals(ACTUAL_LINE_COUNT, lines);
}
@Test
public void whenUsingLineNumberReader_thenReturnTotalNumberOfLines() {
int lines = getTotalNumberOfLinesUsingLineNumberReader(INPUT_FILE_NAME);
assertEquals(ACTUAL_LINE_COUNT, lines);
}
@Test
public void whenUsingScanner_thenReturnTotalNumberOfLines() {
int lines = getTotalNumberOfLinesUsingScanner(INPUT_FILE_NAME);
assertEquals(ACTUAL_LINE_COUNT, lines);
}
@Test
public void whenUsingNIOFiles_thenReturnTotalNumberOfLines() {
int lines = getTotalNumberOfLinesUsingNIOFiles(INPUT_FILE_NAME);
assertEquals(ACTUAL_LINE_COUNT, lines);
}
@Test
public void whenUsingNIOFileChannel_thenReturnTotalNumberOfLines() {
int lines = getTotalNumberOfLinesUsingNIOFileChannel(INPUT_FILE_NAME);
assertEquals(ACTUAL_LINE_COUNT, lines);
}
@Test
public void whenUsingApacheCommonsIO_thenReturnTotalNumberOfLines() {
int lines = getTotalNumberOfLinesUsingApacheCommonsIO(INPUT_FILE_NAME);
assertEquals(ACTUAL_LINE_COUNT, lines);
}
@Test
public void whenUsingGoogleGuava_thenReturnTotalNumberOfLines() {
int lines = getTotalNumberOfLinesUsingGoogleGuava(INPUT_FILE_NAME);
assertEquals(ACTUAL_LINE_COUNT, lines);
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.relationships.aggregation;
import java.util.List;
public class Car {
private List<Wheel> wheels;
}

View File

@ -0,0 +1,13 @@
package com.baeldung.relationships.aggregation;
import java.util.List;
public class CarWithStaticInnerWheel {
private List<Wheel> wheels;
public static class Wheel {
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.relationships.aggregation;
public class Wheel {
private Car car;
}

View File

@ -0,0 +1,7 @@
package com.baeldung.relationships.association;
public class Child {
private Mother mother;
}

View File

@ -0,0 +1,9 @@
package com.baeldung.relationships.association;
import java.util.List;
public class Mother {
private List<Child> children;
}

View File

@ -0,0 +1,18 @@
package com.baeldung.relationships.composition;
import java.util.List;
public class Building {
private String address;
private List<Room> rooms;
public class Room {
public String getBuildingAddress() {
return Building.this.address;
}
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.relationships.composition;
public class BuildingWithDefinitionRoomInMethod {
public Room createAnonymousRoom() {
return new Room() {
@Override
public void doInRoom() {}
};
}
public Room createInlineRoom() {
class InlineRoom implements Room {
@Override
public void doInRoom() {}
}
return new InlineRoom();
}
public Room createLambdaRoom() {
return () -> {};
}
public interface Room {
void doInRoom();
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.relationships.university;
import java.util.List;
public class Department {
private List<Professor> professors;
}

View File

@ -0,0 +1,10 @@
package com.baeldung.relationships.university;
import java.util.List;
public class Professor {
private List<Department> department;
private List<Professor> friends;
}

View File

@ -0,0 +1,9 @@
package com.baeldung.relationships.university;
import java.util.List;
public class University {
private List<Department> department;
}

View File

@ -0,0 +1,63 @@
package com.baeldung.incrementdecrementunaryoperator;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class IncrementDecrementUnaryOperatorUnitTest {
@Test
public void givenAnOperand_whenUsingPreIncrementUnaryOperator_thenOperandIsIncrementedByOne() {
int operand = 1;
++operand;
assertThat(operand).isEqualTo(2);
}
@Test
public void givenANumber_whenUsingPreIncrementUnaryOperatorInEvaluation_thenNumberIsIncrementedByOne() {
int operand = 1;
int number = ++operand;
assertThat(number).isEqualTo(2);
}
@Test
public void givenAnOperand_whenUsingPreDecrementUnaryOperator_thenOperandIsDecrementedByOne() {
int operand = 1;
--operand;
assertThat(operand).isEqualTo(0);
}
@Test
public void givenANumber_whenUsingPreDecrementUnaryOperatorInEvaluation_thenNumberIsDecrementedByOne() {
int operand = 1;
int number = --operand;
assertThat(number).isEqualTo(0);
}
@Test
public void givenAnOperand_whenUsingPostIncrementUnaryOperator_thenOperandIsIncrementedByOne() {
int operand = 1;
operand++;
assertThat(operand).isEqualTo(2);
}
@Test
public void givenANumber_whenUsingPostIncrementUnaryOperatorInEvaluation_thenNumberIsSameAsOldValue() {
int operand = 1;
int number = operand++;
assertThat(number).isEqualTo(1);
}
@Test
public void givenAnOperand_whenUsingPostDecrementUnaryOperator_thenOperandIsDecrementedByOne() {
int operand = 1;
operand--;
assertThat(operand).isEqualTo(0);
}
@Test
public void givenANumber_whenUsingPostDecrementUnaryOperatorInEvaluation_thenNumberIsSameAsOldValue() {
int operand = 1;
int number = operand--;
assertThat(number).isEqualTo(1);
}
}

View File

@ -1,25 +0,0 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml

View File

@ -0,0 +1,29 @@
package com.baeldung.sasl;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.RealmCallback;
public class ClientCallbackHandler implements CallbackHandler {
@Override
public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException {
for (Callback cb : cbs) {
if (cb instanceof NameCallback) {
NameCallback nc = (NameCallback) cb;
nc.setName("username");
} else if (cb instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) cb;
pc.setPassword("password".toCharArray());
} else if (cb instanceof RealmCallback) {
RealmCallback rc = (RealmCallback) cb;
rc.setText("myServer");
}
}
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.sasl;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.AuthorizeCallback;
import javax.security.sasl.RealmCallback;
public class ServerCallbackHandler implements CallbackHandler {
@Override
public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException {
for (Callback cb : cbs) {
if (cb instanceof AuthorizeCallback) {
AuthorizeCallback ac = (AuthorizeCallback) cb;
ac.setAuthorized(true);
} else if (cb instanceof NameCallback) {
NameCallback nc = (NameCallback) cb;
nc.setName("username");
} else if (cb instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) cb;
pc.setPassword("password".toCharArray());
} else if (cb instanceof RealmCallback) {
RealmCallback rc = (RealmCallback) cb;
rc.setText("myServer");
}
}
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.sasl;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class SaslUnitTest {
private static final String MECHANISM = "DIGEST-MD5";
private static final String SERVER_NAME = "myServer";
private static final String PROTOCOL = "myProtocol";
private static final String AUTHORIZATION_ID = null;
private static final String QOP_LEVEL = "auth-conf";
private SaslServer saslServer;
private SaslClient saslClient;
@Before
public void setUp() throws SaslException {
ServerCallbackHandler serverHandler = new ServerCallbackHandler();
ClientCallbackHandler clientHandler = new ClientCallbackHandler();
Map<String, String> props = new HashMap<>();
props.put(Sasl.QOP, QOP_LEVEL);
saslServer = Sasl.createSaslServer(MECHANISM, PROTOCOL, SERVER_NAME, props, serverHandler);
saslClient = Sasl.createSaslClient(new String[] { MECHANISM }, AUTHORIZATION_ID, PROTOCOL, SERVER_NAME, props, clientHandler);
}
@Test
public void givenHandlers_whenStarted_thenAutenticationWorks() throws SaslException {
byte[] challenge;
byte[] response;
challenge = saslServer.evaluateResponse(new byte[0]);
response = saslClient.evaluateChallenge(challenge);
challenge = saslServer.evaluateResponse(response);
response = saslClient.evaluateChallenge(challenge);
assertTrue(saslServer.isComplete());
assertTrue(saslClient.isComplete());
String qop = (String) saslClient.getNegotiatedProperty(Sasl.QOP);
assertEquals("auth-conf", qop);
byte[] outgoing = "Baeldung".getBytes();
byte[] secureOutgoing = saslClient.wrap(outgoing, 0, outgoing.length);
byte[] secureIncoming = secureOutgoing;
byte[] incoming = saslServer.unwrap(secureIncoming, 0, secureIncoming.length);
assertEquals("Baeldung", new String(incoming, StandardCharsets.UTF_8));
}
@After
public void tearDown() throws SaslException {
saslClient.dispose();
saslServer.dispose();
}
}

View File

@ -2,6 +2,7 @@ package com.baeldung.graph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Stack;
@ -29,7 +30,7 @@ public class Graph {
while (!stack.isEmpty()) {
int current = stack.pop();
isVisited[current] = true;
System.out.print(" " + current);
visit(current);
for (int dest : adjVertices.get(current)) {
if (!isVisited[dest])
stack.push(dest);
@ -44,29 +45,30 @@ public class Graph {
private void dfsRecursive(int current, boolean[] isVisited) {
isVisited[current] = true;
System.out.print(" " + current);
visit(current);
for (int dest : adjVertices.get(current)) {
if (!isVisited[dest])
dfsRecursive(dest, isVisited);
}
}
public void topologicalSort(int start) {
Stack<Integer> result = new Stack<Integer>();
public List<Integer> topologicalSort(int start) {
LinkedList<Integer> result = new LinkedList<Integer>();
boolean[] isVisited = new boolean[adjVertices.size()];
topologicalSortRecursive(start, isVisited, result);
while (!result.isEmpty()) {
System.out.print(" " + result.pop());
}
return result;
}
private void topologicalSortRecursive(int current, boolean[] isVisited, Stack<Integer> result) {
private void topologicalSortRecursive(int current, boolean[] isVisited, LinkedList<Integer> result) {
isVisited[current] = true;
for (int dest : adjVertices.get(current)) {
if (!isVisited[dest])
topologicalSortRecursive(dest, isVisited, result);
}
result.push(current);
result.addFirst(current);
}
private void visit(int value) {
System.out.print(" " + value);
}
}

View File

@ -103,14 +103,14 @@ public class BinaryTree {
public void traverseInOrder(Node node) {
if (node != null) {
traverseInOrder(node.left);
System.out.print(" " + node.value);
visit(node.value);
traverseInOrder(node.right);
}
}
public void traversePreOrder(Node node) {
if (node != null) {
System.out.print(" " + node.value);
visit(node.value);
traversePreOrder(node.left);
traversePreOrder(node.right);
}
@ -120,7 +120,7 @@ public class BinaryTree {
if (node != null) {
traversePostOrder(node.left);
traversePostOrder(node.right);
System.out.print(" " + node.value);
visit(node.value);
}
}
@ -159,7 +159,7 @@ public class BinaryTree {
stack.push(current);
}
current = stack.pop();
System.out.print(" " + current.value);
visit(current.value);
if(current.right != null) {
current = current.right;
stack.push(current);
@ -173,7 +173,7 @@ public class BinaryTree {
stack.push(root);
while(! stack.isEmpty()) {
current = stack.pop();
System.out.print(" " + current.value);
visit(current.value);
if(current.right != null)
stack.push(current.right);
@ -196,7 +196,7 @@ public class BinaryTree {
if (!hasChild || isPrevLastChild) {
current = stack.pop();
System.out.print(" " + current.value);
visit(current.value);
prev = current;
} else {
if (current.right != null) {
@ -209,6 +209,9 @@ public class BinaryTree {
}
}
private void visit(int value) {
System.out.print(" " + value);
}
class Node {
int value;

View File

@ -1,5 +1,7 @@
package com.baeldung.graph;
import java.util.List;
import org.junit.Test;
public class GraphUnitTest {
@ -15,7 +17,8 @@ public class GraphUnitTest {
@Test
public void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() {
Graph graph = createDirectedGraph();
graph.topologicalSort(0);
List<Integer> list = graph.topologicalSort(0);
System.out.println(list);
}
private Graph createDirectedGraph() {

View File

@ -1,26 +0,0 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
*.txt
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml

View File

@ -0,0 +1,148 @@
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();
while (decimalNumber > 0) {
int remainder = decimalNumber % 2;
int result = decimalNumber / 2;
binaryNumber.append(remainder);
decimalNumber = result;
}
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 result = 0;
Integer base = 1;
while (binaryNumber > 0) {
int lastDigit = binaryNumber % 10;
binaryNumber = binaryNumber / 10;
result += lastDigit * base;
base = base * 2;
}
return result;
}
/**
* 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());
}
}

View File

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

View File

@ -3,5 +3,20 @@
- [Java Localization Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting)
- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring)
- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords)
- [Java Generate Random String](http://www.baeldung.com/java-random-string)
- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode)
- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char)
- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array)
- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)
- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)
- [Convert a Comma Separated String to a List in Java](https://www.baeldung.com/java-string-with-separator-to-list)
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters)
- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation)
- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions)
- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram)
- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words)
- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings)
- [String Initialization in Java](https://www.baeldung.com/java-string-initialization)

View File

@ -40,6 +40,16 @@
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@ -52,32 +62,54 @@
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<!-- Added for password generation -->
<dependency>
<groupId>org.passay</groupId>
<artifactId>passay</artifactId>
<version>${passay.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<dependency>
<groupId>com.vdurmont</groupId>
<artifactId>emoji-java</artifactId>
<version>${emoji-java.version}</version>
</dependency>
<dependency>
<groupId>org.ahocorasick</groupId>
<artifactId>ahocorasick</artifactId>
<version>${ahocorasick.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.0.Final</version>
<version>${validation-api.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.2.Final</version>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
<version>${javax.el-api.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.6</version>
<version>${javax.el.version}</version>
</dependency>
</dependencies>
<build>
@ -105,9 +137,19 @@
<properties>
<commons-lang3.version>3.8.1</commons-lang3.version>
<commons-codec.version>1.10</commons-codec.version>
<passay.version>1.3.1</passay.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<emoji-java.version>4.0.0</emoji-java.version>
<ahocorasick.version>0.4.0</ahocorasick.version>
<icu4j.version>61.1</icu4j.version>
<guava.version>28.0-jre</guava.version>
<commons-text.version>1.4</commons-text.version>
<validation-api.version>2.0.0.Final</validation-api.version>
<hibernate-validator.version>6.0.2.Final</hibernate-validator.version>
<javax.el-api.version>3.0.0</javax.el-api.version>
<javax.el.version>2.2.6</javax.el.version>
</properties>
</project>

View File

@ -0,0 +1,56 @@
package com.baeldung.string.todouble;
import static org.junit.Assert.assertEquals;
import java.text.DecimalFormat;
import java.text.ParseException;
import org.junit.Test;
public class StringToDoubleConversionUnitTest {
@Test
public void givenValidString_WhenParseDouble_ThenResultIsPrimitiveDouble() {
assertEquals(1.23, Double.parseDouble("1.23"), 0.000001);
}
@Test(expected = NullPointerException.class)
public void givenNullString_WhenParseDouble_ThenNullPointerExceptionIsThrown() {
Double.parseDouble(null);
}
@Test(expected = NumberFormatException.class)
public void givenInalidString_WhenParseDouble_ThenNumberFormatExceptionIsThrown() {
Double.parseDouble("&");
}
@Test
public void givenValidString_WhenValueOf_ThenResultIsPrimitiveDouble() {
assertEquals(1.23, Double.valueOf("1.23"), 0.000001);
}
@Test(expected = NullPointerException.class)
public void givenNullString_WhenValueOf_ThenNullPointerExceptionIsThrown() {
Double.valueOf(null);
}
@Test(expected = NumberFormatException.class)
public void givenInalidString_WhenValueOf_ThenNumberFormatExceptionIsThrown() {
Double.valueOf("&");
}
@Test
public void givenValidString_WhenDecimalFormat_ThenResultIsValidDouble() throws ParseException {
assertEquals(1.23, new DecimalFormat("#").parse("1.23").doubleValue(), 0.000001);
}
@Test(expected = NullPointerException.class)
public void givenNullString_WhenDecimalFormat_ThenNullPointerExceptionIsThrown() throws ParseException {
new DecimalFormat("#").parse(null);
}
@Test(expected = ParseException.class)
public void givenInvalidString_WhenDecimalFormat_ThenParseExceptionIsThrown() throws ParseException {
new DecimalFormat("#").parse("&");
}
}

View File

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

View File

@ -0,0 +1,22 @@
=========
## Java Strings Cookbooks and Examples
### Relevant Articles:
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
- [Java String Conversions](https://www.baeldung.com/java-string-conversions)
- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome)
- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
- [Get Substring from String in Java](https://www.baeldung.com/java-substring)
- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
- [Split a String in Java](http://www.baeldung.com/java-split-string)
- [Common String Operations in Java](https://www.baeldung.com/java-string-operations)
- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
- [Java toString() Method](https://www.baeldung.com/java-tostring)
- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)

99
java-strings-ops/pom.xml Normal file
View File

@ -0,0 +1,99 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>java-strings-ops</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>java-strings-ops</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter-api.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>java-strings-ops</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<compilerArgument>-parameters</compilerArgument>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- util -->
<commons-lang3.version>3.8.1</commons-lang3.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<guava.version>27.0.1-jre</guava.version>
<junit-jupiter-api.version>5.3.1</junit-jupiter-api.version>
</properties>
</project>

View File

@ -10,8 +10,4 @@
# Packaged files #
*.jar
*.war
*.ear
*.ipr
*.iml
*.iws
*.ear

View File

@ -6,51 +6,18 @@
- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
- [Java Generate Random String](http://www.baeldung.com/java-random-string)
- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
- [Java String Conversions](https://www.baeldung.com/java-string-conversions)
- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum)
- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer)
- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
- [Split a String in Java](http://www.baeldung.com/java-split-string)
- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome)
- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
- [Use char[] Array Over a String for Manipulating Passwords in Java?](http://www.baeldung.com/java-storing-passwords)
- [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case)
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
- [Java Check a String for Lowercase/Uppercase Letter, Special Character and Digit](https://www.baeldung.com/java-lowercase-uppercase-special-character-digit-regex)
- [Convert java.util.Date to String](https://www.baeldung.com/java-util-date-to-string)
- [Get Substring from String in Java](https://www.baeldung.com/java-substring)
- [Converting a Stack Trace to a String in Java](https://www.baeldung.com/java-stacktrace-to-string)
- [Sorting a String Alphabetically in Java](https://www.baeldung.com/java-sort-string-alphabetically)
- [Remove Emojis from a Java String](https://www.baeldung.com/java-string-remove-emojis)
- [String Not Empty Test Assertions in Java](https://www.baeldung.com/java-assert-string-not-empty)
- [String Performance Hints](https://www.baeldung.com/java-string-performance)
- [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences)
- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode)
- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char)
- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array)
- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)
- [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline)
- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part)
- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index)
- [Convert a Comma Separated String to a List in Java](https://www.baeldung.com/java-string-with-separator-to-list)
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
- [Remove Leading and Trailing Characters from a String](https://www.baeldung.com/java-remove-trailing-characters)
- [Concatenating Strings In Java](https://www.baeldung.com/java-strings-concatenation)
- [Java toString() Method](https://www.baeldung.com/java-tostring)
- [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions)
- [Check if a String is a Pangram in Java](https://www.baeldung.com/java-string-pangram)
- [Check If a String Contains Multiple Keywords](https://www.baeldung.com/string-contains-multiple-words)
- [Common String Operations in Java](https://www.baeldung.com/java-string-operations)
- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index)

View File

@ -62,12 +62,6 @@
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.vdurmont</groupId>
<artifactId>emoji-java</artifactId>
<version>${emoji-java.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
@ -83,24 +77,6 @@
<scope>test</scope>
</dependency>
<!-- Added for password generation -->
<dependency>
<groupId>org.passay</groupId>
<artifactId>passay</artifactId>
<version>${passay.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<dependency>
<groupId>org.ahocorasick</groupId>
<artifactId>ahocorasick</artifactId>
<version>${ahocorasick.version}</version>
</dependency>
</dependencies>
<build>
@ -134,11 +110,8 @@
<assertj.version>3.6.1</assertj.version>
<icu4j.version>61.1</icu4j.version>
<guava.version>27.0.1-jre</guava.version>
<emoji-java.version>4.0.0</emoji-java.version>
<junit-jupiter-api.version>5.3.1</junit-jupiter-api.version>
<passay.version>1.3.1</passay.version>
<commons-text.version>1.4</commons-text.version>
<ahocorasick.version>0.4.0</ahocorasick.version>
</properties>
</project>

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