Move articles out of core-java-lang part 2

This commit is contained in:
catalin-burcea
2019-10-06 15:57:30 +03:00
parent 7cbe9ac12c
commit 6b80543360
43 changed files with 49 additions and 62 deletions

View File

@@ -5,4 +5,10 @@ This module contains articles about Java syntax
### Relevant Articles:
- [Java private Access Modifier](https://www.baeldung.com/java-private-keyword)
- [Guide to Java Packages](https://www.baeldung.com/java-packages)
- [If-Else Statement in Java](https://www.baeldung.com/java-if-else)
- [Control Structures in Java](https://www.baeldung.com/java-control-structures)
- [Java Double Brace Initialization](https://www.baeldung.com/java-double-brace-initialization)
- [The Java Native Keyword and Methods](https://www.baeldung.com/java-native)
- [Variable Scope in Java](https://www.baeldung.com/java-variable-scope)
- [[<-- Prev]](/core-java-modules/core-java-lang-syntax)

View File

@@ -0,0 +1,68 @@
package com.baeldung.core.controlstructures;
public class ConditionalBranches {
/**
* Multiple if/else/else if statements examples. Shows different syntax usage.
*/
public static void ifElseStatementsExamples() {
int count = 2; // Initial count value.
// Basic syntax. Only one statement follows. No brace usage.
if (count > 1)
System.out.println("Count is higher than 1");
// Basic syntax. More than one statement can be included. Braces are used (recommended syntax).
if (count > 1) {
System.out.println("Count is higher than 1");
System.out.println("Count is equal to: " + count);
}
// If/Else syntax. Two different courses of action can be included.
if (count > 2) {
System.out.println("Count is higher than 2");
} else {
System.out.println("Count is lower or equal than 2");
}
// If/Else/Else If syntax. Three or more courses of action can be included.
if (count > 2) {
System.out.println("Count is higher than 2");
} else if (count <= 0) {
System.out.println("Count is less or equal than zero");
} else {
System.out.println("Count is either equal to one, or two");
}
}
/**
* Ternary Operator example.
* @see ConditionalBranches#ifElseStatementsExamples()
*/
public static void ternaryExample() {
int count = 2;
System.out.println(count > 2 ? "Count is higher than 2" : "Count is lower or equal than 2");
}
/**
* Switch structure example. Shows how to replace multiple if/else statements with one structure.
*/
public static void switchExample() {
int count = 3;
switch (count) {
case 0:
System.out.println("Count is equal to 0");
break;
case 1:
System.out.println("Count is equal to 1");
break;
case 2:
System.out.println("Count is equal to 2");
break;
default:
System.out.println("Count is either negative, or higher than 2");
break;
}
}
}

View File

@@ -0,0 +1,157 @@
package com.baeldung.core.controlstructures;
public class Loops {
/**
* Dummy method. Only prints a generic message.
*/
private static void methodToRepeat() {
System.out.println("Dummy method.");
}
/**
* Shows how to iterate 50 times with 3 different method/control structures.
*/
public static void repetitionTo50Examples() {
for (int i = 1; i <= 50; i++) {
methodToRepeat();
}
int whileCounter = 1;
while (whileCounter <= 50) {
methodToRepeat();
whileCounter++;
}
int count = 1;
do {
methodToRepeat();
count++;
} while (count < 50);
}
/**
* Splits a sentence in words, and prints each word in a new line.
* @param sentence Sentence to print as independent words.
*/
public static void printWordByWord(String sentence) {
for (String word : sentence.split(" ")) {
System.out.println(word);
}
}
/**
* Prints text an N amount of times. Shows usage of the {@code break} branching statement.
* @param textToPrint Text to repeatedly print.
* @param times Amount to times to print received text.
*/
public static void printTextNTimes(String textToPrint, int times) {
int counter = 1;
while (true) {
System.out.println(textToPrint);
if (counter == times) {
break;
}
}
}
/**
* Prints text an N amount of times, up to 50. Shows usage of the {@code break} branching statement.
* @param textToPrint Text to repeatedly print.
* @param times Amount to times to print received text. If times is higher than 50, textToPrint will only be printed 50 times.
*/
public static void printTextNTimesUpTo50(String textToPrint, int times) {
int counter = 1;
while (counter < 50) {
System.out.println(textToPrint);
if (counter == times) {
break;
}
}
}
/**
* Finds the index of {@code name} in a list
* @param name The name to look for
* @param names The list of names
* @return The index where the name was found or -1 otherwise
*/
public static int findFirstInstanceOfName(String name, String[] names) {
int index = 0;
for ( ; index < names.length; index++) {
if (names[index].equals(name)) {
break;
}
}
return index == names.length ? -1 : index;
}
/**
* Takes several names and makes a list, skipping the specified {@code name}.
*
* @param name The name to skip
* @param names The list of names
* @return The list of names as a single string, missing the specified {@code name}.
*/
public static String makeListSkippingName(String name, String[] names) {
String list = "";
for (int i = 0; i < names.length; i++) {
if (names[i].equals(name)) {
continue;
}
list += names[i];
}
return list;
}
/**
* Prints an specified amount of even numbers. Shows usage of both {@code break} and {@code continue} branching statements.
* @param amountToPrint Amount of even numbers to print.
*/
public static void printEvenNumbers(int amountToPrint) {
if (amountToPrint <= 0) { // Invalid input
return;
}
int iterator = 0;
int amountPrinted = 0;
while (true) {
if (iterator % 2 == 0) { // Is an even number
System.out.println(iterator);
amountPrinted++;
iterator++;
} else {
iterator++;
continue; // Won't print
}
if (amountPrinted == amountToPrint) {
break;
}
}
}
/**
* Prints an specified amount of even numbers, up to 100. Shows usage of both {@code break} and {@code continue} branching statements.
* @param amountToPrint Amount of even numbers to print.
*/
public static void printEvenNumbersToAMaxOf100(int amountToPrint) {
if (amountToPrint <= 0) { // Invalid input
return;
}
int iterator = 0;
int amountPrinted = 0;
while (amountPrinted < 100) {
if (iterator % 2 == 0) { // Is an even number
System.out.println(iterator);
amountPrinted++;
iterator++;
} else {
iterator++;
continue; // Won't print
}
if (amountPrinted == amountToPrint) {
break;
}
}
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.core.nativekeyword;
public class DateTimeUtils {
public native String getSystemTime();
static {
System.loadLibrary("nativedatetimeutils");
}
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.core.nativekeyword;
public class NativeMainApp {
public static void main(String[] args) {
DateTimeUtils dateTimeUtils = new DateTimeUtils();
String input = dateTimeUtils.getSystemTime();
System.out.println("System time is : " + input);
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.core.packages;
import com.baeldung.core.packages.domain.TodoItem;
import java.time.LocalDate;
public class TodoApp {
public static void main(String[] args) {
TodoList todoList = new TodoList();
for (int i = 0; i < 3; i++) {
TodoItem item = new TodoItem();
item.setId(Long.valueOf((long)i));
item.setDescription("Todo item " + (i + 1));
item.setDueDate(LocalDate.now().plusDays((long)(i + 1)));
todoList.addTodoItem(item);
}
todoList.getTodoItems().forEach((TodoItem todoItem) -> System.out.println(todoItem.toString()));
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.core.packages;
import com.baeldung.core.packages.domain.TodoItem;
import java.util.ArrayList;
import java.util.List;
public class TodoList {
private List<TodoItem> todoItems;
public void addTodoItem(TodoItem todoItem) {
if (todoItems == null) {
todoItems = new ArrayList<TodoItem>();
}
todoItems.add(todoItem);
}
public List<TodoItem> getTodoItems() {
return todoItems;
}
public void setTodoItems(List<TodoItem> todoItems) {
this.todoItems = todoItems;
}
}

View File

@@ -0,0 +1,39 @@
package com.baeldung.core.packages.domain;
import java.time.LocalDate;
public class TodoItem {
private Long id;
private String description;
private LocalDate dueDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDate getDueDate() {
return dueDate;
}
public void setDueDate(LocalDate dueDate) {
this.dueDate = dueDate;
}
@Override
public String toString() {
return "TodoItem [id=" + id + ", description=" + description + ", dueDate=" + dueDate + "]";
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.core.scope;
public class BracketScopeExample {
public void mathOperationExample() {
Integer sum = 0;
{
Integer number = 2;
sum = sum + number;
}
// compiler error, number cannot be solved as a variable
// number++;
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.core.scope;
public class ClassScopeExample {
Integer amount = 0;
public void exampleMethod() {
amount++;
}
public void anotherExampleMethod() {
Integer anotherAmount = amount + 4;
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.core.scope;
import java.util.Arrays;
import java.util.List;
public class LoopScopeExample {
List<String> listOfNames = Arrays.asList("Joe", "Susan", "Pattrick");
public void iterationOfNames() {
String allNames = "";
for (String name : listOfNames) {
allNames = allNames + " " + name;
}
// compiler error, name cannot be resolved to a variable
// String lastNameUsed = name;
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.core.scope;
public class MethodScopeExample {
public void methodA() {
Integer area = 2;
}
public void methodB() {
// compiler error, area cannot be resolved to a variable
// area = area + 2;
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.core.scope;
public class NestedScopesExample {
String title = "Baeldung";
public void printTitle() {
System.out.println(title);
String title = "John Doe";
System.out.println(title);
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.core.doublebrace;
import org.junit.Test;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toSet;
import static org.junit.Assert.assertTrue;
public class DoubleBraceUnitTest {
@Test
public void whenInitializeSetWithoutDoubleBraces_containsElements() {
final Set<String> countries = new HashSet<>();
countries.add("India");
countries.add("USSR");
countries.add("USA");
assertTrue(countries.contains("India"));
}
@Test
public void whenInitializeSetWithDoubleBraces_containsElements() {
final Set<String> countries = new HashSet<String>() {
{
add("India");
add("USSR");
add("USA");
}
};
assertTrue(countries.contains("India"));
}
@Test
public void whenInitializeUnmodifiableSetWithDoubleBrace_containsElements() {
Set<String> countries = Stream.of("India", "USSR", "USA")
.collect(collectingAndThen(toSet(), Collections::unmodifiableSet));
assertTrue(countries.contains("India"));
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.core.nativekeyword;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import static org.junit.Assert.assertNotNull;
public class DateTimeUtilsManualTest {
private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(DateTimeUtilsManualTest.class);
@BeforeClass
public static void setUpClass() {
System.loadLibrary("msvcr100");
System.loadLibrary("libgcc_s_sjlj-1");
System.loadLibrary("libstdc++-6");
System.loadLibrary("nativedatetimeutils");
}
@Test
public void givenNativeLibsLoaded_thenNativeMethodIsAccessible() {
DateTimeUtils dateTimeUtils = new DateTimeUtils();
LOG.info("System time is : " + dateTimeUtils.getSystemTime());
assertNotNull(dateTimeUtils.getSystemTime());
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.core.packages;
import com.baeldung.core.packages.domain.TodoItem;
import org.junit.Test;
import java.time.LocalDate;
import static org.junit.Assert.assertEquals;
public class PackagesUnitTest {
@Test
public void whenTodoItemAdded_ThenSizeIncreases() {
TodoItem todoItem = new TodoItem();
todoItem.setId(1L);
todoItem.setDescription("Test the Todo List");
todoItem.setDueDate(LocalDate.now());
TodoList todoList = new TodoList();
todoList.addTodoItem(todoItem);
assertEquals(1, todoList.getTodoItems().size());
}
}