Merge pull request #73 from eugenp/master

update
This commit is contained in:
Maiklins
2020-09-26 22:33:31 +02:00
committed by GitHub
262 changed files with 5951 additions and 884 deletions
+1
View File
@@ -5,3 +5,4 @@ This module contains articles about AWS Lambda
### Relevant Articles:
- [Using AWS Lambda with API Gateway](https://www.baeldung.com/aws-lambda-api-gateway)
- [Introduction to AWS Serverless Application Model](https://www.baeldung.com/aws-serverless)
- [How to Implement Hibernate in an AWS Lambda Function in Java](https://www.baeldung.com/java-aws-lambda-hibernate)
+3
View File
@@ -0,0 +1,3 @@
### Relevant Articles:
- [How to Remove a Prefix From Strings in Groovy](https://www.baeldung.com/groovy-remove-string-prefix)
+122
View File
@@ -0,0 +1,122 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>
<artifactId>core-groovy-strings</artifactId>
<version>1.0-SNAPSHOT</version>
<name>core-groovy-strings</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>${groovy.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${groovy-all.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-dateutil</artifactId>
<version>${groovy.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-sql</artifactId>
<version>${groovy-sql.version}</version>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>${spock-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>${gmavenplus-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>addSources</goal>
<goal>addTestSources</goal>
<goal>compile</goal>
<goal>compileTests</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven-failsafe-plugin.version}</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>junit5</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<includes>
<include>**/*Test5.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>central</id>
<url>https://jcenter.bintray.com</url>
</repository>
</repositories>
<properties>
<junit.platform.version>1.0.0</junit.platform.version>
<groovy.version>2.5.6</groovy.version>
<groovy-all.version>2.5.6</groovy-all.version>
<groovy-sql.version>2.5.6</groovy-sql.version>
<hsqldb.version>2.4.0</hsqldb.version>
<spock-core.version>1.1-groovy-2.4</spock-core.version>
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
</properties>
</project>
@@ -0,0 +1,70 @@
package com.baeldung.removeprefix
import org.junit.Assert
import org.junit.Test
class RemovePrefixTest {
@Test
public void whenCasePrefixIsRemoved_thenReturnTrue() {
def trimPrefix = {
it.startsWith('Groovy-') ? it.minus('Groovy-') : it
}
def actual = trimPrefix("Groovy-Tutorials at Baeldung")
def expected = "Tutorials at Baeldung"
Assert.assertEquals(expected, actual)
}
@Test
public void whenPrefixIsRemoved_thenReturnTrue() {
String prefix = "groovy-"
String trimPrefix = "Groovy-Tutorials at Baeldung"
def actual;
if(trimPrefix.startsWithIgnoreCase(prefix)) {
actual = trimPrefix.substring(prefix.length())
}
def expected = "Tutorials at Baeldung"
Assert.assertEquals(expected, actual)
}
@Test
public void whenPrefixIsRemovedUsingRegex_thenReturnTrue() {
def regex = ~"^([Gg])roovy-"
String trimPrefix = "Groovy-Tutorials at Baeldung"
String actual = trimPrefix - regex
def expected = "Tutorials at Baeldung"
Assert.assertEquals(expected, actual)
}
@Test
public void whenPrefixIsRemovedUsingReplaceFirst_thenReturnTrue() {
def regex = ~"^groovy"
String trimPrefix = "groovyTutorials at Baeldung's groovy page"
String actual = trimPrefix.replaceFirst(regex, "")
def expected = "Tutorials at Baeldung's groovy page"
Assert.assertEquals(expected, actual)
}
@Test
public void whenPrefixIsRemovedUsingReplaceAll_thenReturnTrue() {
String trimPrefix = "groovyTutorials at Baeldung groovy"
String actual = trimPrefix.replaceAll(/^groovy/, "")
def expected = "Tutorials at Baeldung groovy"
Assert.assertEquals(expected, actual)
}
}
@@ -7,7 +7,7 @@ import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
public class AppUnitTest
extends TestCase
{
/**
@@ -15,7 +15,7 @@ public class AppTest
*
* @param testName name of the test case
*/
public AppTest( String testName )
public AppUnitTest(String testName )
{
super( testName );
}
@@ -25,7 +25,7 @@ public class AppTest
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
return new TestSuite( AppUnitTest.class );
}
/**
@@ -5,7 +5,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
public class StringAPITest {
public class StringAPIUnitTest {
@Test
public void whenPositiveArgument_thenReturnIndentedString() {
@@ -7,7 +7,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class PersonTest {
public class PersonUnitTest {
@Test
public void givenSameNameAndAddress_whenEquals_thenPersonsEqual() {
+11
View File
@@ -44,6 +44,16 @@
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
</dependencies>
<build>
@@ -77,6 +87,7 @@
<maven.compiler.target>1.9</maven.compiler.target>
<guava.version>25.1-jre</guava.version>
<commons-collections4.version>4.1</commons-collections4.version>
<commons-collections3.version>3.2.2</commons-collections3.version>
</properties>
</project>
@@ -17,7 +17,7 @@ import org.junit.Test;
/**
* Test case for the {@link MethodHandles} API
*/
public class MethodHandlesTest {
public class MethodHandlesUnitTest {
@Test
public void givenConcatMethodHandle_whenInvoked_thenCorrectlyConcatenated() throws Throwable {
@@ -6,3 +6,4 @@ This module contains complete guides about arrays in Java
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
- [Guide to the java.util.Arrays Class](https://www.baeldung.com/java-util-arrays)
- [What is \[Ljava.lang.Object;?](https://www.baeldung.com/java-tostring-array)
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
@@ -0,0 +1,86 @@
package com.baeldung.collections.removeallperformance;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.RandomStringUtils;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import com.baeldung.collections.containsperformance.Employee;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5)
public class HashSetBenchmark {
@State(Scope.Thread)
public static class MyState {
private Set<Employee> employeeSet1 = new HashSet<>();
private List<Employee> employeeList1 = new ArrayList<>();
private Set<Employee> employeeSet2 = new HashSet<>();
private List<Employee> employeeList2 = new ArrayList<>();
private long set1Size = 60000;
private long list1Size = 50000;
private long set2Size = 50000;
private long list2Size = 60000;
@Setup(Level.Trial)
public void setUp() {
for (long i = 0; i < set1Size; i++) {
employeeSet1.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < list1Size; i++) {
employeeList1.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < set2Size; i++) {
employeeSet2.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
for (long i = 0; i < list2Size; i++) {
employeeList2.add(new Employee(i, RandomStringUtils.random(7, true, false)));
}
}
}
@Benchmark
public boolean given_SizeOfHashsetGreaterThanSizeOfCollection_When_RemoveAllFromHashSet_Then_GoodPerformance(MyState state) {
return state.employeeSet1.removeAll(state.employeeList1);
}
@Benchmark
public boolean given_SizeOfHashsetSmallerThanSizeOfCollection_When_RemoveAllFromHashSet_Then_BadPerformance(MyState state) {
return state.employeeSet2.removeAll(state.employeeList2);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder().include(HashSetBenchmark.class.getSimpleName())
.threads(1)
.forks(1)
.shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server")
.build();
new Runner(options).run();
}
}
@@ -0,0 +1,33 @@
package com.baeldung.collections.hashset;
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
class HashSetUnitTest {
@Test
void whenRemoveAllFromHashset_thenRemovesAllElementsFromHashsetThatArePresentInCollection() {
Set<Integer> set = new HashSet<>();
Collection<Integer> collection = new ArrayList<>();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
collection.add(1);
collection.add(3);
set.removeAll(collection);
assertEquals(2, set.size());
Integer[] actualElements = new Integer[set.size()];
Integer[] expectedElements = new Integer[] { 2, 4 };
assertArrayEquals(expectedElements, set.toArray(actualElements));
}
}
@@ -15,21 +15,24 @@ import org.junit.Test;
public class MapFirstPairUnitTest {
private Map.Entry<Integer, String> getFirstPairUsingIterator(Map<Integer, String> map) {
if (map == null || map.size() == 0)
if (map == null || map.size() == 0) {
return null;
}
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet()
.iterator();
if (iterator.hasNext())
if (iterator.hasNext()) {
return iterator.next();
}
return null;
}
private Map.Entry<Integer, String> getFirstPairUsingStream(Map<Integer, String> map) {
if (map == null || map.size() == 0)
if (map == null || map.size() == 0) {
return null;
}
Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
@@ -1,6 +1,8 @@
package com.baeldung.date;
import static org.junit.Assert.assertEquals;
import org.joda.time.Days;
import org.joda.time.Minutes;
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@@ -16,7 +18,7 @@ import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import static org.junit.Assert.*;
public class DateDiffUnitTest {
@@ -29,18 +31,39 @@ public class DateDiffUnitTest {
long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime());
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
assertEquals(diff, 6);
assertEquals(6, diff);
}
@Test
public void givenTwoDatesInJava8_whenDifferentiating_thenWeGetSix() {
LocalDate now = LocalDate.now();
LocalDate sixDaysBehind = now.minusDays(6);
public void givenTwoDatesInJava8_whenUsingPeriodGetDays_thenWorks() {
LocalDate aDate = LocalDate.of(2020, 9, 11);
LocalDate sixDaysBehind = aDate.minusDays(6);
Period period = Period.between(now, sixDaysBehind);
Period period = Period.between(aDate, sixDaysBehind);
int diff = Math.abs(period.getDays());
assertEquals(diff, 6);
assertEquals(6, diff);
}
@Test
public void givenTwoDatesInJava8_whenUsingPeriodGetDays_thenDoesNotWork() {
LocalDate aDate = LocalDate.of(2020, 9, 11);
LocalDate sixtyDaysBehind = aDate.minusDays(60);
Period period = Period.between(aDate, sixtyDaysBehind);
int diff = Math.abs(period.getDays());
//not equals
assertNotEquals(60, diff);
}
@Test
public void givenTwoDatesInJava8_whenUsingPeriod_thenWeGet0Year1Month29Days() {
LocalDate aDate = LocalDate.of(2020, 9, 11);
LocalDate sixtyDaysBehind = aDate.minusDays(60);
Period period = Period.between(aDate, sixtyDaysBehind);
int years = Math.abs(period.getYears());
int months = Math.abs(period.getMonths());
int days = Math.abs(period.getDays());
assertArrayEquals(new int[] { 0, 1, 29 }, new int[] { years, months, days });
}
@Test
@@ -51,7 +74,7 @@ public class DateDiffUnitTest {
Duration duration = Duration.between(now, sixMinutesBehind);
long diff = Math.abs(duration.toMinutes());
assertEquals(diff, 6);
assertEquals(6, diff);
}
@Test
@@ -61,7 +84,7 @@ public class DateDiffUnitTest {
long diff = ChronoUnit.SECONDS.between(now, tenSecondsLater);
assertEquals(diff, 10);
assertEquals(10, diff);
}
@Test
@@ -69,9 +92,9 @@ public class DateDiffUnitTest {
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal"));
ZonedDateTime sixDaysBehind = now.withZoneSameInstant(ZoneId.of("Asia/Singapore"))
.minusDays(6);
.minusDays(6);
long diff = ChronoUnit.DAYS.between(sixDaysBehind, now);
assertEquals(diff, 6);
assertEquals(6, diff);
}
@Test
@@ -81,7 +104,7 @@ public class DateDiffUnitTest {
long diff = now.until(tenSecondsLater, ChronoUnit.SECONDS);
assertEquals(diff, 10);
assertEquals(10, diff);
}
@Test
@@ -89,10 +112,9 @@ public class DateDiffUnitTest {
org.joda.time.LocalDate now = org.joda.time.LocalDate.now();
org.joda.time.LocalDate sixDaysBehind = now.minusDays(6);
org.joda.time.Period period = new org.joda.time.Period(now, sixDaysBehind);
long diff = Math.abs(period.getDays());
long diff = Math.abs(Days.daysBetween(now, sixDaysBehind).getDays());
assertEquals(diff, 6);
assertEquals(6, diff);
}
@Test
@@ -100,8 +122,9 @@ public class DateDiffUnitTest {
org.joda.time.LocalDateTime now = org.joda.time.LocalDateTime.now();
org.joda.time.LocalDateTime sixMinutesBehind = now.minusMinutes(6);
org.joda.time.Period period = new org.joda.time.Period(now, sixMinutesBehind);
long diff = Math.abs(period.getDays());
long diff = Math.abs(Minutes.minutesBetween(now, sixMinutesBehind).getMinutes());
assertEquals(6, diff);
}
@Test
@@ -111,6 +134,6 @@ public class DateDiffUnitTest {
long diff = Math.abs(now.numDaysFrom(sixDaysBehind));
assertEquals(diff, 6);
assertEquals(6, diff);
}
}
}
@@ -6,7 +6,7 @@ import org.junit.jupiter.api.Test;
import java.sql.Timestamp;
import java.time.format.DateTimeFormatter;
public class TimestampToStringConverterTest {
public class TimestampToStringConverterUnitTest {
@Test
public void givenDatePattern_whenFormatting_thenResultingStringIsCorrect() {
@@ -1,3 +1,5 @@
### Relevant Articles:
- [NoSuchMethodError in Java](https://www.baeldung.com/java-nosuchmethod-error)
- [IllegalArgumentException or NullPointerException for a Null Parameter?](https://www.baeldung.com/java-illegalargumentexception-or-nullpointerexception)
- [IllegalMonitorStateException in Java](https://www.baeldung.com/java-illegalmonitorstateexception)
@@ -9,4 +9,6 @@ This module contains articles about core Java input and output (IO)
- [Check If a File or Directory Exists in Java](https://www.baeldung.com/java-file-directory-exists)
- [Copy a Directory in Java](https://www.baeldung.com/java-copy-directory)
- [Java Files Open Options](https://www.baeldung.com/java-file-options)
- [Creating Temporary Directories in Java](https://www.baeldung.com/java-temp-directories)
- [Reading a Line at a Given Line Number From a File in Java](https://www.baeldung.com/java-read-line-at-number)
- [[<-- Prev]](/core-java-modules/core-java-io-2)
@@ -4,6 +4,7 @@ import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -20,8 +21,8 @@ public class DirectoryEmptinessUnitTest {
}
@Test
public void givenPath_whenNotDirectory_thenReturnsFalse() throws IOException {
Path aFile = Paths.get(getClass().getResource("/notDir.txt").getPath());
public void givenPath_whenNotDirectory_thenReturnsFalse() throws IOException, URISyntaxException {
Path aFile = Paths.get(getClass().getResource("/notDir.txt").toURI());
assertThat(isEmpty(aFile)).isFalse();
}
@@ -4,10 +4,7 @@ import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.*;
import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertFalse;
@@ -47,8 +44,18 @@ public class ExistenceUnitTest {
public void givenSymbolicLink_whenTargetDoesNotExists_thenFollowOrNotBasedOnTheOptions() throws IOException {
Path target = Files.createTempFile("baeldung", "target");
Path symbol = Paths.get("test-link-" + ThreadLocalRandom.current().nextInt());
Path symbolicLink = null;
try {
symbolicLink = Files.createSymbolicLink(symbol, target);
} catch (FileSystemException ex) {
System.out.println("Your OS security policy prevents the current user from creating symbolic links.\n" +
"Most probably you're running Windows with UAC.\n" +
"If this is the case, please see - https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/create-symbolic-links\n" +
"You must change your security settings to run this test under Windows.");
return;
}
Path symbolicLink = Files.createSymbolicLink(symbol, target);
assertTrue(Files.exists(symbolicLink));
assertTrue(Files.isSymbolicLink(symbolicLink));
assertFalse(Files.isSymbolicLink(target));
@@ -4,6 +4,7 @@ import org.apache.commons.io.FileUtils;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -66,10 +67,16 @@ public class TemporaryDirectoriesUnitTest {
@Test
public void givenTempDirWithPrefixWithFileAttrs_whenCreatePlainJava_thenAttributesAreSet() throws IOException {
final FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("r--------"));
boolean isPosix = FileSystems.getDefault().supportedFileAttributeViews().contains("posix");
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix", attrs);
assertThat(tmpdir.toFile().getPath()).startsWith("target");
assertThat(tmpdir.toFile().canWrite()).isFalse();
if(!isPosix){
System.out.println("You must be under a Posix Compliant Filesystem to run this test.");
} else {
final FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("r--------"));
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix", attrs);
assertThat(tmpdir.toFile().getPath()).startsWith("target");
assertThat(tmpdir.toFile().canWrite()).isFalse();
}
}
}
@@ -17,7 +17,7 @@
<dependencies>
<dependency>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule</artifactId>
<artifactId>servicemodule1</artifactId>
<version>${servicemodule.version}</version>
</dependency>
</dependencies>
@@ -4,7 +4,8 @@
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>
<artifactId>servicemodule</artifactId>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule1</artifactId>
<packaging>jar</packaging>
<parent>
@@ -17,7 +17,7 @@
<dependencies>
<dependency>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule</artifactId>
<artifactId>servicemodule2</artifactId>
<version>${servicemodule.version}</version>
</dependency>
</dependencies>
@@ -4,7 +4,8 @@
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>
<artifactId>servicemodule</artifactId>
<groupId>com.baeldung.servicemodule</groupId>
<artifactId>servicemodule2</artifactId>
<version>1.0</version>
<parent>
@@ -5,4 +5,5 @@ This module contains articles about core features in the Java language
- [Class.isInstance vs Class.isAssignableFrom](https://www.baeldung.com/java-isinstance-isassignablefrom)
- [Converting a Java String Into a Boolean](https://www.baeldung.com/java-string-to-boolean)
- [When are Static Variables Initialized in Java?](https://www.baeldung.com/java-static-variables-initialization)
- [Checking if a Class Exists in Java](https://www.baeldung.com/java-check-class-exists)
- [[<-- Prev]](/core-java-modules/core-java-lang-2)
@@ -13,4 +13,5 @@
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
- [Debugging with Eclipse](https://www.baeldung.com/eclipse-debugging)
- [Matrix Multiplication in Java](https://www.baeldung.com/java-matrix-multiplication)
- [Largest Power of 2 That Is Less Than the Given Number](https://www.baeldung.com/java-largest-power-of-2-less-than-number)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math)
@@ -9,3 +9,4 @@ This module contains articles about methods in Java
- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)
- [Guide to hashCode() in Java](https://www.baeldung.com/java-hashcode)
- [The Covariant Return Type in Java](https://www.baeldung.com/java-covariant-return-type)
- [Does a Method’s Signature Include the Return Type in Java?](https://www.baeldung.com/java-method-signature-return-type)
@@ -0,0 +1,72 @@
package com.baeldung.signature;
import java.io.Serializable;
public class OverloadingErrors<T extends Serializable> {
public void print() {
System.out.println("Signature is: print()");
}
/*
// Uncommenting this method will lead to a compilation error: java: method print() is already defined in class
// The method signature is independent from return type
public int print() {
System.out.println("Signature is: print()");
return 0;
}
*/
/*
// Uncommenting this method will lead to a compilation error: java: method print() is already defined in class
// The method signature is independent from modifiers
private final void print() {
System.out.println("Signature is: print()");
}
*/
/*
// Uncommenting this method will lead to a compilation error: java: method print() is already defined in class
// The method signature is independent from thrown exception declaration
public void print() throws IllegalStateException {
System.out.println("Signature is: print()");
throw new IllegalStateException();
}
*/
public void print(int parameter) {
System.out.println("Signature is: print(int)");
}
/*
// Uncommenting this method will lead to a compilation error: java: method print(int) is already defined in class
// The method signature is independent from parameter names
public void print(int anotherParameter) {
System.out.println("Signature is: print(int)");
}
*/
public void printElement(T t) {
System.out.println("Signature is: printElement(T)");
}
/*
// Uncommenting this method will lead to a compilation error: java: name clash: printElement(java.io.Serializable) and printElement(T) have the same erasure
// Even though the signatures appear different, the compiler cannot statically bind the correct method after type erasure
public void printElement(Serializable o) {
System.out.println("Signature is: printElement(Serializable)");
}
*/
public void print(Object... parameter) {
System.out.println("Signature is: print(Object...)");
}
/*
// Uncommenting this method will lead to a compilation error: java cannot declare both sum(Object...) and sum(Object[])
// Even though the signatures appear different, after compilation they both resolve to sum(Object[])
public void print(Object[] parameter) {
System.out.println("Signature is: print(Object[])");
}
*/
}
@@ -0,0 +1,46 @@
package com.baeldung.signature;
public class StaticBinding {
public Number sum(Integer term1, Integer term2) {
System.out.println("Adding integers");
return term1 + term2;
}
public Number sum(Number term1, Number term2) {
System.out.println("Adding numbers");
return term1.doubleValue() + term2.doubleValue();
}
public Number sum(Object term1, Object term2) {
System.out.println("Adding objects");
return term1.hashCode() + term2.hashCode();
}
public Number sum(Object term1, Object... term2) {
System.out.println("Adding variable arguments: " + term2.length);
int result = term1.hashCode();
for (Object o : term2) {
result += o.hashCode();
}
return result;
}
public static void main(String[] args) {
StaticBinding obj = new StaticBinding();
obj.sum(2, 3); // "Adding integers" due to auto-boxing from int to Integer
obj.sum(Integer.valueOf(2), Integer.valueOf(3)); // "Adding integers" due to exact parameter types
obj.sum(2, 0x1); // "Adding integers" due to type promotion from byte to int
obj.sum((Number) 2, (Number) 3); // "Adding numbers" due to explicit cast to Number
obj.sum(2.0d, 3.0d); // "Adding numbers" due to auto-boxing from double to Double
obj.sum(Float.valueOf(2), Float.valueOf(3)); // "Adding numbers" due to polimorphism
obj.sum((Object) 2, (Object) 3); // "Adding objects" due to explicit cast to Object
obj.sum(2, "John"); // "Adding objects" due to polimorphism
obj.sum(new Object(), new Object(), new Object()); // "Adding variable arguments 2"
obj.sum(new Object(), new Object[]{new Object()}); // "Adding variable arguments 1"
}
}
@@ -13,4 +13,5 @@ This module contains articles about networking in Java
- [Download a File from an URL in Java](https://www.baeldung.com/java-download-file)
- [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception)
- [Getting MAC addresses in Java](https://www.baeldung.com/java-mac-address)
- [Sending Emails with Attachments in Java](https://www.baeldung.com/java-send-emails-attachments)
- [[<-- Prev]](/core-java-modules/core-java-networking)

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