[BAEL-9555] - Created a core-java-modules folder

This commit is contained in:
amit2103
2019-05-05 17:22:09 +05:30
parent 8b63b0d90a
commit 3bae5e5334
1480 changed files with 25600 additions and 5594 deletions

View File

@@ -0,0 +1,26 @@
package com.baeldung.assertion;
/**
* Simple demonstration of using Java assert keyword.
*/
public class Assertion {
public static void main(String[] args) {
Assertion assertion = new Assertion();
assertion.setup();
}
public void setup() {
Object conn = getConnection();
assert conn != null : "Connection is null";
// continue with other setup ...
}
// Simulate failure to get a connection; using Object
// to avoid dependencies on JDBC or some other heavy
// 3rd party library
public Object getConnection() {
return null;
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.binding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by madhumita.g on 25-07-2018.
*/
public class Animal {
final static Logger logger = LoggerFactory.getLogger(Animal.class);
public void makeNoise() {
logger.info("generic animal noise");
}
public void makeNoise(Integer repetitions) {
while(repetitions != 0) {
logger.info("generic animal noise countdown " + repetitions);
repetitions -= 1;
}
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.binding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by madhumita.g on 25-07-2018.
*/
public class AnimalActivity {
final static Logger logger = LoggerFactory.getLogger(AnimalActivity.class);
public static void sleep(Animal animal) {
logger.info("Animal is sleeping");
}
public static void sleep(Cat cat) {
logger.info("Cat is sleeping");
}
public static void main(String[] args) {
Animal animal = new Animal();
//calling methods of animal object
animal.makeNoise();
animal.makeNoise(3);
//assigning a dog object to reference of type Animal
Animal catAnimal = new Cat();
catAnimal.makeNoise();
// calling static function
AnimalActivity.sleep(catAnimal);
return;
}
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.binding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by madhumita.g on 25-07-2018.
*/
public class Cat extends Animal {
final static Logger logger = LoggerFactory.getLogger(Cat.class);
public void makeNoise() {
logger.info("meow");
}
}

View File

@@ -0,0 +1,41 @@
package com.baeldung.chainedexception;
import com.baeldung.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
import com.baeldung.chainedexception.exceptions.ManagerUpsetException;
import com.baeldung.chainedexception.exceptions.NoLeaveGrantedException;
import com.baeldung.chainedexception.exceptions.TeamLeadUpsetException;
public class LogWithChain {
public static void main(String[] args) throws Exception {
getLeave();
}
private static void getLeave() throws NoLeaveGrantedException {
try {
howIsTeamLead();
} catch (TeamLeadUpsetException e) {
throw new NoLeaveGrantedException("Leave not sanctioned.", e);
}
}
private static void howIsTeamLead() throws TeamLeadUpsetException {
try {
howIsManager();
} catch (ManagerUpsetException e) {
throw new TeamLeadUpsetException("Team lead is not in good mood", e);
}
}
private static void howIsManager() throws ManagerUpsetException {
try {
howIsGirlFriendOfManager();
} catch (GirlFriendOfManagerUpsetException e) {
throw new ManagerUpsetException("Manager is in bad mood", e);
}
}
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
}
}

View File

@@ -0,0 +1,44 @@
package com.baeldung.chainedexception;
import com.baeldung.chainedexception.exceptions.GirlFriendOfManagerUpsetException;
import com.baeldung.chainedexception.exceptions.ManagerUpsetException;
import com.baeldung.chainedexception.exceptions.NoLeaveGrantedException;
import com.baeldung.chainedexception.exceptions.TeamLeadUpsetException;
public class LogWithoutChain {
public static void main(String[] args) throws Exception {
getLeave();
}
private static void getLeave() throws NoLeaveGrantedException {
try {
howIsTeamLead();
} catch (TeamLeadUpsetException e) {
e.printStackTrace();
throw new NoLeaveGrantedException("Leave not sanctioned.");
}
}
private static void howIsTeamLead() throws TeamLeadUpsetException {
try {
howIsManager();
} catch (ManagerUpsetException e) {
e.printStackTrace();
throw new TeamLeadUpsetException("Team lead is not in good mood");
}
}
private static void howIsManager() throws ManagerUpsetException {
try {
howIsGirlFriendOfManager();
} catch (GirlFriendOfManagerUpsetException e) {
e.printStackTrace();
throw new ManagerUpsetException("Manager is in bad mood");
}
}
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.chainedexception.exceptions;
public class GirlFriendOfManagerUpsetException extends Exception {
public GirlFriendOfManagerUpsetException(String message, Throwable cause) {
super(message, cause);
}
public GirlFriendOfManagerUpsetException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.chainedexception.exceptions;
public class ManagerUpsetException extends Exception {
public ManagerUpsetException(String message, Throwable cause) {
super(message, cause);
}
public ManagerUpsetException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.chainedexception.exceptions;
public class NoLeaveGrantedException extends Exception {
public NoLeaveGrantedException(String message, Throwable cause) {
super(message, cause);
}
public NoLeaveGrantedException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.chainedexception.exceptions;
public class TeamLeadUpsetException extends Exception {
public TeamLeadUpsetException(String message, Throwable cause) {
super(message, cause);
}
public TeamLeadUpsetException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.className;
public class RetrievingClassName {
public class InnerClass {
}
}

View File

@@ -0,0 +1,51 @@
package com.baeldung.comparable;
public class Player implements Comparable<Player> {
private int ranking;
private String name;
private int age;
public Player(int ranking, String name, int age) {
this.ranking = ranking;
this.name = name;
this.age = age;
}
public int getRanking() {
return ranking;
}
public void setRanking(int ranking) {
this.ranking = ranking;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return this.name;
}
@Override
public int compareTo(Player otherPlayer) {
return (this.getRanking() - otherPlayer.getRanking());
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.comparable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PlayerSorter {
public static void main(String[] args) {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 20);
Player player2 = new Player(67, "Roger", 22);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
System.out.println("Before Sorting : " + footballTeam);
Collections.sort(footballTeam);
System.out.println("After Sorting : " + footballTeam);
}
}

View File

@@ -0,0 +1,46 @@
package com.baeldung.comparator;
public class Player {
private int ranking;
private String name;
private int age;
public Player(int ranking, String name, int age) {
this.ranking = ranking;
this.name = name;
this.age = age;
}
public int getRanking() {
return ranking;
}
public void setRanking(int ranking) {
this.ranking = ranking;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return this.name;
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.comparator;
import java.util.Comparator;
public class PlayerAgeComparator implements Comparator<Player> {
@Override
public int compare(Player firstPlayer, Player secondPlayer) {
return (firstPlayer.getAge() - secondPlayer.getAge());
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PlayerAgeSorter {
public static void main(String[] args) {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 22);
Player player2 = new Player(67, "Roger", 20);
Player player3 = new Player(45, "Steven", 24);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
System.out.println("Before Sorting : " + footballTeam);
//Instance of PlayerAgeComparator
PlayerAgeComparator playerComparator = new PlayerAgeComparator();
Collections.sort(footballTeam, playerComparator);
System.out.println("After Sorting by age : " + footballTeam);
}
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.comparator;
import java.util.Comparator;
public class PlayerRankingComparator implements Comparator<Player> {
@Override
public int compare(Player firstPlayer, Player secondPlayer) {
return (firstPlayer.getRanking() - secondPlayer.getRanking());
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.comparator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PlayerRankingSorter {
public static void main(String[] args) {
List<Player> footballTeam = new ArrayList<Player>();
Player player1 = new Player(59, "John", 22);
Player player2 = new Player(67, "Roger", 20);
Player player3 = new Player(45, "Steven", 40);
footballTeam.add(player1);
footballTeam.add(player2);
footballTeam.add(player3);
System.out.println("Before Sorting : " + footballTeam);
//Instance of PlayerRankingComparator
PlayerRankingComparator playerComparator = new PlayerRankingComparator();
Collections.sort(footballTeam, playerComparator);
System.out.println("After Sorting by ranking : " + footballTeam);
}
}

View File

@@ -0,0 +1,68 @@
package com.baeldung.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.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,43 @@
package com.baeldung.customexception;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileManager {
public static String getFirstLine(String fileName) throws IncorrectFileNameException {
try (Scanner file = new Scanner(new File(fileName))) {
if (file.hasNextLine()) {
return file.nextLine();
} else {
throw new IllegalArgumentException("Non readable file");
}
} catch (FileNotFoundException err) {
if (!isCorrectFileName(fileName)) {
throw new IncorrectFileNameException("Incorrect filename : " + fileName, err);
}
// Logging etc
} catch (IllegalArgumentException err) {
if (!containsExtension(fileName)) {
throw new IncorrectFileExtensionException("Filename does not contain extension : " + fileName, err);
}
// Other error cases and logging
}
return "Default First Line";
}
private static boolean containsExtension(String fileName) {
if (fileName.contains(".txt") || fileName.contains(".doc"))
return true;
return false;
}
private static boolean isCorrectFileName(String fileName) {
if (fileName.equals("wrongFileName.txt"))
return false;
else
return true;
}
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.customexception;
public class IncorrectFileExtensionException extends RuntimeException{
private static final long serialVersionUID = 1L;
public IncorrectFileExtensionException(String errorMessage, Throwable err) {
super(errorMessage, err);
}
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.customexception;
public class IncorrectFileNameException extends Exception {
private static final long serialVersionUID = 1L;
public IncorrectFileNameException(String errorMessage, Throwable err) {
super(errorMessage, err);
}
}

View File

@@ -0,0 +1,40 @@
package com.baeldung.doubles;
import java.math.BigDecimal;
public class SplitFloatingPointNumbers {
public static void main(String[] args) {
double doubleNumber = 24.04;
splitUsingFloatingTypes(doubleNumber);
splitUsingString(doubleNumber);
splitUsingBigDecimal(doubleNumber);
}
private static void splitUsingFloatingTypes(double doubleNumber) {
System.out.println("Using Floating Point Arithmetics:");
int intPart = (int) doubleNumber;
System.out.println("Double Number: "+doubleNumber);
System.out.println("Integer Part: "+ intPart);
System.out.println("Decimal Part: "+ (doubleNumber - intPart));
}
private static void splitUsingString(double doubleNumber) {
System.out.println("Using String Operations:");
String doubleAsString = String.valueOf(doubleNumber);
int indexOfDecimal = doubleAsString.indexOf(".");
System.out.println("Double Number: "+doubleNumber);
System.out.println("Integer Part: "+ doubleAsString.substring(0, indexOfDecimal));
System.out.println("Decimal Part: "+ doubleAsString.substring(indexOfDecimal));
}
private static void splitUsingBigDecimal(double doubleNumber) {
System.out.println("Using BigDecimal Operations:");
BigDecimal bigDecimal = new BigDecimal(String.valueOf(doubleNumber));
int intValue = bigDecimal.intValue();
System.out.println("Double Number: "+bigDecimal.toPlainString());
System.out.println("Integer Part: "+intValue);
System.out.println("Decimal Part: "+bigDecimal.subtract(new BigDecimal(intValue)).toPlainString());
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.dynamicproxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class DynamicInvocationHandler implements InvocationHandler {
private static Logger LOGGER = LoggerFactory.getLogger(DynamicInvocationHandler.class);
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
LOGGER.info("Invoked method: {}", method.getName());
return 42;
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.dynamicproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TimingDynamicInvocationHandler implements InvocationHandler {
private static Logger LOGGER = LoggerFactory.getLogger(TimingDynamicInvocationHandler.class);
private final Map<String, Method> methods = new HashMap<>();
private Object target;
TimingDynamicInvocationHandler(Object target) {
this.target = target;
for(Method method: target.getClass().getDeclaredMethods()) {
this.methods.put(method.getName(), method);
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
long start = System.nanoTime();
Object result = methods.get(method.getName()).invoke(target, args);
long elapsed = System.nanoTime() - start;
LOGGER.info("Executing {} finished in {} ns", method.getName(), elapsed);
return result;
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.enums.values;
/**
* This is a simple enum of periodic table elements
*/
public enum Element1 {
H,
HE,
LI,
BE,
B,
C,
N,
O,
F,
NE
}

View File

@@ -0,0 +1,52 @@
package com.baeldung.enums.values;
/**
* The simple enum has been enhanced to add the name of the element.
*/
public enum Element2 {
H("Hydrogen"),
HE("Helium"),
LI("Lithium"),
BE("Beryllium"),
B("Boron"),
C("Carbon"),
N("Nitrogen"),
O("Oxygen"),
F("Flourine"),
NE("Neon");
/** a final variable to store the label, which can't be changed */
public final String label;
/**
* A private constructor that sets the label.
* @param label
*/
private Element2(String label) {
this.label = label;
}
/**
* Look up Element2 instances by the label field. This implementation iterates through
* the values() list to find the label.
* @param label The label to look up
* @return The Element2 instance with the label, or null if not found.
*/
public static Element2 valueOfLabel(String label) {
for (Element2 e2 : values()) {
if (e2.label.equals(label)) {
return e2;
}
}
return null;
}
/**
* Override the toString() method to return the label instead of the declared name.
* @return
*/
@Override
public String toString() {
return this.label;
}
}

View File

@@ -0,0 +1,63 @@
package com.baeldung.enums.values;
import java.util.HashMap;
import java.util.Map;
/**
* A Map has been added to cache labels for faster lookup.
*/
public enum Element3 {
H("Hydrogen"),
HE("Helium"),
LI("Lithium"),
BE("Beryllium"),
B("Boron"),
C("Carbon"),
N("Nitrogen"),
O("Oxygen"),
F("Flourine"),
NE("Neon");
/**
* A map to cache labels and their associated Element3 instances.
* Note that this only works if the labels are all unique!
*/
private static final Map<String, Element3> BY_LABEL = new HashMap<>();
/** populate the BY_LABEL cache */
static {
for (Element3 e3 : values()) {
BY_LABEL.put(e3.label, e3);
}
}
/** a final variable to store the label, which can't be changed */
public final String label;
/**
* A private constructor that sets the label.
* @param label
*/
private Element3(String label) {
this.label = label;
}
/**
* Look up Element2 instances by the label field. This implementation finds the
* label in the BY_LABEL cache.
* @param label The label to look up
* @return The Element3 instance with the label, or null if not found.
*/
public static Element3 valueOfLabel(String label) {
return BY_LABEL.get(label);
}
/**
* Override the toString() method to return the label instead of the declared name.
* @return
*/
@Override
public String toString() {
return this.label;
}
}

View File

@@ -0,0 +1,95 @@
package com.baeldung.enums.values;
import java.util.HashMap;
import java.util.Map;
/**
* Multiple fields have been added and the Labeled interface is implemented.
*/
public enum Element4 implements Labeled {
H("Hydrogen", 1, 1.008f),
HE("Helium", 2, 4.0026f),
LI("Lithium", 3, 6.94f),
BE("Beryllium", 4, 9.01722f),
B("Boron", 5, 10.81f),
C("Carbon", 6, 12.011f),
N("Nitrogen", 7, 14.007f),
O("Oxygen", 8, 15.999f),
F("Flourine", 9, 18.998f),
NE("Neon", 10, 20.180f);
/**
* Maps cache labels and their associated Element3 instances.
* Note that this only works if the values are all unique!
*/
private static final Map<String, Element4> BY_LABEL = new HashMap<>();
private static final Map<Integer, Element4> BY_ATOMIC_NUMBER = new HashMap<>();
private static final Map<Float, Element4> BY_ATOMIC_WEIGHT = new HashMap<>();
/** populate the caches */
static {
for (Element4 e4 : values()) {
BY_LABEL.put(e4.label, e4);
BY_ATOMIC_NUMBER.put(e4.atomicNumber, e4);
BY_ATOMIC_WEIGHT.put(e4.atomicWeight, e4);
}
}
/** final variables to store the values, which can't be changed */
public final String label;
public final int atomicNumber;
public final float atomicWeight;
private Element4(String label, int atomicNumber, float atomicWeight) {
this.label = label;
this.atomicNumber = atomicNumber;
this.atomicWeight = atomicWeight;
}
/**
* Implement the Labeled interface.
* @return the label value
*/
@Override
public String label() {
return label;
}
/**
* Look up Element2 instances by the label field. This implementation finds the
* label in the BY_LABEL cache.
* @param label The label to look up
* @return The Element4 instance with the label, or null if not found.
*/
public static Element4 valueOfLabel(String label) {
return BY_LABEL.get(label);
}
/**
* Look up Element2 instances by the atomicNumber field. This implementation finds the
* atomicNUmber in the cache.
* @param number The atomicNumber to look up
* @return The Element4 instance with the label, or null if not found.
*/
public static Element4 valueOfAtomicNumber(int number) {
return BY_ATOMIC_NUMBER.get(number);
}
/**
* Look up Element2 instances by the atomicWeight field. This implementation finds the
* atomic weight in the cache.
* @param weight the atomic weight to look up
* @return The Element4 instance with the label, or null if not found.
*/
public static Element4 valueOfAtomicWeight(float weight) {
return BY_ATOMIC_WEIGHT.get(weight);
}
/**
* Override the toString() method to return the label instead of the declared name.
* @return
*/
@Override
public String toString() {
return this.label;
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.enums.values;
public interface Labeled {
String label();
}

View File

@@ -0,0 +1,212 @@
package com.baeldung.exceptionhandling;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Logger;
import java.util.stream.Collectors;
public class Exceptions {
private final static Logger logger = Logger.getLogger("ExceptionLogging");
public static List<Player> getPlayers() throws IOException {
Path path = Paths.get("players.dat");
List<String> players = Files.readAllLines(path);
return players.stream()
.map(Player::new)
.collect(Collectors.toList());
}
public List<Player> loadAllPlayers(String playersFile) throws IOException{
try {
throw new IOException();
} catch(IOException ex) {
throw new IllegalStateException();
}
}
public int getPlayerScoreThrows(String playerFile) throws FileNotFoundException {
Scanner contents = new Scanner(new File(playerFile));
return Integer.parseInt(contents.nextLine());
}
public int getPlayerScoreTryCatch(String playerFile) {
try {
Scanner contents = new Scanner(new File(playerFile));
return Integer.parseInt(contents.nextLine());
} catch (FileNotFoundException noFile) {
throw new IllegalArgumentException("File not found");
}
}
public int getPlayerScoreTryCatchRecovery(String playerFile) {
try {
Scanner contents = new Scanner(new File(playerFile));
return Integer.parseInt(contents.nextLine());
} catch ( FileNotFoundException noFile ) {
logger.warning("File not found, resetting score.");
return 0;
}
}
public int getPlayerScoreFinally(String playerFile) throws FileNotFoundException {
Scanner contents = null;
try {
contents = new Scanner(new File(playerFile));
return Integer.parseInt(contents.nextLine());
} finally {
if (contents != null) {
contents.close();
}
}
}
public int getPlayerScoreTryWithResources(String playerFile) {
try (Scanner contents = new Scanner(new File(playerFile))) {
return Integer.parseInt(contents.nextLine());
} catch (FileNotFoundException e ) {
logger.warning("File not found, resetting score.");
return 0;
}
}
public int getPlayerScoreMultipleCatchBlocks(String playerFile) {
try (Scanner contents = new Scanner(new File(playerFile))) {
return Integer.parseInt(contents.nextLine());
} catch (IOException e) {
logger.warning("Player file wouldn't load!");
return 0;
} catch (NumberFormatException e) {
logger.warning("Player file was corrupted!");
return 0;
}
}
public int getPlayerScoreMultipleCatchBlocksAlternative(String playerFile) {
try (Scanner contents = new Scanner(new File(playerFile)) ) {
return Integer.parseInt(contents.nextLine());
} catch (FileNotFoundException e) {
logger.warning("Player file not found!");
return 0;
} catch (IOException e) {
logger.warning("Player file wouldn't load!");
return 0;
} catch (NumberFormatException e) {
logger.warning("Player file was corrupted!");
return 0;
}
}
public int getPlayerScoreUnionCatchBlocks(String playerFile) {
try (Scanner contents = new Scanner(new File(playerFile))) {
return Integer.parseInt(contents.nextLine());
} catch (IOException | NumberFormatException e) {
logger.warning("Failed to load score!");
return 0;
}
}
public List<Player> loadAllPlayersThrowingChecked(String playersFile) throws TimeoutException {
boolean tooLong = true;
while (!tooLong) {
// ... potentially long operation
}
throw new TimeoutException("This operation took too long");
}
public List<Player> loadAllPlayersThrowingUnchecked(String playersFile) throws TimeoutException {
if(!isFilenameValid(playersFile)) {
throw new IllegalArgumentException("Filename isn't valid!");
}
return null;
// ...
}
public List<Player> loadAllPlayersWrapping(String playersFile) throws IOException {
try {
throw new IOException();
} catch (IOException io) {
throw io;
}
}
public List<Player> loadAllPlayersRethrowing(String playersFile) throws PlayerLoadException {
try {
throw new IOException();
} catch (IOException io) {
throw new PlayerLoadException(io);
}
}
public List<Player> loadAllPlayersThrowable(String playersFile) {
try {
throw new NullPointerException();
} catch ( Throwable t ) {
throw t;
}
}
class FewerExceptions extends Exceptions {
@Override
public List<Player> loadAllPlayers(String playersFile) { //can't add "throws MyCheckedException
return null;
// overridden
}
}
public void throwAsGotoAntiPattern() throws MyException {
try {
// bunch of code
throw new MyException();
// second bunch of code
} catch ( MyException e ) {
// third bunch of code
}
}
public int getPlayerScoreSwallowingExceptionAntiPattern(String playerFile) {
try {
// ...
} catch (Exception e) {} // <== catch and swallow
return 0;
}
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative(String playerFile) {
try {
// ...
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative2(String playerFile) throws PlayerScoreException {
try {
throw new IOException();
} catch (IOException e) {
throw new PlayerScoreException(e);
}
}
public int getPlayerScoreReturnInFinallyAntiPattern(String playerFile) {
int score = 0;
try {
throw new IOException();
} finally {
return score; // <== the IOException is dropped
}
}
private boolean isFilenameValid(String name) {
return false;
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.exceptionhandling;
public class MyException extends Throwable {
}

View File

@@ -0,0 +1,12 @@
package com.baeldung.exceptionhandling;
public class Player {
public int id;
public String name;
public Player(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,11 @@
package com.baeldung.exceptionhandling;
import java.io.IOException;
public class PlayerLoadException extends Exception {
public PlayerLoadException(IOException io) {
super(io);
}
}

View File

@@ -0,0 +1,8 @@
package com.baeldung.exceptionhandling;
public class PlayerScoreException extends Exception {
public PlayerScoreException(Exception e) {
super(e);
}
}

View File

@@ -0,0 +1,8 @@
package com.baeldung.exceptionhandling;
public class TimeoutException extends Exception {
public TimeoutException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.finalize;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class CloseableResource implements AutoCloseable {
private BufferedReader reader;
public CloseableResource() {
InputStream input = this.getClass().getClassLoader().getResourceAsStream("file.txt");
reader = new BufferedReader(new InputStreamReader(input));
}
public String readFirstLine() throws IOException {
String firstLine = reader.readLine();
return firstLine;
}
@Override
public void close() {
try {
reader.close();
System.out.println("Closed BufferedReader in the close method");
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,30 @@
package com.baeldung.finalize;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Finalizable {
private BufferedReader reader;
public Finalizable() {
InputStream input = this.getClass().getClassLoader().getResourceAsStream("file.txt");
reader = new BufferedReader(new InputStreamReader(input));
}
public String readFirstLine() throws IOException {
String firstLine = reader.readLine();
return firstLine;
}
@Override
public void finalize() {
try {
reader.close();
System.out.println("Closed BufferedReader in the finalizer");
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.interfaces;
public interface Box extends HasColor {
int getHeight();
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.interfaces;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class CommaSeparatedCustomers implements Customer.List {
private List<Customer> customers = new ArrayList<Customer>();
@Override
public void Add(Customer customer) {
customers.add(customer);
}
@Override
public String getCustomerNames() {
return customers.stream().map(customer -> customer.getName()).collect(Collectors.joining(","));
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.interfaces;
public class Customer {
public interface List {
void Add(Customer customer);
String getCustomerNames();
}
private String name;
public Customer(String name) {
this.name = name;
}
String getName() {
return name;
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.interfaces;
public class Employee {
private double salary;
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.interfaces;
import java.util.Comparator;
public class EmployeeSalaryComparator implements Comparator<Employee> {
@Override
public int compare(Employee employeeA, Employee employeeB) {
if (employeeA.getSalary() < employeeB.getSalary()) {
return -1;
} else if (employeeA.getSalary() > employeeB.getSalary()) {
return 1;
} else {
return 0;
}
}
}

View File

@@ -0,0 +1,4 @@
package com.baeldung.interfaces;
public interface HasColor {
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.interfaces.multiinheritance;
public class Car implements Fly,Transform {
@Override
public void fly() {
System.out.println("I can Fly!!");
}
@Override
public void transform() {
System.out.println("I can Transform!!");
}
}

View File

@@ -0,0 +1,6 @@
package com.baeldung.interfaces.multiinheritance;
public interface Fly {
void fly();
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.interfaces.multiinheritance;
public interface Transform {
void transform();
default void printSpecs(){
System.out.println("Transform Specification");
}
}

View File

@@ -0,0 +1,4 @@
package com.baeldung.interfaces.multiinheritance;
public abstract class Vehicle implements Transform {
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.interfaces.polymorphysim;
public class Circle implements Shape {
@Override
public String name() {
return "Circle";
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.interfaces.polymorphysim;
import java.util.ArrayList;
import java.util.List;
public class MainTestClass {
public static void main(String[] args) {
List<Shape> shapes = new ArrayList<>();
Shape circleShape = new Circle();
Shape squareShape = new Square();
shapes.add(circleShape);
shapes.add(squareShape);
for (Shape shape : shapes) {
System.out.println(shape.name());
}
}
}

View File

@@ -0,0 +1,6 @@
package com.baeldung.interfaces.polymorphysim;
public interface Shape {
String name();
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.interfaces.polymorphysim;
public class Square implements Shape {
@Override
public String name() {
return "Square";
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.java.reflection;
public abstract class Animal implements Eating {
public static final String CATEGORY = "domestic";
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
protected abstract String getSound();
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.java.reflection;
public class Bird extends Animal {
private boolean walks;
public Bird() {
super("bird");
}
public Bird(String name, boolean walks) {
super(name);
setWalks(walks);
}
public Bird(String name) {
super(name);
}
@Override
public String eats() {
return "grains";
}
@Override
protected String getSound() {
return "chaps";
}
public boolean walks() {
return walks;
}
public void setWalks(boolean walks) {
this.walks = walks;
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.java.reflection;
import java.lang.annotation.Annotation;
public class DynamicGreeter implements Greeter {
private String greet;
public DynamicGreeter(String greet) {
this.greet = greet;
}
@Override
public Class<? extends Annotation> annotationType() {
return DynamicGreeter.class;
}
@Override
public String greet() {
return greet;
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.java.reflection;
public interface Eating {
String eats();
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.java.reflection;
public class Goat extends Animal implements Locomotion {
public Goat(String name) {
super(name);
}
@Override
protected String getSound() {
return "bleat";
}
@Override
public String getLocomotion() {
return "walks";
}
@Override
public String eats() {
return "grass";
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.java.reflection;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Greeter {
public String greet() default "";
}

View File

@@ -0,0 +1,58 @@
package com.baeldung.java.reflection;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
public class GreetingAnnotation {
private static final String ANNOTATION_METHOD = "annotationData";
private static final String ANNOTATION_FIELDS = "declaredAnnotations";
private static final String ANNOTATIONS = "annotations";
public static void main(String ...args) {
Greeter greetings = Greetings.class.getAnnotation(Greeter.class);
System.err.println("Hello there, " + greetings.greet() + " !!");
Greeter targetValue = new DynamicGreeter("Good evening");
//alterAnnotationValueJDK8(Greetings.class, Greeter.class, targetValue);
alterAnnotationValueJDK7(Greetings.class, Greeter.class, targetValue);
greetings = Greetings.class.getAnnotation(Greeter.class);
System.err.println("Hello there, " + greetings.greet() + " !!");
}
@SuppressWarnings("unchecked")
public static void alterAnnotationValueJDK8(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) {
try {
Method method = Class.class.getDeclaredMethod(ANNOTATION_METHOD, null);
method.setAccessible(true);
Object annotationData = method.invoke(targetClass);
Field annotations = annotationData.getClass().getDeclaredField(ANNOTATIONS);
annotations.setAccessible(true);
Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(annotationData);
map.put(targetAnnotation, targetValue);
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static void alterAnnotationValueJDK7(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) {
try {
Field annotations = Class.class.getDeclaredField(ANNOTATIONS);
annotations.setAccessible(true);
Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(targetClass);
System.out.println(map);
map.put(targetAnnotation, targetValue);
System.out.println(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,6 @@
package com.baeldung.java.reflection;
@Greeter(greet="Good morning")
public class Greetings {
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.java.reflection;
public interface Locomotion {
String getLocomotion();
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.java.reflection;
public class Operations {
public double publicSum(int a, double b) {
return a + b;
}
public static double publicStaticMultiply(float a, long b) {
return a * b;
}
private boolean privateAnd(boolean a, boolean b) {
return a && b;
}
protected int protectedMax(int a, int b) {
return a > b ? a : b;
}
}

View File

@@ -0,0 +1,6 @@
package com.baeldung.java.reflection;
public class Person {
private String name;
private int age;
}

View File

@@ -0,0 +1,18 @@
package com.baeldung.keywords.finalize;
public class FinalizeObject {
@Override
protected void finalize() throws Throwable {
System.out.println("Execute finalize method");
super.finalize();
}
public static void main(String[] args) throws Exception {
FinalizeObject object = new FinalizeObject();
object = null;
System.gc();
Thread.sleep(1000);
}
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.keywords.finalkeyword;
public final class Child extends Parent {
@Override
void method1(int arg1, final int arg2) {
// OK
}
/* @Override
void method2() {
// Compilation error
}*/
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.keywords.finalkeyword;
/*public class GrandChild extends Child {
// Compilation error
}*/

View File

@@ -0,0 +1,23 @@
package com.baeldung.keywords.finalkeyword;
public class Parent {
int field1 = 1;
final int field2 = 2;
Parent() {
field1 = 2; // OK
// field2 = 3; // Compilation error
}
void method1(int arg1, final int arg2) {
arg1 = 2; // OK
// arg2 = 3; // Compilation error
}
final void method2() {
final int localVar = 2; // OK
// localVar = 3; // Compilation error
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.keywords.finallykeyword;
public class FinallyExample {
public static void main(String args[]) throws Exception {
try {
System.out.println("Execute try block");
throw new Exception();
} catch (Exception e) {
System.out.println("Execute catch block");
} finally {
System.out.println("Execute finally block");
}
try {
System.out.println("Execute try block");
} finally {
System.out.println("Execute finally block");
}
try {
System.out.println("Execute try block");
throw new Exception();
} finally {
System.out.println("Execute finally block");
}
}
}

View File

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

View File

@@ -0,0 +1,11 @@
package com.baeldung.nativekeyword;
import com.baeldung.nativekeyword.DateTimeUtils;
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,5 @@
package com.baeldung.noclassdeffounderror;
public class ClassWithInitErrors {
static int data = 1 / 0;
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.noclassdeffounderror;
public class NoClassDefFoundErrorExample {
public ClassWithInitErrors getClassWithInitErrors() {
ClassWithInitErrors test;
try {
test = new ClassWithInitErrors();
} catch (Throwable t) {
System.out.println(t);
}
test = new ClassWithInitErrors();
return test;
}
}

View File

@@ -0,0 +1,51 @@
package com.baeldung.objects;
public class Car {
private String type;
private String model;
private String color;
private int speed;
public Car(String type, String model, String color) {
this.type = type;
this.model = model;
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getSpeed() {
return speed;
}
public int increaseSpeed(int increment) {
if (increment > 0) {
this.speed += increment;
} else {
System.out.println("Increment can't be negative.");
}
return this.speed;
}
public int decreaseSpeed(int decrement) {
if (decrement > 0 && decrement <= this.speed) {
this.speed -= decrement;
} else {
System.out.println("Decrement can't be negative or greater than current speed.");
}
return this.speed;
}
@Override
public String toString() {
return "Car [type=" + type + ", model=" + model + ", color=" + color + ", speed=" + speed + "]";
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.packages;
import java.time.LocalDate;
import com.baeldung.packages.domain.TodoItem;
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.packages;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.packages.domain.TodoItem;
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.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,27 @@
package com.baeldung.parameterpassing;
public class NonPrimitives {
public static void main(String[] args) {
FooClass a = new FooClass(1);
FooClass b = new FooClass(1);
System.out.printf("Before Modification: a = %d and b = %d ", a.num, b.num);
modify(a, b);
System.out.printf("\nAfter Modification: a = %d and b = %d ", a.num, b.num);
}
public static void modify(FooClass a1, FooClass b1) {
a1.num++;
b1 = new FooClass(1);
b1.num++;
}
}
class FooClass {
public int num;
public FooClass(int num) {
this.num = num;
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.parameterpassing;
public class Primitives {
public static void main(String[] args) {
int x = 1;
int y = 2;
System.out.printf("Before Modification: x = %d and y = %d ", x, y);
modify(x, y);
System.out.printf("\nAfter Modification: x = %d and y = %d ", x, y);
}
public static void modify(int x1, int y1) {
x1 = 5;
y1 = 10;
}
}

View File

@@ -0,0 +1,31 @@
package com.baeldung.recursion;
public class BinaryNode {
int value;
BinaryNode left;
BinaryNode right;
public BinaryNode(int value){
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public BinaryNode getLeft() {
return left;
}
public void setLeft(BinaryNode left) {
this.left = left;
}
public BinaryNode getRight() {
return right;
}
public void setRight(BinaryNode right) {
this.right = right;
}
}

View File

@@ -0,0 +1,64 @@
package com.baeldung.recursion;
public class RecursionExample {
public int sum(int n){
if (n >= 1){
return sum(n - 1) + n;
}
return n;
}
public int tailSum(int currentSum, int n){
if (n <= 1) {
return currentSum + n;
}
return tailSum(currentSum + n, n - 1);
}
public int iterativeSum(int n){
int sum = 0;
if(n < 0){
return -1;
}
for(int i=0; i<=n; i++){
sum += i;
}
return sum;
}
public int powerOf10(int n){
if (n == 0){
return 1;
}
return powerOf10(n-1)*10;
}
public int fibonacci(int n){
if (n <=1 ){
return n;
}
return fibonacci(n-1) + fibonacci(n-2);
}
public String toBinary(int n){
if (n <= 1 ){
return String.valueOf(n);
}
return toBinary(n / 2) + String.valueOf(n % 2);
}
public int calculateTreeHeight(BinaryNode root){
if (root!= null){
if (root.getLeft() != null || root.getRight() != null){
return 1 + max(calculateTreeHeight(root.left) , calculateTreeHeight(root.right));
}
}
return 0;
}
public int max(int a,int b){
return a>b ? a:b;
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.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.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.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.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.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,23 @@
package com.baeldung.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();
}
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.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();
}
}
}

View File

@@ -0,0 +1,8 @@
package com.baeldung.stackoverflowerror;
public class AccountHolder {
private String firstName;
private String lastName;
AccountHolder jointAccountHolder = new AccountHolder();
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.stackoverflowerror;
public class ClassOne {
private int oneValue;
private ClassTwo clsTwoInstance = null;
public ClassOne() {
oneValue = 0;
clsTwoInstance = new ClassTwo();
}
public ClassOne(int oneValue, ClassTwo clsTwoInstance) {
this.oneValue = oneValue;
this.clsTwoInstance = clsTwoInstance;
}
}

View File

@@ -0,0 +1,16 @@
package com.baeldung.stackoverflowerror;
public class ClassTwo {
private int twoValue;
private ClassOne clsOneInstance = null;
public ClassTwo() {
twoValue = 10;
clsOneInstance = new ClassOne();
}
public ClassTwo(int twoValue, ClassOne clsOneInstance) {
this.twoValue = twoValue;
this.clsOneInstance = clsOneInstance;
}
}

View File

@@ -0,0 +1,7 @@
package com.baeldung.stackoverflowerror;
public class InfiniteRecursionWithTerminationCondition {
public int calculateFactorial(final int number) {
return number == 1 ? 1 : number * calculateFactorial(number - 1);
}
}

View File

@@ -0,0 +1,7 @@
package com.baeldung.stackoverflowerror;
public class RecursionWithCorrectTerminationCondition {
public int calculateFactorial(final int number) {
return number <= 1 ? 1 : number * calculateFactorial(number - 1);
}
}

View File

@@ -0,0 +1,7 @@
package com.baeldung.stackoverflowerror;
public class UnintendedInfiniteRecursion {
public int calculateFactorial(int number) {
return number * calculateFactorial(number - 1);
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.synthetic;
import java.util.Comparator;
/**
* Class which contains a synthetic bridge method.
*
* @author Donato Rimenti
*
*/
public class BridgeMethodDemo implements Comparator<Integer> {
/*
* (non-Javadoc)
*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Integer o1, Integer o2) {
return 0;
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.synthetic;
/**
* Wrapper for a class which contains a synthetic constructor.
*
* @author Donato Rimenti
*
*/
public class SyntheticConstructorDemo {
/**
* We need to instantiate the {@link NestedClass} using a private
* constructor from the enclosing instance in order to generate a synthetic
* constructor.
*/
private NestedClass nestedClass = new NestedClass();
/**
* Class which contains a synthetic constructor.
*
* @author Donato Rimenti
*
*/
class NestedClass {
/**
* In order to generate a synthetic constructor, this class must have a
* private constructor.
*/
private NestedClass() {
}
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.synthetic;
/**
* Wrapper for a class which contains a synthetic field reference to the outer
* class.
*
* @author Donato Rimenti
*
*/
public class SyntheticFieldDemo {
/**
* Class which contains a synthetic field reference to the outer class.
*
* @author Donato Rimenti
*
*/
class NestedClass {
}
}

View File

@@ -0,0 +1,48 @@
package com.baeldung.synthetic;
/**
* Wrapper for a class which contains two synthetic methods accessors to a
* private field.
*
* @author Donato Rimenti
*
*/
public class SyntheticMethodDemo {
/**
* Class which contains two synthetic methods accessors to a private field.
*
* @author Donato Rimenti
*
*/
class NestedClass {
/**
* Field for which will be generated synthetic methods accessors. It's
* important that this field is private for this purpose.
*/
private String nestedField;
}
/**
* Gets the private nested field. We need to read the nested field in order
* to generate the synthetic getter.
*
* @return the {@link NestedClass#nestedField}
*/
public String getNestedField() {
return new NestedClass().nestedField;
}
/**
* Sets the private nested field. We need to write the nested field in order
* to generate the synthetic setter.
*
* @param nestedField
* the {@link NestedClass#nestedField}
*/
public void setNestedField(String nestedField) {
new NestedClass().nestedField = nestedField;
}
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.throwsexception;
public class DataAccessException extends RuntimeException {
public DataAccessException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@@ -0,0 +1,41 @@
package com.baeldung.throwsexception;
import com.sun.mail.iap.ConnectionException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.SocketException;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
TryCatch tryCatch = new TryCatch();
try {
tryCatch.execute();
} catch (ConnectionException | SocketException ex) {
System.out.println("IOException");
} catch (Exception ex) {
System.out.println("General exception");
}
checkedException();
checkedExceptionWithThrows();
}
private static void checkedExceptionWithThrows() throws FileNotFoundException {
File file = new File("not_existing_file.txt");
FileInputStream stream = new FileInputStream(file);
}
private static void checkedException() {
File file = new File("not_existing_file.txt");
try {
FileInputStream stream = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

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