<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>Java Archives - Program Easily</title>
	<atom:link href="https://programeasily.com/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>https://programeasily.com/tag/java/</link>
	<description>Program Easily helps people to learn about software programs in a easy manner.</description>
	<lastBuildDate>Fri, 18 Nov 2022 16:28:40 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.1</generator>

<image>
	<url>https://i0.wp.com/programeasily.com/wp-content/uploads/2020/12/cropped-logo.png?fit=32%2C32&#038;ssl=1</url>
	<title>Java Archives - Program Easily</title>
	<link>https://programeasily.com/tag/java/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">187075990</site>	<item>
		<title>AWS S3 Client &#8211; Local Stack &#8211; Test Container</title>
		<link>https://programeasily.com/2022/11/18/aws-s3-client-local-stack-test-container/</link>
					<comments>https://programeasily.com/2022/11/18/aws-s3-client-local-stack-test-container/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Fri, 18 Nov 2022 16:27:13 +0000</pubDate>
				<category><![CDATA[J-unit]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[aws]]></category>
		<category><![CDATA[docker]]></category>
		<category><![CDATA[localstack]]></category>
		<category><![CDATA[test container]]></category>
		<guid isPermaLink="false">https://programeasily.com/?p=1676</guid>

					<description><![CDATA[<p>Test Container Test container is a third party Java library which offers to test or validate anything that can run in a Docker container. For Example, we can create lightweight database instances of  MySQL, PostgreSQL or Oracle database to test our data access layer code (DAO , Repositories). Similarly we can test our AWS cloud services like server less apps without actually using the cloud. We can do this with the help of LocalStack, a fully functional local AWS cloud...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2022/11/18/aws-s3-client-local-stack-test-container/"> Read More<span class="screen-reader-text">  Read More</span></a></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2022/11/18/aws-s3-client-local-stack-test-container/">AWS S3 Client &#8211; Local Stack &#8211; Test Container</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h2>Test Container</h2>
<p>Test container is a third party Java library which offers to test or validate anything that can run in a Docker container. For Example, we can create lightweight database instances of  MySQL, PostgreSQL or Oracle database to test our data access layer code (DAO , Repositories). <strong>Similarly we can test our AWS cloud services like server less apps without actually using the cloud.</strong> We can do this with the help of <a href="http://localstack.cloud/">LocalStack,</a> a fully functional local AWS cloud stack.</p>
<h2>Local Stack</h2>
<p><a href="https://localstack.cloud/">LocalStack</a> is a cloud service emulator. We can able to run AWS applications like Lambda, S3 entirely on your laptop or machine without connecting to a remote cloud provider.</p>
<p><img fetchpriority="high" decoding="async" class="aligncenter size-full wp-image-1954" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2022/11/Snapshot_38.png?resize=640%2C360&#038;ssl=1" alt="AWS S3 Client with Local Stack and Test Container" width="640" height="360" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2022/11/Snapshot_38.png?w=1920&amp;ssl=1 1920w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/11/Snapshot_38.png?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/11/Snapshot_38.png?resize=1024%2C576&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/11/Snapshot_38.png?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/11/Snapshot_38.png?resize=1536%2C864&amp;ssl=1 1536w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/11/Snapshot_38.png?resize=480%2C270&amp;ssl=1 480w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/11/Snapshot_38.png?w=1280&amp;ssl=1 1280w" sizes="(max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<h2>Why It is needed ?</h2>
<p>We can able to connect to AWS services like S3 from Java using their SDK&#8217;s. But here the problem is, if we wants to validate our code then we are need to connect cloud sandboxes using AWS SAM or anything like that. And While we access the cloud services, It is billable as well. Secondly we can not write unit test or integration test for this sources in a efficient way which would be a another downside of it. So In this article, we are going to learn to write unit testing for AWS S3 services with the help of Local stack and Test containers. Let&#8217;s dive into that. Cheers.</p>
<h2>Prerequisite</h2>
<ul>
<li>Java</li>
<li>Maven</li>
<li>Docker</li>
</ul>
<h2>Create a Spring initializer project</h2>
<p>First, I am creating basic spring initializer project with Spring boot starter, Spring boot test and <strong>AWS SDK maven dependencies</strong>.</p>
<pre><code class="language-java">&lt;dependency&gt;
            &lt;groupId&gt;com.amazonaws&lt;/groupId&gt;
            &lt;artifactId&gt;aws-java-sdk&lt;/artifactId&gt;
            &lt;version&gt;1.11.163&lt;/version&gt;
&lt;/dependency&gt;</code></pre>
<h2>Creating AWS S3 Client</h2>
<p>Second, now I am creating AWS S3 client with simple upload object functionality. Here I am validating whether the bucket is exist or not, followed by uploading an object into the S3 storage system.</p>
<pre><code class="language-java">package awsservicestutorial.client;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;

public class AwsS3Client {

    private final AmazonS3 amazonS3;

    public AwsS3Client(final AmazonS3 amazonS3) {
        this.amazonS3 = amazonS3;
    }

    public void uploadObject(final String bucketName, final Path path) throws IOException {

        isBucketExists(bucketName);

        final String filename = path.getFileName().toString();

        final ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(URLConnection.guessContentTypeFromName(filename));
        metadata.setSSEAlgorithm("AES256");
        metadata.setContentLength(Files.size(path));

        try(final InputStream stream = Files.newInputStream(path)){
            amazonS3.putObject(bucketName, filename, stream, metadata);
        }
    }

    private void isBucketExists(final String bucketName) {
        if(!amazonS3.doesBucketExist(bucketName)) {
            throw new IllegalStateException(String.format("Bucket %s does not exist", bucketName));
        }
    }

}</code></pre>
<h2>Local Stack and Test Container Dependencies</h2>
<p>Add the following dependency to your <code>pom.xml</code> for using local stack and test container libraries.</p>
<pre><code class="language-apacheconf">        &lt;dependency&gt;
            &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;
            &lt;artifactId&gt;localstack&lt;/artifactId&gt;
            &lt;version&gt;1.17.6&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.testcontainers&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter&lt;/artifactId&gt;
            &lt;version&gt;1.17.6&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;</code></pre>
<p>Here I am using Junit-5 for unit testing the application. It is up to to decide whether Junit 5 or 4. We can do this with Junit 4 as well.</p>
<h2>AWS S3 Client &#8211; Local Stack &#8211; Test Container &#8211; Create Unit Test</h2>
<p>Creating unit test with local stack is really very simple. we just need to create local stack instance. This instance can act as AWS S3 services with the help of test container and docker. It will create a exact AWS mock in local or in our CI environment. This will reduce a lot money, since we don&#8217;t need to interact AWS cloud services during local development and testing.</p>
<pre><code class="language-java">package awsservicestutorial;

import awsservicestutorial.client.AwsS3Client;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.testcontainers.containers.localstack.LocalStackContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;

@Testcontainers(disabledWithoutDocker = true)
@ExtendWith(SpringExtension.class)
class AwsServicesTutorialApplicationTests {
    private static final String BUCKET_NAME = "test-bucket";
    @Container
    public final static LocalStackContainer LOCAL_STACK_CONTAINER =
            new LocalStackContainer(DockerImageName.parse("localstack/localstack:0.12.16"))
                    .withServices(LocalStackContainer.Service.S3).withEnv("DEFAULT_REGION", "us-east-1");
    private AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard()
            .withEndpointConfiguration(LOCAL_STACK_CONTAINER.getEndpointConfiguration(LocalStackContainer.Service.S3))
            .withCredentials(LOCAL_STACK_CONTAINER.getDefaultCredentialsProvider()).build();

    private AwsS3Client awsS3Client;

    @BeforeEach
    public void beforeEach() throws IOException, InterruptedException {
        LOCAL_STACK_CONTAINER.execInContainer("awslocal", "s3", "mb", "s3://" + BUCKET_NAME);
        awsS3Client = new AwsS3Client(amazonS3);
    }

    @AfterEach
    public void afterEach() throws IOException, InterruptedException {
        LOCAL_STACK_CONTAINER.execInContainer("awslocal", "s3", "rb", "s3://" + BUCKET_NAME, "--force");
    }

    /**
     * First assert whether localstack is running!
     */
    @Test
    public void test_isLocalstackRunning() {
        Assertions.assertTrue(LOCAL_STACK_CONTAINER.isRunning());
    }

    @Test
    public void test_uploadObjectSuccess() throws URISyntaxException, IOException {

        awsS3Client.uploadObject(BUCKET_NAME, createPath());
        Assertions.assertTrue(amazonS3.doesObjectExist(BUCKET_NAME, "sample.csv"));
    }

    @Test
    public void tes_uploadObjectError() throws IOException, InterruptedException {

        LOCAL_STACK_CONTAINER.execInContainer("awslocal", "s3", "rb", "s3://" + BUCKET_NAME, "--force");
        Assertions.assertThrows(IllegalStateException.class, () -&gt; awsS3Client.uploadObject(BUCKET_NAME, createPath()));
    }

    private Path createPath() throws URISyntaxException {
        return Optional.ofNullable(ClassLoader.getSystemResource("sample.csv").toURI())
                .map(Paths::get)
                .orElseThrow(IllegalArgumentException::new);
    }

}
</code></pre>
<ul>
<li>First, I am validating whether the local or CI machine having docker environment.</li>
<li>Second, <strong>@Container creates the local stack container instance and mimic the AWS S3 as we are providing S3 as a service here. </strong>If you are using Junit-4, then you must use @ClassRule annotation here.</li>
<li>During <code>beforeEach()</code> method, we are just creating the bucket in the S3 where as <code>afterEach()</code> method deletes the bucket after each test execution.</li>
<li>You will need to create sample.csv file under test/resources directory for uploading into local stack S3.</li>
<li>During upload test, once the file upload has been done, we can assert that using <code>amazonS3.doesObjectExist</code> method, whether the file has been successfully uploaded or not.</li>
<li>And also we are validating after deleting the the bucket, whether it is throwing <code>IllegalStateException</code> exception or not.</li>
<li><strong>Finally In this way, we tested our AWS S3 client class effectively without connecting into AWS services.</strong></li>
</ul>
<h2>AWS S3 Client &#8211; Local Stack &#8211; Test Container &#8211; Code Sample</h2>
<ul>
<li><a href="https://github.com/programeasily/aws-services-tutorial/blob/main/src/main/java/awsservicestutorial/client/AwsS3Client.java">https://github.com/programeasily/aws-services-tutorial/blob/main/src/main/java/awsservicestutorial/client/AwsS3Client.java</a></li>
<li><a href="https://github.com/programeasily/aws-services-tutorial/blob/main/src/test/java/awsservicestutorial/AwsServicesTutorialApplicationTests.java">https://github.com/programeasily/aws-services-tutorial/blob/main/src/test/java/awsservicestutorial/AwsServicesTutorialApplicationTests.java</a></li>
<li><a href="https://github.com/programeasily/aws-services-tutorial">https://github.com/programeasily/aws-services-tutorial</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://programeasily.com/2022/11/18/aws-s3-client-local-stack-test-container/">AWS S3 Client &#8211; Local Stack &#8211; Test Container</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programeasily.com/2022/11/18/aws-s3-client-local-stack-test-container/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1676</post-id>	</item>
		<item>
		<title>String in Java &#8211; String Literal, String Pool, String Objects</title>
		<link>https://programeasily.com/2022/09/01/string-in-java/</link>
					<comments>https://programeasily.com/2022/09/01/string-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Thu, 01 Sep 2022 04:49:00 +0000</pubDate>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[core java]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://programeasily.com/?p=1672</guid>

					<description><![CDATA[<p>         String is a special non primitive data type in java if we compare with any others. But why! In String, we are having string pool as well as heap memory to store the values. The strings are immutable by nature. String is an object which contains sequence of character&#8217;s. String is not belong to primitive data type whereas we can create object using java.lang.String. There are two ways to create the string in Java.    ...</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2022/09/01/string-in-java/"> Read More<span class="screen-reader-text">  Read More</span></a></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2022/09/01/string-in-java/">String in Java &#8211; String Literal, String Pool, String Objects</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>         String is a special non primitive data type in java if we compare with any others. But why! In String, we are having string pool as well as heap memory to store the values. The strings are immutable by nature. String is an object which contains sequence of character&#8217;s. String is not belong to primitive data type whereas we can create object using <em>java.lang.String</em>. There are two ways to create the string in Java.</p>
<p>             1. By Literal in Java</p>
<p>             2. By New Keyword</p>
<h2>String Literal in Java</h2>
<p>String Literals are very special in Java. We can create String object using double quotes as followed,</p>
<pre><code class="language-java">String message = "Hello ! I am a string";</code></pre>
<p>The above code calls the intern() method of string first. Then the intern checks whether the same object is exists in pool or not!. If it is exist, it will return the same object reference. Otherwise It will create the new object in the pool and return the new object reference. Ultimately the string literal should be fast if we compare with new keyword since it will not create the new objects every time.</p>
<p><img decoding="async" class="wp-image-1704 size-large aligncenter" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2022/09/untitled_page.png?resize=640%2C277&#038;ssl=1" alt="String Literal" width="640" height="277" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2022/09/untitled_page.png?resize=1024%2C443&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/09/untitled_page.png?resize=300%2C130&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/09/untitled_page.png?resize=768%2C333&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/09/untitled_page.png?resize=1536%2C665&amp;ssl=1 1536w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/09/untitled_page.png?w=1725&amp;ssl=1 1725w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/09/untitled_page.png?w=1280&amp;ssl=1 1280w" sizes="(max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<h2>By New Keyword</h2>
<p>We can create String object using new keyword as followed,</p>
<pre><code class="language-java">String message = new String("Hello ! I am a string");</code></pre>
<p>The above code creates two string objects. It will create one object in Heap Memory directly and other in String Pool Area. And the reference will points to heap memory object.</p>
<p><img decoding="async" class="aligncenter wp-image-1717 size-full" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2022/09/heap-1.png?resize=640%2C360&#038;ssl=1" alt="new of string in java" width="640" height="360" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2022/09/heap-1.png?w=1064&amp;ssl=1 1064w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/09/heap-1.png?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/09/heap-1.png?resize=1024%2C576&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2022/09/heap-1.png?resize=768%2C432&amp;ssl=1 768w" sizes="(max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></p>
<h3>Caution in String Compare</h3>
<p>We have to use equals method of string to compare two strings always, not ==. Because == compares only the memory locations. But the equals method compare the memory location as well as the content of the stored objects.</p>
<pre><code class="language-java">String a = "Hello";
String b = "Hello";

// since literals re-use existing objects from the pool
System.out.println(a == b) // true

String c = new String("Hello");

// new keyword always creates new objects in the heap
// And == compares the memory locations not the exact
// content of the objects
System.out.println(a == c) // false

// Always use equals for comparison
// String class equals method checks the content of the 
// object as well
System.out.println(a.equals(c)) // true</code></pre>
<h2>Why String is Immutable</h2>
<p>The rule to create any <a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html">immutable object</a> is, it&#8217;s state can not be changed after it is created. And String class designed to follow this rule. Even we could create N number of objects by following this rule. Let&#8217;s come to the point, why string is immutable ? The most correct answer is probably: Because the java language authors or designers figured it was a good idea. So that It will provide lot of benefits to us, Let&#8217;s see one by one.</p>
<h3>Security</h3>
<p>We have been mostly using string object in network connections, database connection URLs, usernames/passwords and etc. It it were mutable, we can change these parameters and runtime And which creates security issues.</p>
<h4>Synchronization And Concurrency</h4>
<p>We can say an object is thread safe, when multiple threads are operating on it but none of them is able to corrupt its state and object hold the same state for every thread at any point in time. Making String immutable automatically makes them thread safe by default thereby solving the synchronization issues.</p>
<h4>Caching</h4>
<p>when compiler optimizes your String objects, it sees that if two objects have same value (a=&#8221;test&#8221;, and b=&#8221;test&#8221;) and thus you need only one string object (for both a and b, these two will point to the same object)</p>
<h4>Hash Code Caching</h4>
<p>String object caches its hash code at the time of object creation which makes it the great candidate for hashing related operations because hash code doesn&#8217;t need to be calculated again which save us some time. This is why String is mostly used as <code>Hash Map</code> keys</p>
<h4>Class Loading</h4>
<p>We have been using String as an arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).</p>
<h2>Summary</h2>
<ol>
<li>
<p>Usually we design classes as immutable for them being thread safe and to optimize performance and memory consumption.</p>
</li>
<li>
<p>Security and Efficiency to be the primary design goals, then immutable strings are a means to meet those goals.</p>
</li>
<li>
<p>immutable objects in java are like copy-by-value, you can have 2 references to a String, but you should consider them 2 separate Strings since it&#8217;s immutable, and working with one of them won&#8217;t affect the other.</p>
</li>
</ol>
<h3>You May Also Like</h3>
<ul>
<li><a href="https://programeasily.com/2022/01/04/java-8-interview-questions-for-experienced/">Java 8 Interview Questions for Experienced</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://programeasily.com/2022/09/01/string-in-java/">String in Java &#8211; String Literal, String Pool, String Objects</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programeasily.com/2022/09/01/string-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1672</post-id>	</item>
		<item>
		<title>Java 8 Interview Questions for Experienced</title>
		<link>https://programeasily.com/2022/01/04/java-8-interview-questions-for-experienced/</link>
					<comments>https://programeasily.com/2022/01/04/java-8-interview-questions-for-experienced/#respond</comments>
		
		<dc:creator><![CDATA[Admin]]></dc:creator>
		<pubDate>Tue, 04 Jan 2022 09:36:49 +0000</pubDate>
				<category><![CDATA[Interview Questions]]></category>
		<category><![CDATA[Java Interview Questions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java-8]]></category>
		<guid isPermaLink="false">https://programeasily.com/?p=540</guid>

					<description><![CDATA[<p>As same as in the previous versions, Java released two products in it&#8217;s 8th version. One is JRE-8 (Runtime environment) and the other one is JDK-8 (Development kit). JRE provides the base libraries (lang and util, input/output etc.), integration libraries (JDBC, RMI etc.), user interface toolkits (Java FX, Swing etc.) and deployments (Java web start). On the other hand, JDK has everything from JRE, in addition to tools like compiler, debuggers and API which are necessary for developing the applications....</p>
<p class="read-more"><a class="btn btn-default" href="https://programeasily.com/2022/01/04/java-8-interview-questions-for-experienced/"> Read More<span class="screen-reader-text">  Read More</span></a></p>
<p>The post <a rel="nofollow" href="https://programeasily.com/2022/01/04/java-8-interview-questions-for-experienced/">Java 8 Interview Questions for Experienced</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><span style="font-weight: 400;">As same as in the previous versions, Java released two products in it&#8217;s 8th version. One is JRE-8 (Runtime environment) and the other one is JDK-8 (Development kit). JRE provides the base libraries (lang and util, input/output etc.), integration libraries (JDBC, RMI etc.), user interface toolkits (Java FX, Swing etc.) and deployments (Java web start). On the other hand, JDK has everything from JRE, in addition to tools like compiler, debuggers and API which are necessary for developing the applications.</span></p>
<p><a href="https://docs.oracle.com/javase/8/docs/"><span style="font-weight: 400;">Java edition 8</span></a><span style="font-weight: 400;"> is a major release after the 6th edition. In this article we are going to refresh the concepts which will help us to improve the interview experience. Let&#8217;s take a deep dive into it.</span></p>
<h2>Java 8 Interview Questions for Experienced</h2>
<h2><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-726" src="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/12/java-8-interview-questions.png?resize=640%2C360&#038;ssl=1" alt="Java 8 Interview Questions" width="640" height="360" srcset="https://i0.wp.com/programeasily.com/wp-content/uploads/2021/12/java-8-interview-questions.png?w=1366&amp;ssl=1 1366w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/12/java-8-interview-questions.png?resize=300%2C169&amp;ssl=1 300w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/12/java-8-interview-questions.png?resize=1024%2C576&amp;ssl=1 1024w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/12/java-8-interview-questions.png?resize=768%2C432&amp;ssl=1 768w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/12/java-8-interview-questions.png?resize=480%2C270&amp;ssl=1 480w, https://i0.wp.com/programeasily.com/wp-content/uploads/2021/12/java-8-interview-questions.png?w=1280&amp;ssl=1 1280w" sizes="auto, (max-width: 640px) 100vw, 640px" data-recalc-dims="1" /></h2>
<h3>1. Features of Java 8</h3>
<ul>
<li>Lambda Expressions &#8211; Lambda expressions are anonymous functions or methods without the name</li>
<li>Functional Interface &#8211; It is a single abstract method (SAM) interface, i.e. interface with only one abstract method.</li>
<li>Default Method &#8211; the default implementation of the method and we can override it in the concrete class if required.</li>
<li>Method Reference &#8211; <span style="font-weight: 400;">It will just refer to the existing method with name. An easy way of referring to a method of a functional interface.</span></li>
<li>Stream &#8211; a sequence of elements involved with sequential and parallel aggregate operations. The operations are composed into a stream pipeline.</li>
<li>Optional &#8211; A wrapper object which may or may not contain a non null value.</li>
<li>Static methods in interface &#8211; Static methods makes it easier to organize the helper methods in our libraries. We can create static methods specific to an interface in the same interface rather than in a separate class.</li>
<li>Nashorn &#8211; The Nashorn engine is an implementation of the ECMAScript. Nashorn Java API allows us to write Java Applications as scripts which can be interpreted by the Nashorn engine.</li>
</ul>
<h3>2. What are functional interface</h3>
<p><span style="font-weight: 400;">Java 8 introduced the concept of functional programming with the help of functional interfaces. It is a <strong>single abstract method</strong> (SAM) interface, i.e. interface with only one abstract method. So one abstract method is responsible for one particular functionality. <strong>@FunctionalInterface</strong> annotation is used to indicate that the interface is a functional interface. This annotation is not mandatory. It just let the compilers to throw the error incase if we maintain more than one abstract method in the interface.</span></p>
<p><span style="font-weight: 400;">Note that, we can create the functional interface instances with the help of lambda expressions, method references or constructor references.</span></p>
<h3>3. Some Predefined functional interfaces</h3>
<ul>
<li><strong>Consumer</strong> &#8211; a function that accepts a single input argument and returns no result.</li>
<li><strong>Function</strong> &#8211; a function that accepts one argument and produces a result.</li>
<li><strong>Predicate</strong> &#8211; Represents a predicate (boolean-valued function) of one argument.</li>
<li><strong>Supplier</strong> &#8211; a function that does not accept input and produces a result.</li>
</ul>
<h3>4. What is lambda expression</h3>
<p>Lambda expressions are anonymous functions or methods without the name. We can replace the anonymous class implementation with the help of lambda expressions after Java-8. We can pass functionality as an argument to another method here. Some of the key points are,</p>
<ul>
<li>Function without a name</li>
<li>Anonymous function</li>
<li>Executes on demand</li>
<li>Applied only to functional interface</li>
<li>Standalone, does not belong to any class</li>
</ul>
<p>The Lambda expression syntax consists of the following,</p>
<ol>
<li>A comma separated list of parameters enclosed in parentheses</li>
<li>The Arrow token, -&gt;</li>
<li>A Body, which consists of a single expression or a statement block.</li>
</ol>
<pre><code class="language-java">// single parameter and single expression example,
p -&gt; p.getGender() &gt; 25 &amp;&amp; p.getGender() &lt;= 18

// multiple parameter example,
( a, b ) -&gt; a + b;

// statement block example,
p -&gt;{
     return  p.getGender() &gt; 25 &amp;&amp; p.getGender() &lt;= 18 ;
}
</code></pre>
<h3>5. What is default method</h3>
<p>Before Java 8, interfaces allowed abstract methods only. From Java-8, we can do the abstract method implementation in the interface itself. Let&#8217;s say the default implementation of the method and we can override it in the concrete class if required.</p>
<p>The idea behind the default method is that the java-8 team wants to introduce new abstract methods in the old utility libraries. If they do so, it will provide compiler error to all it&#8217;s implemented classes. So the default method was introduced to ensure backward compatibility. It enables you to add new methods to the old interfaces with the compatibility of it&#8217;s older versions of those interfaces.</p>
<h3>6. What is Method Reference</h3>
<p><span style="font-weight: 400;">Sometimes we want to create the lambda function(anonymous function) that does nothing but call an existing method. Here we are having the super shortcut called method reference. It will just refer to the existing method by name, an easy way of referring to a method of a functional interface.</span></p>
<pre><code class="language-java">// a lambda expression does nothing but call an existing method
Arrays.sort(rosterAsArray,
    (a, b) -&gt; Person.compareByAge(a, b)
);

// Using method reference
// refer to the existing method by name
Arrays.sort(rosterAsArray, Person::compareByAge);</code></pre>
<h3>7. What is Optional</h3>
<p><span style="font-weight: 400;">A wrapper object which may or may not contain a non null value. We can use optional to handle null values after Java-8. If value is not null, isPresent() will return true and get() will return the value.</span></p>
<pre><code class="language-java">// Creates the optional object
Optional.of(argument);</code></pre>
<h3>8. What is Stream</h3>
<p><span style="font-weight: 400;">A Stream is not a data structure that stores elements. It does not hold any data(No Storage). Whereas, is a sequence of elements involved with sequential and parallel aggregate operations. The operations are composed into a stream pipeline. The Stream pipeline consist of below components,</span></p>
<ul>
<li>A source (array, collection, generator function, an I/O channel)</li>
<li>Zero or more intermediate operations (each intermediate operation transform a stream into another stream)</li>
<li>A terminal operation (produces a result or side-effect)</li>
</ul>
<p><span style="font-weight: 400;">Here the important information is, you can have a number of intermediate operations and computation on the source data which is performed only when the terminal operation is initiated. Streams are Lazy and source elements are consumed only as needed.</span></p>
<h3>9. Stream vs Collection</h3>
<table dir="ltr" style="height: 410px;" border="1" width="637" cellspacing="0" cellpadding="0">
<colgroup>
<col width="331" />
<col width="275" /></colgroup>
<tbody>
<tr>
<td style="text-align: center;" data-sheets-value="{&quot;1&quot;:2,&quot;2&quot;:&quot;Stream&quot;}"><strong>Stream</strong></td>
<td style="text-align: center;" data-sheets-value="{&quot;1&quot;:2,&quot;2&quot;:&quot;Collections&quot;}"><strong>Collections</strong></td>
</tr>
<tr>
<td data-sheets-value="{&quot;1&quot;:2,&quot;2&quot;:&quot;No Storage. A stream is not a data structure that stores elements&quot;}">No Storage. A stream is not a data structure that stores elements</td>
<td data-sheets-value="{&quot;1&quot;:2,&quot;2&quot;:&quot;Collections holds all the elements on memory&quot;}">Collections holds all the elements on memory</td>
</tr>
<tr>
<td data-sheets-value="{&quot;1&quot;:2,&quot;2&quot;:&quot;Functional in nature. An operation on a stream produces a result, but does not modify its source&quot;}">Functional in nature. An operation on a stream produces a result, but does not modify its source</td>
<td data-sheets-value="{&quot;1&quot;:2,&quot;2&quot;:&quot;Non Functional. An operations on a collection would modify its content&quot;}">Non Functional. An operations on a collection would modify its content</td>
</tr>
<tr>
<td data-sheets-value="{&quot;1&quot;:2,&quot;2&quot;:&quot;Laziness-seeking. Many stream operations such as filtering, mapping can be implemented lazily.&quot;}">Laziness-seeking. Many stream operations such as filtering, mapping can be implemented lazily.</td>
<td data-sheets-value="{&quot;1&quot;:2,&quot;2&quot;:&quot;Collections are not lazy&quot;}">Collections are not lazy</td>
</tr>
<tr>
<td data-sheets-value="{&quot;1&quot;:2,&quot;2&quot;:&quot;Possibly unbounded. While collections have the finite size, streams need not. Short circuiting operations such as limit can allow compuations on infinite streams to complete in finite time&quot;}">Possibly unbounded. While collections have finite size, streams need not. Short circuiting operations such as limit can allow computations on infinite streams to complete in finite time</td>
<td data-sheets-value="{&quot;1&quot;:2,&quot;2&quot;:&quot;collections have the finite size&quot;}">Collections have the finite size</td>
</tr>
<tr>
<td data-sheets-value="{&quot;1&quot;:2,&quot;2&quot;:&quot;Consumable. The elements of a stream are only visitied once during the life of a stream&quot;}">Consumable. The elements of a stream are only visited once during the life of a stream</td>
<td data-sheets-value="{&quot;1&quot;:2,&quot;2&quot;:&quot;We can process collections number of time&quot;}"><span style="font-weight: 400;">We can process collections a number of times.</span></td>
</tr>
<tr>
<td data-sheets-value="{&quot;1&quot;:2,&quot;2&quot;:&quot;API to process the data&quot;}">API to process the data</td>
<td data-sheets-value="{&quot;1&quot;:2,&quot;2&quot;:&quot;Data structure which holds the data&quot;}">Data structure which holds the data</td>
</tr>
</tbody>
</table>
<h3>10. Intermediate operation vs Terminate operations in Stream</h3>
<p><span style="font-weight: 400;">Stream operations are divided into intermediate operations and terminal operations. They are combined to form a stream pipeline. </span><b>Intermediate operations</b><span style="font-weight: 400;"> return a new stream. It&#8217;s always lazy, meaning that executing intermediate operations such as filter() does not actually perform. But creates a new stream. When terminal operation is initiated, the traversal of all intermediate operations will be executed. </span><b>Terminal operations</b><span style="font-weight: 400;"> such as Stream.forEach may traverse the stream to produce the final result. After the terminal operation is performed, the stream pipeline is considered as consumed and can no longer be used.</span></p>
<h3>11. map vs flatmap</h3>
<p><strong>map</strong> <span style="font-weight: 400;">&#8211; Transforms the stream by applying the given function to all the elements of its stream. It is an intermediate operation.</span></p>
<pre><code class="language-java">// transforms all elements to uppercase
Stream.of("apple", "meta", "google")
        .map(mapper -&gt; mapper.toUpperCase()).collect(Collectors.toList());
// output
[APPLE, META, GOOGLE]</code></pre>
<p><strong>flatMap</strong> &#8211; flattening the resulting elements into a new stream. One-to-many transformation to the elements of the stream.</p>
<pre><code class="language-java">List&lt;Integer&gt; list1 = Arrays.asList(1,2,3);
        List&lt;Integer&gt; list2 = Arrays.asList(4,5,6);
        List&lt;Integer&gt; list3 = Arrays.asList(7,8,9);
        // flatten the elements into a single list
        List&lt;Integer&gt; result = Stream.of(list1, list2, list3)
        .flatMap(list -&gt; list.stream()).collect(Collectors.toList());

// output
[1, 2, 3, 4, 5, 6, 7, 8, 9]</code></pre>
<h3>12. findFirst vs findAny vs anyMatch vs allMatch vs noneMatch</h3>
<p><strong>findFirst</strong> &#8211; To find the first element of the stream. It will return the Optional object with either the first element or the empty optional object. This is a terminal operation.</p>
<pre><code class="language-java">Optional&lt;String&gt; first = Stream.of("apple", "meta", "google").findFirst();
System.out.println(first.get());
// output
apple</code></pre>
<p><strong>findAny</strong> &#8211; To find any element of the stream. It will return the Optional object with any one of the <span style="font-weight: 400;">elements </span> or the empty optional object. This is also a terminal operation.</p>
<pre><code class="language-java">Optional&lt;String&gt; any = Stream.of("apple", "meta", "google").findAny();
System.out.println(any.get());
// output
apple</code></pre>
<p><strong>anyMatch</strong> &#8211; <span style="font-weight: 400;">Returns true if any one of the elements evaluates true with the provided predicate. If the stream is empty or all elements evaluate false with the provided predicate then it will return false.</span></p>
<pre><code class="language-java">boolean any = Stream.of("apple", "meta", "google").anyMatch(predicate -&gt; predicate.equals("apple"));
System.out.println(any);
// output
true</code></pre>
<p><strong>allMatch</strong> &#8211; Returns true if all the elements <span style="font-weight: 400;">evaluate </span> true with the provided predicate. If the stream is empty then it will return true without evaluating the predicate.</p>
<pre><code class="language-java">boolean allMatch = Stream.of("apple", "meta", "google").allMatch(predicate -&gt; predicate instanceof String);
System.out.println(allMatch);
// output
true</code></pre>
<p><strong>noneMatch</strong> &#8211; Returns true if no elements evaluate true with the provided predicate. If the stream is empty then it will return true without evaluating the predicate.</p>
<pre><code class="language-java">boolean noneMatch = Stream.of("apple", "meta", "google").noneMatch(predicate -&gt; predicate.equals("facebook"));
System.out.println(noneMatch);
// output
true</code></pre>
<h3>13. skip vs limit vs count</h3>
<p><strong>skip</strong> &#8211; discards the first N elements of the stream. If the stream contains less elements than N ,then it will return an empty stream. This is an intermediate operation.</p>
<pre><code class="language-java">List&lt;Integer&gt; skipList = Stream.of(10,20,30,40,50).skip(2).collect(Collectors.toList());
System.out.println(skipList);
// output
[30, 40, 50]</code></pre>
<p><strong>limit</strong> &#8211; returns only the first N elements of the stream. It will throw an exception if the N is negative. This is also an intermediate operation.</p>
<pre><code class="language-java">// first skip the list, and then limit from it
List&lt;Integer&gt; limitList = Stream.of(10,20,30,40,50).skip(2).limit(2).collect(Collectors.toList());
System.out.println(limitList);
// output
[30, 40]</code></pre>
<p><strong>count</strong> &#8211; returns the count of elements in the stream. This is a terminal operation.</p>
<pre><code class="language-java">Long count = Stream.of(10,20,30,40,50).skip(2).limit(2).count();
System.out.println(count);
// output
2</code></pre>
<h3>14. map vs filter vs forEach vs sorted</h3>
<p><strong>map</strong> &#8211; a transformation operation. Returns a new stream after applying the given Function to all the elements of this stream. This is an intermediate operation.</p>
<pre><code class="language-java">&lt;R&gt; Stream&lt;R&gt; map(Function&lt;? super T, ? extends R&gt; mapper);
// Transformation operation
List&lt;String&gt; strings =  Stream.of("apple", "meta", "google")
        .map(mapper -&gt; mapper.toUpperCase()).collect(Collectors.toList());
// output
[APPLE, META, GOOGLE]</code></pre>
<p><strong>filter</strong> &#8211; Returns a new stream which matches the given predicate(the predicate should evaluate true). This is also an intermediate operation.</p>
<pre><code class="language-java">Stream&lt;T&gt; filter(Predicate&lt;? super T&gt; predicate);
// Filter operation
List&lt;Integer&gt; filterList = Stream.of(10,20,30,40,50)
                .filter(predicate -&gt; predicate &gt; 25).collect(Collectors.toList());
// output
[30, 40, 50]</code></pre>
<p><strong>forEach</strong> &#8211; Performs the action for each element of this stream. This is a terminal operation.</p>
<pre><code class="language-java">void forEach(Consumer&lt;? super T&gt; action);
// Just performs an action of its element
Stream.of(10,20,30,40,50).forEach(action -&gt; System.out.println(action));
// output
10
20
30
40
50</code></pre>
<p><strong>sorted</strong> &#8211; Returns a new stream after sorting the elements based on the provided Comparator. This is an intermediate operation.</p>
<pre><code class="language-java">// Default sorting is ascending without Comparator
List&lt;Integer&gt; sortedList1 = Stream.of(4,2,3,1).sorted().collect(Collectors.toList());

// Based on provided Comparator 
List&lt;Integer&gt; sortedList2 = Stream.of(4,2,3,1).sorted(Comparator.reverseOrder()).collect(Collectors.toList());

// output - sortedList1
[1, 2, 3, 4]
// output - sortedList12
[4, 3, 2, 1]</code></pre>
<h3>15. groupBy vs mapping</h3>
<p><strong>groupBy</strong> &#8211; groups the elements based on the classification function and <span style="font-weight: 400;">returns </span> the result in the map. The key should be the grouping element and value should be the list.</p>
<pre><code class="language-java">The following will classify Person objects by city:

Map&lt;String, List&lt;Person&gt;&gt; peopleByCity = personStream.collect(Collectors.groupingBy(Person::getCity);
 
The following will classify Person objects by state and city, cascading two Collectors together:

     Map&lt;String, Map&lt;String, List&lt;Person&gt;&gt;&gt; peopleByStateAndCity =personStream.collect(Collectors.groupingBy(Person::getState,
                                        Collectors.groupingBy(Person::getCity)));</code></pre>
<p><strong>mapping</strong> &#8211; When we do collect with reduction operation, we can transform the element by applying the mapping function to each input before accumulation. In the below example, the Person object transforms to last name during the accumulation.</p>
<pre><code class="language-java">Map&lt;City, Set&lt;String&gt;&gt; lastNamesByCity
            = people.stream().collect(
              groupingBy(Person::getCity,
                         mapping(Person::getLastName,
                                toSet())));</code></pre>
<h3>16. Reduction operations</h3>
<p>A reduction operation takes a sequence of input elements and combines them into a single summary result. For example, finding the sum or accumulating elements into a list. The stream classes have multiple forms of general reduction operations called reduce() and collect(). And we are having reductions forms such as sum(), max(), or count().</p>
<pre><code class="language-java">int sum = 0;
for (int x : numbers) {
      sum += x;
}

// Above operation can be implemented using reduction
int sum = numbers.stream().reduce(0, (x,y) -&gt; x+y);</code></pre>
<p><strong>Mutable reduction</strong> accumulates input elements into a mutable result container such as a <code>Collection</code> or <code>StringBuilder</code>, as it processes the elements in the stream.</p>
<h3>17. stream vs parallel stream which one should use</h3>
<p>Parallel stream has a higher view compared to sequential stream. But Parallel stream needs threads which takes a significant amount of time. I would prefer to use sequential streams by default and we can go for parallel ones if</p>
<ul>
<li>having large amount of items to process</li>
<li>having the performance problem</li>
<li>we don&#8217;t already run other process in a <span style="font-weight: 400;">multithreaded </span> environment</li>
</ul>
<p><span style="font-weight: 400;">Meanwhile, note that parallel streams will not solve synchronization problems if predicates and functions in the process uses a shared resource. Here, we have to ensure that all are thread-safe. So whenever we use parallel streams, we should worry about side effects.</span></p>
<h3>18. why static method introduced in Interface with Java 8</h3>
<p><span style="font-weight: 400;">Static methods make it easier to organize the helper methods in our libraries. We can create static methods specific to an interface in the same interface rather than in a separate class. We can also ignore public modifiers since all methods are implicitly public in the interface. At the same time you should be careful that the interface has to be clear and does not create additional clutter in the API.</span></p>
<p><span style="font-weight: 400;">Even the JDK code has Collectors &#8211; static factory methods, and a Collector interface at the same time. Those methods could be merged into the Collector interface, but that would make the interface more clunky.</span></p>
<h3>19. Date API&#8217;s in Java 8</h3>
<p><strong>LocalDate</strong> &#8211; a date in ISO format(yyyy-MM-dd). LocalDate provides a lot of utility methods to perform various data operations.</p>
<pre><code class="language-java">LocalDate localDate = LocalDate.now();

LocalDate.of(2015, 02, 20);

LocalDate.parse("2015-02-20");</code></pre>
<p><strong>LocalTime</strong> &#8211; a time without the date. LocalTime also provides lot of utility methods.</p>
<pre><code class="language-java">LocalTime now = LocalTime.now();
LocalTime sixThirty = LocalTime.of(6, 30);
LocalTime sixThirty = LocalTime.parse("06:30");</code></pre>
<p><strong>LocalDateTime</strong> &#8211; a combination of date and time. We can use this while we need the combination of date and time.</p>
<pre><code class="language-java">LocalDateTime.now();
LocalDateTime.of(2015, Month.FEBRUARY, 20, 06, 30);
LocalDateTime.parse("2015-02-20T06:30:00");</code></pre>
<p><strong>ZonedDateTime API</strong> &#8211; If we need a zone specific date and time we can go for a ZonedDatTime class. Here the ZoneId used to represent different zones.</p>
<pre><code class="language-java">ZoneId zoneId = ZoneId.of("Europe/Paris");
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
ZonedDateTime.parse("2015-05-03T10:15:30+01:00[Europe/Paris]");
</code></pre>
<p><strong>Period and Duration</strong> &#8211; The Period provides a quantity of time in terms of year, month and days. The Duration provides the quantity of time in terms of seconds and nanosconds.</p>
<h3>20. Nashorn Engine in java 8</h3>
<p><span style="font-weight: 400;">The Nashorn engine is an implementation of ECMAScript. It was developed in the Java language as the Nashorn project. The Nashorn engine is included in the JDK in Java 1.8. Nashorn Java API allows us to write Java Applications as scripts which can be interpreted by the Nashorn engine.</span></p>
<h3>You May Also Like</h3>
<ul>
<li><a href="https://programeasily.com/2021/07/16/basic-git-commands-part-1/">Basic Git Commands – Part 1</a></li>
<li><a href="https://programeasily.com/2021/06/20/react-best-free-admin-dashboard-template-in-2021/">React Best Free Admin Dashboard Template in 2021</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://programeasily.com/2022/01/04/java-8-interview-questions-for-experienced/">Java 8 Interview Questions for Experienced</a> appeared first on <a rel="nofollow" href="https://programeasily.com">Program Easily</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programeasily.com/2022/01/04/java-8-interview-questions-for-experienced/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">540</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/

Page Caching using disk: enhanced 
Minified using disk
Database Caching 3/45 queries in 0.025 seconds using disk

Served from: programeasily.com @ 2025-06-27 02:20:17 by W3 Total Cache
-->