<?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/"
	>

<channel>
	<title>Java &#8211; jasta</title>
	<atom:link href="https://jasta.io/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>https://jasta.io</link>
	<description>Beyond Syntax</description>
	<lastBuildDate>Sun, 14 Apr 2024 20:23:17 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>

<image>
	<url>https://jasta.io/wp-content/uploads/2024/01/cropped-jasta_favicon-32x32.webp</url>
	<title>Java &#8211; jasta</title>
	<link>https://jasta.io</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Writing Unit Tests in Java with JUnit 5: A Comprehensive Guide</title>
		<link>https://jasta.io/java-basics/writing-unit-tests-in-java-with-junit-5/</link>
					<comments>https://jasta.io/java-basics/writing-unit-tests-in-java-with-junit-5/#respond</comments>
		
		<dc:creator><![CDATA[Jakob]]></dc:creator>
		<pubDate>Sun, 14 Apr 2024 14:51:39 +0000</pubDate>
				<category><![CDATA[Java Basics]]></category>
		<category><![CDATA[IntelliJ IDEA]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JUnit 5]]></category>
		<guid isPermaLink="false">https://jasta.io/?p=2943</guid>

					<description><![CDATA[Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into how to write unit tests in Java with JUnit 5, providing a step-by-step guide to help you accomplish this on your computer. Whether you’re a seasoned tech guru or just starting your digital journey, our straightforward instructions will make the process a breeze. Let’s jump in and start writing unit tests in Java with JUnit 5.</p>



<div class="wp-block-rank-math-toc-block" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#why-you-should-implement-unit-tests-for-your-java-application">Why You Should Implement Unit Tests for Your Java Application</a></li><li><a href="#most-important-annotations-for-j-unit-5-tests-in-java">Most Important Annotations for JUnit 5 tests in Java</a></li><li><a href="#step-by-step-guide-to-writing-unit-tests-in-java-with-j-unit-5">Step-by-Step Guide to Writing Unit Tests in Java with JUnit 5</a></li></ul></nav></div>



<h2 class="wp-block-heading" id="why-you-should-implement-unit-tests-for-your-java-application">Why You Should Implement Unit Tests for Your Java Application</h2>



<p>In modern software development, unit testing stands as an indispensable pillar of ensuring code quality and reliability. At its core, unit testing involves the systematic validation of individual units or components of a software application, typically at the function or method level. The primary goal? To verify that each unit behaves exactly as intended under various conditions, effectively contributing to the overall functionality of the system.</p>



<p>Writing unit tests in Java with JUnit 5 offers a structured approach to this crucial aspect of software engineering. By meticulously crafting tests to assess the behavior of isolated code units, developers gain invaluable insights into the correctness and robustness of their implementations. But why is unit testing so vital, especially in the context of Java development with JUnit 5?</p>



<p>First and foremost, unit testing serves as an early warning system, flagging potential bugs and errors in the codebase long before they manifest into critical issues in a production environment. By identifying and rectifying these issues early in the development lifecycle, developers can significantly reduce the time and effort spent on debugging and troubleshooting later stages.</p>



<p>Moreover, unit testing fosters a culture of confidence and trust in the codebase. Each passing test provides a tangible affirmation that a particular piece of functionality works as expected, instilling a sense of assurance among developers and stakeholders alike. This confidence translates into smoother integration processes, as developers can confidently integrate their changes knowing that existing functionality remains intact.</p>



<p>Furthermore, writing unit tests in Java with JUnit 5 facilitates seamless code maintenance and refactoring. As software projects evolve over time, developers often need to make changes to existing code to accommodate new requirements or optimize performance. Unit tests act as a safety net, ensuring that modifications do not inadvertently introduce regressions or break existing functionality.</p>



<p>In summary, unit testing with JUnit 5 is not merely a best practice; it&#8217;s a fundamental aspect of modern software development. By validating individual units of code in isolation, developers can uncover defects early, build confidence in their codebase, and facilitate seamless maintenance and evolution of software projects.</p>



<h2 class="wp-block-heading" id="most-important-annotations-for-j-unit-5-tests-in-java">Most Important Annotations for JUnit 5 tests in Java</h2>



<p>In JUnit 5, annotations play an important role in defining the behavior and structure of unit tests. Understanding and effectively utilizing these annotations is essential for writing clear, concise, and maintainable test code. Below, are some important annotations that are necessary for writing unit tests in Java with JUnit 5.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Test</pre>



<p>This annotation is used to mark a method as a test method. JUnit 5 will execute all methods annotated with @Test.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@BeforeEach</pre>



<p>Methods annotated with @BeforeEach are executed before each test method in the class. They are typically used to set up common test fixtures or initialize resources.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@AfterEach</pre>



<p>Methods annotated with @AfterEach are executed after each test method in the class. They are commonly used to clean up resources or reset the state after each test.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@BeforeAll</pre>



<p>Methods annotated with @BeforeAll are executed once before all test methods in the class. They are used for setup operations that are performed once for the entire test class.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@AfterAll</pre>



<p>Methods annotated with @AfterAll are executed once after all test methods in the class have been executed. They are typically used for cleanup operations that need to be performed once after all tests have finished.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Disabled</pre>



<p>Methods annotated with @Disabled are skipped during test execution. This annotation is useful for temporarily excluding tests that are not ready or relevant</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@ExtendWith</pre>



<p>Used to register extensions with JUnit 5 tests, @ExtendWith allows you to customize the behavior of test classes or methods by applying additional functionality provided by extensions.</p>



<h2 class="wp-block-heading" id="step-by-step-guide-to-writing-unit-tests-in-java-with-j-unit-5">Step-by-Step Guide to Writing Unit Tests in Java with JUnit 5</h2>



<p>In this tutorial, we are writing unit tests in Java with JUnit 5 for our FileHelper from the <a href="https://jasta.io/java-basics/reading-files-in-java/">reading</a> and <a href="https://jasta.io/java-basics/writing-to-files-in-java/">writing</a> to files in Java tutorials. You can find the full code of the FileHelper class <a href="https://github.com/jastaio/JavaTutorials/blob/main/FileReaderWriter/src/main/java/FileHelper.java" target="_blank" rel="noopener">here</a> on our GitHub repository.</p>



<p>To start, we must create a class that will later contain all the tests. This can be automatically done. For that, you need to open the class which should be tested and press CTRL+SHIFT+T on your keyboard. Now a small menu will appear where you can click on create new test. Then a configuration window is going to show on your screen. With that configurator, you can choose the JUnit version, the class name, a superclass, and the destination package and you can even auto-generate the setup and teardown methods and create test methods for the methods inside the class.</p>



<p>For this tutorial, we are just choosing the correct version and the class name. The rest will be left empty.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img fetchpriority="high" decoding="async" width="437" height="469" src="https://jasta.io/wp-content/uploads/2024/04/JUnit5ClassConfiguration.webp" alt="" class="wp-image-2950" srcset="https://jasta.io/wp-content/uploads/2024/04/JUnit5ClassConfiguration.webp 437w, https://jasta.io/wp-content/uploads/2024/04/JUnit5ClassConfiguration-280x300.webp 280w" sizes="(max-width: 437px) 100vw, 437px" /></figure>
</div>


<p>For our FileHelper we want to test both read and write methods. All of the methods have a Path as a method parameter so we first need to create a file within a directory that can be used for testing. To not have to worry about deleting the directory after all the tests, we are using the @TempDir annotation. This will generate a temporary directory when starting the tests. After all the tests run through, the directory will be deleted automatically. Without this annotation it would be necessary, to create the directory in the @BeforeAll method and delete it in the @AfterAll method.</p>



<p>In addition to the directory that will contain the file, we are also declaring a file name, the file for the tests itself and the file content in the test class. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  @TempDir
  private File tempDir;
  private final String fileName = "tempFile.txt";
  private File tempFile = new File(tempDir, fileName);;
  private final List&lt;String> testContent = List.of("Hello World!", "This is a test.");</pre>



<p>After declaring every necessary variable in the class we are creating the @BeforeEach and @AfterEach method. In these methods, we are going to create/delete the file that will be used for the tests.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  @BeforeEach
  void setUp() throws IOException {
    tempFile.createNewFile();
  }

  @AfterEach
  void tearDown() {
    tempFile.delete();
  }</pre>



<p>Now we are going to test our methods of the FileWriter class. Since the FileWriter class has read and write methods implemented with java.nio and java.io, we are going to test these in two different tests. </p>



<p>To create a unit test you need to write a method that does something to begin with. In this case, this would be FileHelper.writeToFile and FileHelper.readFromFile. To make this method a test you need to add a @Test annotation above the method declaration. Now the method is already a valid test which calls a method but doesn&#8217;t check if the method is actually working. Therefore we are adding an assertEquals call which will check if the file content written and then read by our FileHelper has the same amount of lines. Furthermore, we are iterating through the read results and checking if it is equal to the content we wanted to write with the FileHelper.</p>



<p>If all these assertions are correct, we know that the writing and reading of files is working correctly. The same checks are also done in the test method for the java.io FileWriter methods.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  @Test
  void testFileWriter() {
    FileHelper.writeToFile(tempFile.getAbsolutePath(), String.join("\n", testContent));
    List&lt;String> fileContent = FileHelper.readFromFile(tempFile.getAbsolutePath());

    assertEquals(testContent.size(), fileContent.size());

    for (int i = 0; i &lt; testContent.size(); i++) {
      assertEquals(testContent.get(i), fileContent.get(i));
    }
  }

  @Test
  void testBufferedFileWriter() {
    FileHelper.writeToFileBufferedWriter(tempFile.getAbsolutePath(),
        String.join("\n", testContent));
    List&lt;String> fileContent = FileHelper.readFromFileBufferedReader(tempFile.getAbsolutePath());

    assertEquals(testContent.size(), fileContent.size());

    for (int i = 0; i &lt; testContent.size(); i++) {
      assertEquals(testContent.get(i), fileContent.get(i));
    }
  }</pre>



<p>To prevent code duplications, the checks can also be done in a separate method which is called by a test method. The code would then look like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  @Test
  void testFileWriter() {
    FileHelper.writeToFile(tempFile.getAbsolutePath(), String.join("\n", testContent));
    checkReadResult(FileHelper.readFromFile(tempFile.getAbsolutePath()));
  }

  @Test
  void testBufferedFileWriter() {
    FileHelper.writeToFileBufferedWriter(tempFile.getAbsolutePath(),
        String.join("\n", testContent));
    checkReadResult(FileHelper.readFromFileBufferedReader(tempFile.getAbsolutePath()));
  }

  private void checkReadResult(List&lt;String> actualContent) {
    assertEquals(testContent.size(), actualContent.size());

    for (int i = 0; i &lt; testContent.size(); i++) {
      assertEquals(testContent.get(i), actualContent.get(i));
    }
  }</pre>



<p>It&#8217;s also possible to assert Exceptions to test invalid parameters given to the FileHelper. Instead of assertEquals you can use assertThrows with the expected exception class, an executable code and you can also add an error message to all of your assertions. It is also possible to check the exception message because assertThrows returns the occurred exception.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  @Test
  void readFromFileError() {
    RuntimeException e = assertThrows(RuntimeException.class,
        () -> FileHelper.readFromFile(tempDir.getAbsolutePath()),
        "Exception was not thrown!");

    assertEquals(e.getCause().getMessage(), "The file cannot be accessed!");
  }

  @Test
  void readFromFileBufferedReaderError() {
    assertThrows(RuntimeException.class,
        () -> FileHelper.readFromFileBufferedReader(tempDir.getAbsolutePath()),
        "Exception was not thrown!");
  }</pre>



<p>Your full test class should now be the same as the code below. You can also find the complete code <a href="https://github.com/jastaio/JavaTutorials/blob/main/FileReaderWriter/src/test/java/FileHelperTest.java" target="_blank" rel="noopener">here</a>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import static org.junit.jupiter.api.Assertions.*;

import java.io.File;
import java.io.IOException;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

class FileHelperTest {

  @TempDir
  private File tempDir;
  private final String fileName = "tempFile.txt";
  private File tempFile = new File(tempDir, fileName);;
  private final List&lt;String> testContent = List.of("Hello World!", "This is a test.");

  @BeforeEach
  void setUp() throws IOException {
    tempFile.createNewFile();
  }

  @AfterEach
  void tearDown() {
    tempFile.delete();
  }

  @Test
  void testFileWriter() {
    FileHelper.writeToFile(tempFile.getAbsolutePath(), String.join("\n", testContent));
    checkReadResult(FileHelper.readFromFile(tempFile.getAbsolutePath()));
  }

  @Test
  void testBufferedFileWriter() {
    FileHelper.writeToFileBufferedWriter(tempFile.getAbsolutePath(),
        String.join("\n", testContent));
    checkReadResult(FileHelper.readFromFileBufferedReader(tempFile.getAbsolutePath()));
  }

  private void checkReadResult(List&lt;String> actualContent) {
    assertEquals(testContent.size(), actualContent.size());

    for (int i = 0; i &lt; testContent.size(); i++) {
      assertEquals(testContent.get(i), actualContent.get(i));
    }
  }

  @Test
  void readFromFileError() {
    RuntimeException e = assertThrows(RuntimeException.class,
        () -> FileHelper.readFromFile(tempDir.getAbsolutePath()),
        "Exception was not thrown!");

    assertEquals(e.getCause().getMessage(), "The file cannot be accessed!");
  }

  @Test
  void readFromFileBufferedReaderError() {
    assertThrows(RuntimeException.class,
        () -> FileHelper.readFromFileBufferedReader(tempDir.getAbsolutePath()),
        "Exception was not thrown!");
  }
}</pre>



<p>Now that your test class is ready, you can execute the whole test class with all the tests with the green arrow next to the class name inside the code or just run a single test method with the green arrow next to the method declaration.</p>



<p>When the tests are finished you will see the result of them in the run window at the bottom of your IDE as shown in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img decoding="async" width="1024" height="209" src="https://jasta.io/wp-content/uploads/2024/04/JUnit5TestsInJava-1024x209.webp" alt="Writing Unit Tests in Java with JUnit 5" class="wp-image-2947" srcset="https://jasta.io/wp-content/uploads/2024/04/JUnit5TestsInJava-1024x209.webp 1024w, https://jasta.io/wp-content/uploads/2024/04/JUnit5TestsInJava-300x61.webp 300w, https://jasta.io/wp-content/uploads/2024/04/JUnit5TestsInJava-768x157.webp 768w, https://jasta.io/wp-content/uploads/2024/04/JUnit5TestsInJava-512x104.webp 512w, https://jasta.io/wp-content/uploads/2024/04/JUnit5TestsInJava-920x188.webp 920w, https://jasta.io/wp-content/uploads/2024/04/JUnit5TestsInJava.webp 1054w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>If you don&#8217;t see each test method result but only the test class, you have to switch from running unit tests with Gradle to running them with IntelliJ IDEA. To do this you first have to open the settings of IntelliJ. This can be done with CTRL+ALT+S or via the top menu under &#8216;File&#8217;. After opening the settings window, you need to find &#8216;Build, Execution, Deployment&#8217; on the left side, expand it, find Build Tools and click on Gradle. In the window after clicking on Gradle you can now set &#8216;Run tests using:. Choose IntelliJ IDEA from the drop-down menu and click OK. </p>



<p>If you now run your unit tests you will see every single test listed on the run window.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" width="975" height="729" src="https://jasta.io/wp-content/uploads/2024/04/IntelliJ_runTestsWithIntelliJIDEA.webp" alt="Run unit tests with IntelliJ IDEA" class="wp-image-2946" srcset="https://jasta.io/wp-content/uploads/2024/04/IntelliJ_runTestsWithIntelliJIDEA.webp 975w, https://jasta.io/wp-content/uploads/2024/04/IntelliJ_runTestsWithIntelliJIDEA-300x224.webp 300w, https://jasta.io/wp-content/uploads/2024/04/IntelliJ_runTestsWithIntelliJIDEA-768x574.webp 768w, https://jasta.io/wp-content/uploads/2024/04/IntelliJ_runTestsWithIntelliJIDEA-512x383.webp 512w, https://jasta.io/wp-content/uploads/2024/04/IntelliJ_runTestsWithIntelliJIDEA-920x688.webp 920w" sizes="(max-width: 975px) 100vw, 975px" /></figure>
</div>


<p>If a unit test fails you will also be able to see the difference in the result window, so you don&#8217;t have to debug into the test to see what values are getting compared or checked.</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="253" src="https://jasta.io/wp-content/uploads/2024/04/JUnit5FailedTest-1024x253.webp" alt="" class="wp-image-2951" srcset="https://jasta.io/wp-content/uploads/2024/04/JUnit5FailedTest-1024x253.webp 1024w, https://jasta.io/wp-content/uploads/2024/04/JUnit5FailedTest-300x74.webp 300w, https://jasta.io/wp-content/uploads/2024/04/JUnit5FailedTest-768x190.webp 768w, https://jasta.io/wp-content/uploads/2024/04/JUnit5FailedTest-512x127.webp 512w, https://jasta.io/wp-content/uploads/2024/04/JUnit5FailedTest-920x228.webp 920w, https://jasta.io/wp-content/uploads/2024/04/JUnit5FailedTest.webp 1091w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>As we wrap up our journey through the process of writing unit tests in Java with JUnit 5, I hope you&#8217;ve found this guide insightful and helpful in enhancing your knowledge. Should you encounter any questions or challenges while implementing, don&#8217;t hesitate to reach out. Your feedback, queries, and insights are always valued, and I&#8217;m here to assist you on your coding adventures. Until next time, happy coding!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jasta.io/java-basics/writing-unit-tests-in-java-with-junit-5/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Implement Powerful Logging in Java with Log4j2</title>
		<link>https://jasta.io/java-basics/logging-in-java-with-log4j2/</link>
					<comments>https://jasta.io/java-basics/logging-in-java-with-log4j2/#respond</comments>
		
		<dc:creator><![CDATA[Jakob]]></dc:creator>
		<pubDate>Thu, 04 Apr 2024 15:57:50 +0000</pubDate>
				<category><![CDATA[Java Basics]]></category>
		<category><![CDATA[IntelliJ IDEA]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://jasta.io/?p=2902</guid>

					<description><![CDATA[Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into how to implement logging in Java with Log4j2, providing a step-by-step guide to help you accomplish this on your computer. Whether you’re a seasoned tech guru or just starting your digital journey, our straightforward instructions will make the process a breeze. Let’s jump in and start implementing logging in Java with Log4j2.</p>



<div class="wp-block-rank-math-toc-block" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#why-proper-logging-is-necessary-for-every-application">Why Proper Logging is Necessary for Every Application</a></li><li><a href="#adding-log-4-j-2-dependencies-to-your-project">Adding Log4j2 Dependencies to Your Project</a></li><li><a href="#implement-logging-in-java-with-log-4-j-2">Implement Logging in Java with Log4j2</a></li></ul></nav></div>



<h2 class="wp-block-heading" id="why-proper-logging-is-necessary-for-every-application">Why Proper Logging is Necessary for Every Application</h2>



<p>Proper logging is indispensable for every application as it serves as a crucial lifeline for developers and operators alike. Logging provides a detailed record of system behavior, errors, and events, aiding in troubleshooting and debugging processes. It offers insights into the application&#8217;s health, performance, and usage patterns, enabling developers to identify and rectify issues promptly. </p>



<p>Moreover, comprehensive logs enhance security by facilitating the detection of suspicious activities or breaches. In essence, robust logging practices not only enhance the reliability and maintainability of an application but also contribute significantly to its overall security and performance. </p>



<h2 class="wp-block-heading" id="adding-log-4-j-2-dependencies-to-your-project">Adding Log4j2 Dependencies to Your Project</h2>



<p>Before implementing logging in Java with Log4j2 you first need to add certain dependencies to your <a href="https://jasta.io/java-basics/create-your-first-java-program-with-ease/">Java project</a> so that you can use Log4j2. If you are using Kotlin as your DSL you can copy the required dependencies from below. If you use any other language you can find the correct dependency implementation on the Maven repository. To follow this tutorial you need the <a href="https://mvnrepository.com/artifact/org.slf4j/slf4j-api/2.0.12" target="_blank" rel="noopener">slf4j-api dependency</a> and the <a href="https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-slf4j2-impl/2.23.1" target="_blank" rel="noopener">log4j-slf4j2-impl</a>. The dependencies need to be added to your build.gradle if you use Gradle or to your pom.xml if you use Maven.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    implementation("org.slf4j:slf4j-api:2.0.12")
    implementation("org.apache.logging.log4j:log4j-slf4j2-impl:2.23.1")</pre>



<h2 class="wp-block-heading" id="implement-logging-in-java-with-log-4-j-2">Implement Logging in Java with Log4j2</h2>



<p>The first thing you need to do to implement logging in Java with Log4j2 is, to create a configuration file. In that file, you need to define different settings like log levels, different log appenders and settings for these like a Rollover strategy. The file must be placed in your application&#8217;s resources folder and named &#8216;log4j2&#8217;. The file type is XML. After the creation, it should look like the red highlighted file below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="381" height="319" src="https://jasta.io/wp-content/uploads/2024/04/log4j2ConfigurationFile.webp" alt="Log4j2.xml configuration" class="wp-image-2910" srcset="https://jasta.io/wp-content/uploads/2024/04/log4j2ConfigurationFile.webp 381w, https://jasta.io/wp-content/uploads/2024/04/log4j2ConfigurationFile-300x251.webp 300w" sizes="auto, (max-width: 381px) 100vw, 381px" /></figure>
</div>


<p>Inside the file, you can now define different configurations. For example, you can create a File logger or configure it, to log everything in the application console. But you can also configure multiple loggers. All the different configurations can be found on the <a href="https://logging.apache.org/log4j/2.x/manual/appenders.html" target="_blank" rel="noopener">website of Apache about log4j2.</a></p>



<p>In this tutorial, we are going to create a file logger. The file logger will be configured with a SizeBasedTriggeringPolicy which means that if the current log file of the app is bigger than the configured value, a new log file will be created and the &#8216;full&#8217; one will be saved. We are also adding a DefaultRolloverStrategy. With that, it can be prevented that hundreds of &#8216;full&#8217; log files are being created. You can have different conditions to delete old log files like a maximum amount, an age limitation and many more.</p>



<p>You can copy the full code of the file logger configuration from the <a href="https://github.com/jastaio/JavaTutorials/tree/main/Log4jTest" target="_blank" rel="noopener">jasta GitHub repository</a> or from below. Carefully read the comments in the XML file to fully understand the meaning of each line inside the file, configure it to your requirements, and implement your custom logging in Java with Log4j2.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?xml version="1.0" encoding="UTF-8"?>
&lt;!--
Status defines the level of internal Log4j events that should be logged to the console.
If there are any configuration problems without an obvious error you can set it to trace or other levels.
Valid values are: off, trace, debug, info, warn, error, fatal, all
-->
&lt;Configuration status="info">
  &lt;Properties>
    &lt;!-- 
    The path of the log directory. With the configuration below, the log files are stored under 
    &lt;drive>:\logs
    -->
    &lt;Property name="LOG_DIR">/logs&lt;/Property>
  &lt;/Properties>

  &lt;Appenders>
    &lt;!--
     name: The name of the appender
     fileName: The name of the current log file
     filePattern: The file names of any older log which is created if the current log size exceeds the SizeBasedTriggeringPolicy
     immediateFlush: Log is written as soon as the log methods are called
     -->
    &lt;RollingFile
      name="fileLogger"
      fileName="${LOG_DIR}/AppCurrent.log"
      filePattern="${LOG_DIR}/App_%d{yyyy-MM-dd_hh-mm-ss}.log"
      immediateFlush="true">
      &lt;PatternLayout>
        &lt;!--
        The format of the log message inside the file
        Example: 2024-04-04 18:57:29.369 [Bank.register] [INFO] WorldBank Germany - Customer 'Id' successfully registered!
        Definition: &lt;Date with Time> [&lt;ClassName>.&lt;Method>] [&lt;Message Log Level>] &lt;LoggerName> - &lt;Message>
        -->
        &lt;Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%C{1}.%M] [%level] %logger{36} - %msg%n&lt;/Pattern>
      &lt;/PatternLayout>
      &lt;Policies>
        &lt;!-- Maximum size of the current log file -->
        &lt;SizeBasedTriggeringPolicy size="10MB"/>
      &lt;/Policies>

      &lt;!-- Rollover strategy to delete old log files -->
      &lt;DefaultRolloverStrategy>
        &lt;!-- Search path for the deletion and depth (1 = just the search path not any subfolders, -1: search path with every subfolder, 2,3,4...: search path with x subfolders -->
        &lt;Delete basePath="${LOG_DIR}" maxDepth="1">
          &lt;!-- File name pattern for the old log files -->
          &lt;IfFileName glob="App_*.log"/>
          &lt;!-- Maximum amount of old log file -->
          &lt;IfAccumulatedFileCount exceeds="10"/>
        &lt;/Delete>
      &lt;/DefaultRolloverStrategy>
    &lt;/RollingFile>
  &lt;/Appenders>

  &lt;Loggers>
    &lt;!--
    The log level of the root logger which will be applied to the child logger.
    With info log messages with .info, .error, .warn are logged - .debug for example will not get logged
    Valid values are: off, trace, debug, info, warn, error, fatal, all
    -->
    &lt;Root level="info">
      &lt;!-- Add the appender via its name -->
      &lt;AppenderRef ref="fileLogger"/>
    &lt;/Root>
  &lt;/Loggers>
&lt;/Configuration></pre>



<p>After you have copied the code above or configured it to your requirements, you can start logging in Java with Log4j2. Therefore you have to call LoggerFactory.getLogger(&lt;ConstructorParameter>) with either a class or a String as a constructor parameter. The given Parameter will be the name of the logger. The returned Object will be a Logger Object from org.slf4j.Logger. You can now call different log methods like debug, error, info, warn, trace and many more. Depending on what log level is set in the configuration file some messages will not get logged. All available methods can be seen <a href="https://www.slf4j.org/api/org/slf4j/Logger.html" target="_blank" rel="noopener">here</a>.</p>



<p>An example declaration would look like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">private static final Logger LOGGER = LoggerFactory.getLogger(TestDriver.class);</pre>



<p>Later the Logger object can be used like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">LOGGER.info("Application is starting...");</pre>



<p>If you are logging much, your log output directory will look similar to the screenshot below. As you can see, a new log file is created after 10KB (in this case 11KB since it is such a small unit. With MB it would not be 11MB). Also, the old log files are created with the date and time as configured in the log4j2.xml file. Furthermore, the limit of 10 old log files is also considered. If a new log file were to be created, the oldest log file, in this case &#8216;App_2024-04-06_05-13-05.log&#8217;, would be deleted.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="610" height="348" src="https://jasta.io/wp-content/uploads/2024/04/LogFileLog4j.webp" alt="Logging in Java with Log4j2" class="wp-image-2911" srcset="https://jasta.io/wp-content/uploads/2024/04/LogFileLog4j.webp 610w, https://jasta.io/wp-content/uploads/2024/04/LogFileLog4j-300x171.webp 300w, https://jasta.io/wp-content/uploads/2024/04/LogFileLog4j-512x292.webp 512w" sizes="auto, (max-width: 610px) 100vw, 610px" /></figure>
</div>


<p>This was the process of implementing logging in Java with Log4j2. If you have any questions or trouble implementing your logging system feel free to leave a comment below.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jasta.io/java-basics/logging-in-java-with-log4j2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Writing to Files in Java: Master File Operations with Ease</title>
		<link>https://jasta.io/java-basics/writing-to-files-in-java/</link>
					<comments>https://jasta.io/java-basics/writing-to-files-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Jakob]]></dc:creator>
		<pubDate>Fri, 29 Mar 2024 17:29:15 +0000</pubDate>
				<category><![CDATA[Java Basics]]></category>
		<category><![CDATA[IntelliJ IDEA]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://jasta.io/?p=2872</guid>

					<description><![CDATA[Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into writing to files in Java, providing a step-by-step guide to help you accomplish this on your computer. Whether you’re a seasoned tech guru or just starting your digital journey, our straightforward instructions will make the process a breeze. Let’s jump in and start writing to files in Java.</p>



<div class="wp-block-rank-math-toc-block" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#the-importance-of-writing-to-files-in-java">The Importance of Writing to Files in Java</a></li><li><a href="#implement-different-ways-to-write-to-files">Implement Different Ways to Write to Files</a><ul><li><a href="#java-nio-files">Java NIO Files</a></li><li><a href="#buffered-writer-with-file-writer">BufferedWriter with FileWriter</a></li></ul></li></ul></nav></div>



<h2 class="wp-block-heading" id="the-importance-of-writing-to-files-in-java">The Importance of Writing to Files in Java</h2>



<p>In the world of software development, the ability to write data to files in Java plays a vital role in managing and preserving valuable information. This aspect is often considered the counterpart to reading files, as it enables developers to not only access existing data but also store new or modified data for future use.</p>



<p>When we talk about writing files in Java, we&#8217;re essentially talking about the process of saving data to different types of files, be it plain text files, structured data files like CSV or XML, or even binary files. This capability is crucial for a wide range of applications. For instance, in a logging scenario, writing critical events to a log file ensures that important information is recorded for debugging or auditing purposes.</p>



<p>Moreover, writing to files in Java facilitates data persistence, ensuring that essential data isn&#8217;t lost between application sessions. This is particularly crucial for applications that require user preferences or settings to be saved, allowing users to seamlessly resume their activities without losing their custom configurations.</p>



<p>Beyond basic data storage, Java&#8217;s file writing capabilities extend to creating structured outputs in formats suitable for sharing and collaboration. For example, generating reports in PDF or Excel formats allows users to analyze and share data insights efficiently. This ability to produce structured outputs enhances the usability and versatility of Java-powered applications across various domains.</p>



<p>Mastering the art of writing to files in Java empowers developers to design robust and efficient software solutions that not only capture and retain crucial data but also unleash the full potential of their applications to deliver impactful insights and drive innovation.</p>



<h2 class="wp-block-heading" id="implement-different-ways-to-write-to-files">Implement Different Ways to Write to Files</h2>



<p>For reading files in Java there are two different approaches. One uses Java.io which is available since version 1.1 and the other uses a method of Java.nio which was introduced with version  1.7.</p>



<h3 class="wp-block-heading" id="java-nio-files">Java NIO Files</h3>



<p>The more modern and easy solution for writing to files in Java is Java.nio.Files. With that, you can call the static method write from Files with a Path parameter, the content as a byte array and OpenOptions. Via the OpenOptions you can decide what should happen if the file already exists/not exists. There are many different options like Create, Create_New and Append. You can find all the options with a description <a href="https://docs.oracle.com/javase/8/docs/api/java/nio/file/StandardOpenOption.html" target="_blank" rel="noopener">here</a>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  public static void writeToFile(String path, String content) {
    try {
      Files.write(Path.of(path), content.getBytes(), StandardOpenOption.CREATE);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }</pre>



<h3 class="wp-block-heading" id="buffered-writer-with-file-writer">BufferedWriter with FileWriter</h3>



<p>The more traditional and sometimes necessary way with a Java version below 1.7 is with a BufferedWriter and a FileWriter. After initializing the BufferedWriter with the FileWriter the write method of the BufferedWriter has to be called with the content as a String. After the method call the BufferedWriter has to be closed via its close method.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  public static void writeToFileBufferedWriter(String path, String content) {
    File fileToWrite = new File(path);
    try {
      boolean fileExists = fileToWrite.exists();
      if (!fileExists) {
        fileExists = fileToWrite.createNewFile();
      }

      if (fileExists &amp;&amp; fileToWrite.isFile() &amp;&amp; fileToWrite.canWrite()) {
        BufferedWriter writer = new BufferedWriter(new FileWriter(fileToWrite));
        writer.write(content);
        writer.close();
      } else {
        throw new RuntimeException(new IOException("The file cannot be accessed!"));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }</pre>



<p>You can also find the whole code on the <a href="https://github.com/jastaio/JavaTutorials/tree/main/FileReaderWriter" target="_blank" rel="noopener">jasta GitHub repository</a>. To also learn how to read files in Java you can click <a href="https://jasta.io/java-basics/reading-files-in-java/">here</a>. If you have any questions or feedback feel free to comment below. </p>
]]></content:encoded>
					
					<wfw:commentRss>https://jasta.io/java-basics/writing-to-files-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Reading Files in Java: Unleash Data Insights Effortless</title>
		<link>https://jasta.io/java-basics/reading-files-in-java/</link>
					<comments>https://jasta.io/java-basics/reading-files-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Jakob]]></dc:creator>
		<pubDate>Fri, 29 Mar 2024 17:29:08 +0000</pubDate>
				<category><![CDATA[Java Basics]]></category>
		<category><![CDATA[IntelliJ IDEA]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://jasta.io/?p=2873</guid>

					<description><![CDATA[Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into reading files in Java, providing a step-by-step guide to help you accomplish this on your computer. Whether you’re a seasoned tech guru or just starting your digital journey, our straightforward instructions will make the process a breeze. Let’s jump in and start reading files in Java.</p>



<div class="wp-block-rank-math-toc-block" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#the-importance-of-reading-files-in-java">The Importance of Reading Files in Java</a></li><li><a href="#implement-different-ways-to-read-files">Implement Different Ways to Read Files</a><ul><li><a href="#java-nio-files">Java NIO Files</a></li><li><a href="#buffered-reader-with-file-reader">BufferedReader with FileReader</a></li></ul></li></ul></nav></div>



<h2 class="wp-block-heading" id="the-importance-of-reading-files-in-java">The Importance of Reading Files in Java</h2>



<p>In the realm of software development, the ability to efficiently read and process data from files is a fundamental skill, and Java equips developers with powerful tools to accomplish this task seamlessly.</p>



<p>Reading files in Java is not merely a technical necessity; it is a gateway to unlocking valuable insights and harnessing the potential of diverse data sources. Whether it&#8217;s parsing configuration files, analyzing log data, or extracting information from structured documents, Java&#8217;s file reading capabilities play a pivotal role in enabling developers to interact with data stored in various formats.</p>



<p>From plain text files to complex binary formats, Java offers versatile mechanisms for accessing and manipulating file contents. Moreover, Java&#8217;s support for popular data interchange formats such as JSON and XML further enhances its utility in modern software development.</p>



<p>JSON and XML, being widely adopted for their simplicity and flexibility in representing structured data, find extensive use in web services, configuration files, and data exchange between different systems. By adeptly reading and processing files in Java, developers can seamlessly integrate these data formats into their applications, thereby facilitating interoperability and enhancing the overall functionality and usability of their software solutions.</p>



<p>In essence, mastering the art of reading files in Java is not merely about manipulating bytes and characters; it&#8217;s about harnessing the potential of data to drive innovation, gain insights, and deliver impactful software solutions.</p>



<h2 class="wp-block-heading" id="implement-different-ways-to-read-files">Implement Different Ways to Read Files</h2>



<p>For reading files in Java there are two different approaches. One uses Java.io which is available since version 1.1 and the other uses a method of Java.nio which was introduced with version  1.7.</p>



<h3 class="wp-block-heading" id="java-nio-files">Java NIO Files</h3>



<p>The more modern and easy solution for reading files in Java is Java.nio.Files. With that, you can call the static method readAllLines from Files with a Path parameter. A Path can be created via toPath on a File object or with Path.of(&lt;FilePathAsString&gt;). Optionally you can add a Charset after the path as well. It returns a list of strings where one entry represents one line in the file.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  public static List&lt;String> readFromFile(String path) {
    File fileToRead = new File(path);

    if (fileToRead.exists() &amp;&amp; fileToRead.isFile() &amp;&amp; fileToRead.canRead()) {
      try {
        return Files.readAllLines(fileToRead.toPath());
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    } else {
      throw new RuntimeException(new IOException("The file cannot be accessed!"));
    }
  }</pre>



<h3 class="wp-block-heading" id="buffered-reader-with-file-reader">BufferedReader with FileReader</h3>



<p>The more traditional and sometimes necessary way with a Java version below 1.7 is with a BufferedReader and a FileReader. After initializing the BufferedReader with the FilleReader the readLine method of the BufferedReader has to be called to get the next line. When the file ends, the method will return null. After the end of the file is reached the BufferedReader has to be closed.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  public static List&lt;String> readFromFileBufferedReader(String path) {
    File fileToRead = new File(path);

    if (fileToRead.exists() &amp;&amp; fileToRead.isFile() &amp;&amp; fileToRead.canRead()) {
      try {
        BufferedReader reader = new BufferedReader(new FileReader(fileToRead));
        String temp;
        List&lt;String> content = new ArrayList&lt;>();

        while ((temp = reader.readLine()) != null) {
          content.add(temp);
        }

        reader.close();

        return content;
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    } else {
      throw new RuntimeException(new IOException("The file cannot be accessed!"));
    }
  }</pre>



<p>You can also find the whole code on the <a href="https://github.com/jastaio/JavaTutorials/tree/main/FileReaderWriter" target="_blank" rel="noopener">jasta GitHub repository</a>. You can also click <a href="https://jasta.io/java-basics/writing-to-files-in-java/">here</a> to learn how to write to files in Java. If you have any questions or feedback feel free to comment below. </p>
]]></content:encoded>
					
					<wfw:commentRss>https://jasta.io/java-basics/reading-files-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Mastering Java Objects: Comprehensive Guide to Constructors, Getters, and Setters</title>
		<link>https://jasta.io/java-basics/mastering-java-objects-a-comprehensive-guide/</link>
					<comments>https://jasta.io/java-basics/mastering-java-objects-a-comprehensive-guide/#respond</comments>
		
		<dc:creator><![CDATA[Jakob]]></dc:creator>
		<pubDate>Sun, 24 Mar 2024 17:16:15 +0000</pubDate>
				<category><![CDATA[Java Basics]]></category>
		<category><![CDATA[IntelliJ IDEA]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://jasta.io/?p=2854</guid>

					<description><![CDATA[Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into how to create and use Java Objects, providing a step-by-step guide to help you accomplish this on your computer. Whether you’re a seasoned tech guru or just starting your digital journey, our straightforward instructions will make the process a breeze. Let’s jump in and start coding with Java Objects.</p>



<div class="wp-block-rank-math-toc-block" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#what-are-java-objects-and-why-do-they-exist">What are Java Objects and Why Do They Exist?</a></li><li><a href="#understanding-the-purpose-of-constructors-in-java">Understanding the Purpose of Constructors in Java</a></li><li><a href="#how-to-create-and-use-java-objects">How to Create and Use Java Objects</a></li></ul></nav></div>



<h2 class="wp-block-heading" id="what-are-java-objects-and-why-do-they-exist">What are Java Objects and Why Do They Exist?</h2>



<p>As you might already know, there are some predefined objects in Java. Examples would be a String which stores some text or an Integer which can store a number. These are already pretty useful but what would you do, if you want to store multiple pieces of information for one thing? An example would be a car. All necessary information cannot be stored inside a String or an Integer. So the best approach is to create a new Object which cannot just store one particular information but many different things.</p>



<p>Regarding the car example some things that should be stored would be:</p>



<ul class="wp-block-list">
<li>Brand</li>



<li>Model</li>



<li>Plate</li>



<li>Color</li>



<li>Seats</li>



<li>Steering wheel</li>
</ul>



<p>Of course, there are many more things, but this is enough for the beginning. Some of the info can be easily stored in a string like the brand or the model whereas others require more details like the seats and steering wheel. This is because seats can come in various configurations for example with heating or without. That is also the case for the steering wheel. Therefore we would also need to create custom Java objects for the seats and the steering wheel.</p>



<h2 class="wp-block-heading" id="understanding-the-purpose-of-constructors-in-java">Understanding the Purpose of Constructors in Java</h2>



<p>Before actually creating your first Java Objects you have to know about constructors. A constructor is called at the very beginning of creating an object. It is called once and then never again. The purpose of it is to set some variables in the object or execute functions that are necessary at the beginning. Variables that are given with the constructor to the Java Object are often:</p>



<ul class="wp-block-list">
<li>Values that must be set before any method call</li>



<li>Values that are already known upon the creation of the object</li>



<li>Values that are used for a method call inside the constructor </li>
</ul>



<p>To get back to the car example a constructor would look like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  public Car(String brand, String model) {
    this.brand = brand;
    this.model = model;
  }</pre>



<p>With that constructor, we are already setting the brand and the model inside the car object since this information is already known on creation. Other information is probably not known when starting with the creation of the car.</p>



<p>Good to know is, if there is no constructor defined in a class it is the same as an empty constructor. But there can also be multiple constructor definitions.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">  public Car(String brand, String model) {
    this.brand = brand;
    this.model = model;
  }  
  
  public Car(String brand, String model, String color) {
    this.brand = brand;
    this.model = model;
    this.color = color;
  }</pre>



<p>In the example above you have two constructors so you can create an object with these options depending on if you already know the color. In the code a new car object can now be created via &#8216;new Car(&#8220;Audi&#8221;, &#8220;A4&#8221;);&#8217; or &#8216;new Car(&#8220;Audi&#8221;, &#8220;A4&#8221;, &#8220;Green&#8221;);&#8217;.</p>



<p>The difference between a constructor and a setter method is, that a constructor is once called when creating an object. A setter method can be but must not be called after initializing the object and can also be called multiple times with different values.</p>



<h2 class="wp-block-heading" id="how-to-create-and-use-java-objects">How to Create and Use Java Objects</h2>



<p>Now let&#8217;s implement the car example with Java Objects. The complete code can be found and cloned from the <a href="https://github.com/jastaio/JavaTutorials/tree/main/CarProduction" target="_blank" rel="noopener">jasta GitHub repository</a>. To begin with we have to create our objects by creating new classes. If you don&#8217;t know how to create classes in IntelliJ IDEA click <a href="https://jasta.io/java-basics/create-your-first-java-program-with-ease/">here</a>. We need to create the following classes: Car, Seat, Steeringwheel and a Main class to test the Java Objects. After creating all classes your project structure looks like the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="337" height="335" src="https://jasta.io/wp-content/uploads/2024/03/JavaObjects.webp" alt="Java Objects Car example IntelliJ IDEA" class="wp-image-2864" srcset="https://jasta.io/wp-content/uploads/2024/03/JavaObjects.webp 337w, https://jasta.io/wp-content/uploads/2024/03/JavaObjects-300x298.webp 300w, https://jasta.io/wp-content/uploads/2024/03/JavaObjects-150x150.webp 150w, https://jasta.io/wp-content/uploads/2024/03/JavaObjects-148x148.webp 148w" sizes="auto, (max-width: 337px) 100vw, 337px" /></figure>
</div>


<p>First of all, we are adding code to the seat class. We are adding three variables to the class: material, weight and heating. Since we will probably know all of these when creating the seat we are setting all of them inside the constructor. Also, these attributes will not change, therefore they have the final keyword in front of the declaration so they can not be modified later on. To get the values of the variables we are also adding get methods.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public class Seat {

  private final String material;
  private final int weight;
  private final boolean heating;

  public Seat(String material, int weight, boolean heating) {
    this.material = material;
    this.weight = weight;
    this.heating = heating;
  }

  public String getMaterial() {
    return material;
  }

  public int getWeight() {
    return weight;
  }

  public boolean isHeating() {
    return heating;
  }
}</pre>



<p>The second class which will be implemented is the Steeringwheel class. For simplicity, we are just adding two variables: material and diameter. These will be known on creation and should not be changed later. Therefore the final keyword is added again and the values are assigned inside the constructor. In addition, of course, getter methods are added.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public class Steeringwheel {

  private final String material;
  private final int diameter;

  public Steeringwheel(String material, int diameter) {
    this.material = material;
    this.diameter = diameter;
  }

  public String getMaterial() {
    return material;
  }

  public int getDiameter() {
    return diameter;
  }
}</pre>



<p>Now that all Java Objects used for the car object are created, we can implement the car class. As previously described a car will have multiple seats therefore a list of seats, a String brand, a String model, a Steeringwheel object, a String plate and a String with the car&#8217;s color. The list type, the brand and the model shouldn&#8217;t be modified after initialization therefore they are declared final. Since the list type is already declared at the variable declaration only the brand and the model need to be set in the constructor. Every other attribute can be set via the corresponding set method. Of course getter methods are added as well.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import java.util.ArrayList;
import java.util.List;

public class Car {

  private final List&lt;Seat> seats = new ArrayList&lt;>();
  private final String brand;
  private final String model;
  private Steeringwheel steeringwheel;
  private String plate;
  private String color;

  public Car(String brand, String model) {
    this.brand = brand;
    this.model = model;
  }

  public List&lt;Seat> getSeats() {
    return seats;
  }

  public void addSeat(Seat seat) {
    seats.add(seat);
  }

  public String getBrand() {
    return brand;
  }

  public String getModel() {
    return model;
  }

  public Steeringwheel getSteeringwheel() {
    return steeringwheel;
  }

  public void setSteeringwheel(Steeringwheel steeringwheel) {
    this.steeringwheel = steeringwheel;
  }

  public String getPlate() {
    return plate;
  }

  public void setPlate(String plate) {
    this.plate = plate;
  }

  public String getColor() {
    return color;
  }

  public void setColor(String color) {
    this.color = color;
  }
}</pre>



<p>To test and understand how all this works, you can copy the code from below into your main class and execute it.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public class Main {

  public static void main(String[] args) {
    Car audiA4 = new Car("Audi", "A4");

    audiA4.setColor("green");

    Steeringwheel steeringwheel = new Steeringwheel("Leather", 38);
    audiA4.setSteeringwheel(steeringwheel);

    audiA4.addSeat(new Seat("Leather", 10, true));
    audiA4.addSeat(new Seat("Leather", 10, true));
    audiA4.addSeat(new Seat("Fabric", 8, false));
    audiA4.addSeat(new Seat("Fabric", 8, false));
    audiA4.addSeat(new Seat("Fabric", 8, false));

    audiA4.setPlate("ABCD1");

    System.out.println(
        "Car: " + audiA4.getBrand() + " " + audiA4.getModel() + " in " + audiA4.getColor());
    System.out.println(
        "Steeringwheel: " + audiA4.getSteeringwheel().getMaterial() + " steeringwheel which is "
            + audiA4.getSteeringwheel().getDiameter() + "cm big");

    int count = 1;
    String tempSeatOutput;
    for (Seat seat : audiA4.getSeats()) {
      tempSeatOutput =
          "Seat " + count + ": " + seat.getMaterial() + " seat which weights " + seat.getWeight()
              + "kg";

      if (seat.isHeating()) {
        tempSeatOutput += " and can heat up";
      } else {
        tempSeatOutput += " and cannot heat up";
      }

      System.out.println(tempSeatOutput);
      count++;
    }

    System.out.println("Plate: " + audiA4.getPlate());
  }
}</pre>



<p>The code above creates a new object with Car audiA4 = new Car(&#8220;Audi&#8221;, &#8220;A4&#8221;);. &#8216;Audi&#8217; and &#8216;A4&#8217; are the constructor arguments (brand and model). After creation, we are now using the setter methods of the car objects to set other variables. </p>



<p>The color is just set with a simple String argument. To set a Steeringwheel object we first have to create one. This is done like the Car object but now with Steeringwheel: Steeringwheel steeringwheel = new Steeringwheel(&#8220;Leather&#8221;, 38);. When creating the Steeringwheel Object the constructor arguments (material and diameter) are added. Now there are two separate objects. One is the Car and the other one is the Steeringwheel Object. To link the Steeringwheel object to the Car object we need to call the setSteeringwheel method of the car. The same process is now done with the seats but with anonymous objects.</p>



<p>Anonymous objects are used if you don&#8217;t need to access the object later on in the code. So you can type new Seat(&lt;material>, &lt;weight>, &lt;heating>) and add it immediately to the car with addSeat. This has two benefits. All this is done within one line and you don&#8217;t have to think about an object name. This can also be done with the Steeringwheel object since it will not be used directly later in the code.</p>



<p>After setting the plate every information about the car is printed out in the console. To do this the respective getter method is called to get the wanted String, Steeringwheel or Seat objects.</p>



<p>That&#8217;s the process of creating and using Java Objects. If you have any questions feel free to leave a comment.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jasta.io/java-basics/mastering-java-objects-a-comprehensive-guide/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Crafting Your First Android App with Java: A Beginner&#8217;s Guide to Success</title>
		<link>https://jasta.io/mobile-apps/crafting-your-first-android-app-with-java/</link>
					<comments>https://jasta.io/mobile-apps/crafting-your-first-android-app-with-java/#respond</comments>
		
		<dc:creator><![CDATA[Jakob]]></dc:creator>
		<pubDate>Sat, 16 Mar 2024 14:51:36 +0000</pubDate>
				<category><![CDATA[Mobile Apps]]></category>
		<category><![CDATA[Android Studio]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Mobile-App]]></category>
		<guid isPermaLink="false">https://jasta.io/?p=2791</guid>

					<description><![CDATA[Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into how to create your first Android app with Java, providing a step-by-step guide to help you accomplish this on your computer. Whether you’re a seasoned tech guru or just starting your digital journey, our straightforward instructions will make the process a breeze. Let’s jump in and create an Android app with Java.</p>



<div class="wp-block-rank-math-toc-block" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#creating-an-android-app-with-java-in-android-studio">Creating an Android App with Java in Android Studio</a></li><li><a href="#extending-the-source-code-of-your-app">Extending the Source Code of Your App</a></li><li><a href="#testing-your-first-android-app-with-java">Testing Your First Android App with Java</a></li></ul></nav></div>



<h2 class="wp-block-heading" id="creating-an-android-app-with-java-in-android-studio">Creating an Android App with Java in Android Studio</h2>



<p>To start, you first need to click on the new project button to start configuring your Android app.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="775" height="632" src="https://jasta.io/wp-content/uploads/2024/03/CreateAndroidStudioProject.webp" alt="Create a new project in Android Studio" class="wp-image-2799" srcset="https://jasta.io/wp-content/uploads/2024/03/CreateAndroidStudioProject.webp 775w, https://jasta.io/wp-content/uploads/2024/03/CreateAndroidStudioProject-300x245.webp 300w, https://jasta.io/wp-content/uploads/2024/03/CreateAndroidStudioProject-768x626.webp 768w, https://jasta.io/wp-content/uploads/2024/03/CreateAndroidStudioProject-512x418.webp 512w" sizes="auto, (max-width: 775px) 100vw, 775px" /></figure>
</div>


<p>On the first page, you need to select what activity you want to use for creating your app. Since we don&#8217;t want any pre-created buttons or menus in this app we are just using the Empty Views Activity. </p>



<p>FYI: An activity is one screen of an app. If you are for example creating an app with a login mechanism you would have the following activities:</p>



<ul class="wp-block-list">
<li>Login Activity</li>



<li>Registration Activity</li>



<li>Home Activity</li>
</ul>



<p>The app would probably start with the login activity. On this activity, you could now have two fields for email and password and two buttons. One for new users which would open the registration activity and one login button which would redirect the user to the home activity. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="890" height="644" src="https://jasta.io/wp-content/uploads/2024/03/CreateAndroidStudioProject2.webp" alt="Empty Views Activity in Android Studio" class="wp-image-2800" srcset="https://jasta.io/wp-content/uploads/2024/03/CreateAndroidStudioProject2.webp 890w, https://jasta.io/wp-content/uploads/2024/03/CreateAndroidStudioProject2-300x217.webp 300w, https://jasta.io/wp-content/uploads/2024/03/CreateAndroidStudioProject2-768x556.webp 768w, https://jasta.io/wp-content/uploads/2024/03/CreateAndroidStudioProject2-512x370.webp 512w" sizes="auto, (max-width: 890px) 100vw, 890px" /></figure>
</div>


<p>After pressing next you will see the actual configuration screen of your project. There you can change various settings for your app. You can enter whatever you like regarding the name and the package name. This applies also to the save location. However, if you change the directory, no new folder will be created with the project name so the project gets generated exactly in the folder you choose. So don&#8217;t choose a parent folder without creating a subfolder.</p>



<p>For the language you should also choose whatever you know the best. For this tutorial, I am choosing Java. The next point is the minimum SDK. This means any device with an Android version below this version won&#8217;t be able to download and use this app. A good minimum SDK is API 24 which is already preselected. Below the drop-down menu, you can also see how many smartphones can use this app. The last configuration option is the build configuration language. You can choose between Kotlin and Groovy and since Kotlin is superior we are choosing it.</p>



<p>After every configuration option is set it should look similar to the screenshot below. If this is the case you can start the generating process of your Android app with Java by clicking Finish.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="897" height="646" src="https://jasta.io/wp-content/uploads/2024/03/CreateAndroidStudioProject3.webp" alt="Project configuration in Android Studio" class="wp-image-2801" srcset="https://jasta.io/wp-content/uploads/2024/03/CreateAndroidStudioProject3.webp 897w, https://jasta.io/wp-content/uploads/2024/03/CreateAndroidStudioProject3-300x216.webp 300w, https://jasta.io/wp-content/uploads/2024/03/CreateAndroidStudioProject3-768x553.webp 768w, https://jasta.io/wp-content/uploads/2024/03/CreateAndroidStudioProject3-512x369.webp 512w" sizes="auto, (max-width: 897px) 100vw, 897px" /></figure>
</div>


<p>After your project is generated you should locate two important files in the project explorer on the left of the screen. The MainActivity class contains all the programming logic for our activity. The activity_main.xml file contains the information on how your MainActivity will look like.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="448" height="416" src="https://jasta.io/wp-content/uploads/2024/03/AppExplorer.webp" alt="Project explorer inside Android Studio" class="wp-image-2803" srcset="https://jasta.io/wp-content/uploads/2024/03/AppExplorer.webp 448w, https://jasta.io/wp-content/uploads/2024/03/AppExplorer-300x279.webp 300w" sizes="auto, (max-width: 448px) 100vw, 448px" /></figure>
</div>


<p>When opening the activity_main.xml you will probably see a white screen with a Hello World! text since this is the default option. But there is also an option to see the code of the actual file side by side with the live preview of it which is mandatory for developing an app. To switch to this view click on the symbol in the top right corner highlighted in the screenshot below. You can also see another highlighted button. With that, you can switch from seeing a blueprint beneath the actual preview of the activity to just previewing the activity. For that, you have to switch to Design only.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="834" src="https://jasta.io/wp-content/uploads/2024/03/layoutPreviewSettingsAndroidStudio-1024x834.webp" alt="See code and preview side by side in Android Studio" class="wp-image-2804" srcset="https://jasta.io/wp-content/uploads/2024/03/layoutPreviewSettingsAndroidStudio-1024x834.webp 1024w, https://jasta.io/wp-content/uploads/2024/03/layoutPreviewSettingsAndroidStudio-300x244.webp 300w, https://jasta.io/wp-content/uploads/2024/03/layoutPreviewSettingsAndroidStudio-768x626.webp 768w, https://jasta.io/wp-content/uploads/2024/03/layoutPreviewSettingsAndroidStudio-512x417.webp 512w, https://jasta.io/wp-content/uploads/2024/03/layoutPreviewSettingsAndroidStudio-920x749.webp 920w, https://jasta.io/wp-content/uploads/2024/03/layoutPreviewSettingsAndroidStudio.webp 1295w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h2 class="wp-block-heading" id="extending-the-source-code-of-your-app">Extending the Source Code of Your App</h2>



<p>Now that you know the basics we are extending the source code of your Android app with Java a bit so there will be a Button that can be pressed which increases a counter that is displayed in a TextView. For this, we are giving the already existing TextView in the activity_main.xml an ID. An ID is needed so we can access the TextView via the logic inside the MainActivity Java class. To add an ID you need to add the line below inside the TextView tag.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">android:id="@+id/counterLabel"</pre>



<p>After adding this line we are also adding a Button to the activity with this code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    &lt;Button
        android:id="@+id/countUpButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Count up"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/counterLabel" /></pre>



<p>Now our activity_main.xml is done and should look like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?xml version="1.0" encoding="utf-8"?>
&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    &lt;TextView
        android:id="@+id/counterLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    &lt;Button
        android:id="@+id/countUpButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Count up"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/counterLabel" />

&lt;/androidx.constraintlayout.widget.ConstraintLayout></pre>



<p>The user interface is now done. There is a Button and a TextView. Now we need to access these two components inside the MainActivity.java and work with them.<br>First of all, we are adding 3 variables to the class.</p>



<ul class="wp-block-list">
<li>private TextView counterLabel; This will be set to our TextView</li>



<li>private Button counterButton; This will be set to our Button</li>



<li>private int currentCount = 0; This will work as our counter variable</li>
</ul>



<p>Then we initialize the TextView and Button variables. This can be done in the onCreate method since this method is only once called at the very start of the activity. To get different components of your XML files you call findViewById(R.id.&lt;IDInsideXMLFile&gt;). So the assignments will look like this.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">counterLabel = findViewById(R.id.counterLabel);
counterButton = findViewById(R.id.countUpButton);</pre>



<p>The next step is to set the text of the counter label to 0. For setting an initial value there are always two options. The first one is to set it directly inside the activity_main.xml file with the android:text attribute or you can do it via code like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">counterLabel.setText(String.valueOf(currentCount));</pre>



<p>Last, we need to add an onClickListener with which we can override the onClick method to increase our counter and set the new value to our TextView. To do this you can either use a lambda expression or not. That depends entirely on what you prefer to use. You can see the difference below:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">counterButton.setOnClickListener(v -> {
    currentCount++;
    counterLabel.setText(String.valueOf(currentCount));
});

counterButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        currentCount++;
        counterLabel.setText(String.valueOf(currentCount));
    }
});</pre>



<p>Finally, your finished MainActivity class will look like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.example.myfirstandroidapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView counterLabel;
    private Button counterButton;
    private int currentCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        counterLabel = findViewById(R.id.counterLabel);
        counterButton = findViewById(R.id.countUpButton);

        counterLabel.setText(String.valueOf(currentCount));

        counterButton.setOnClickListener((v) -> {
            currentCount++;
            counterLabel.setText(String.valueOf(currentCount));
        });
    }
}</pre>



<p>Always call findViewById after super.onCreate(savedInstanceState); and setContentView(R.layout.activity_main);. Otherwise, it will not work.</p>



<h2 class="wp-block-heading" id="testing-your-first-android-app-with-java">Testing Your First Android App with Java</h2>



<p>To test your newly created Android app with Java you have two options. <br>The first one is to use your real mobile phone. You can either connect it via cable or connect via Wi-Fi. To do this you first need to enable the respective debugging mode on your smartphone in the developer settings. This can vary from brand to brand so the best thing is to Google how to do it on your device. After enabling the mode you can connect your device via cable and the smartphone will automatically show up on the devices list, or you use &#8216;Pair Devices Using Wi-Fi&#8217; from the options in the screenshot below and follow the steps displayed.</p>



<p>The second option to test your Android app with Java is, to use a virtual device. The advantage of a virtual device is, that you can have multiple. So you can test your app on devices with different sizes and Android versions. Furthermore, you can test device categories that you may not even own, like a smartwatch. To learn how to add a virtual device you can click <a href="https://jasta.io/how-tos/add-a-powerful-virtual-device-in-android-studio/">here</a>.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="382" height="224" src="https://jasta.io/wp-content/uploads/2024/03/AndroidStudioTestApp.webp" alt="Available devices in Android Studio" class="wp-image-2796" srcset="https://jasta.io/wp-content/uploads/2024/03/AndroidStudioTestApp.webp 382w, https://jasta.io/wp-content/uploads/2024/03/AndroidStudioTestApp-300x176.webp 300w" sizes="auto, (max-width: 382px) 100vw, 382px" /></figure>
</div>


<p>After you have added/selected the correct device you can now click on the play button next to the drop-down list, which is also highlighted in the screenshot below to start your app.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="578" src="https://jasta.io/wp-content/uploads/2024/03/StartAndroidApp-1-1024x578.webp" alt="Run you app in Android Studio" class="wp-image-2807" srcset="https://jasta.io/wp-content/uploads/2024/03/StartAndroidApp-1-1024x578.webp 1024w, https://jasta.io/wp-content/uploads/2024/03/StartAndroidApp-1-300x169.webp 300w, https://jasta.io/wp-content/uploads/2024/03/StartAndroidApp-1-768x433.webp 768w, https://jasta.io/wp-content/uploads/2024/03/StartAndroidApp-1-1536x867.webp 1536w, https://jasta.io/wp-content/uploads/2024/03/StartAndroidApp-1-2048x1156.webp 2048w, https://jasta.io/wp-content/uploads/2024/03/StartAndroidApp-1-512x289.webp 512w, https://jasta.io/wp-content/uploads/2024/03/StartAndroidApp-1-920x519.webp 920w, https://jasta.io/wp-content/uploads/2024/03/StartAndroidApp-1-1600x903.webp 1600w, https://jasta.io/wp-content/uploads/2024/03/StartAndroidApp-1-1920x1084.webp 1920w, https://jasta.io/wp-content/uploads/2024/03/StartAndroidApp-1.webp 2151w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<p>After clicking the button the app will be built. When the build process is finished the virtual device will start and launch your app. If you use your personal device the app will also launch itself. After the application is started on your device it should look like the preview from the activity_main.xml file. To test the logic we implemented you can click on the counter button. You will then see the counter getting increased with each click. </p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="669" height="744" src="https://jasta.io/wp-content/uploads/2024/03/FinishedApp-1.webp" alt="Android app with Java in Android Studio" class="wp-image-2808" srcset="https://jasta.io/wp-content/uploads/2024/03/FinishedApp-1.webp 669w, https://jasta.io/wp-content/uploads/2024/03/FinishedApp-1-270x300.webp 270w, https://jasta.io/wp-content/uploads/2024/03/FinishedApp-1-512x569.webp 512w" sizes="auto, (max-width: 669px) 100vw, 669px" /></figure>
</div>


<p>This was the process of creating your first Android app with Java in Android Studio. If you have any problems or questions feel free to comment below. To read more about creating an app in Android Studio you can visit the <a href="https://developer.android.com/codelabs/build-your-first-android-app#0" target="_blank" rel="noopener">documentation of Google</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jasta.io/mobile-apps/crafting-your-first-android-app-with-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Create a powerful Java Web Application with Spring</title>
		<link>https://jasta.io/web-development/create-a-java-web-application-with-spring/</link>
					<comments>https://jasta.io/web-development/create-a-java-web-application-with-spring/#respond</comments>
		
		<dc:creator><![CDATA[Jakob]]></dc:creator>
		<pubDate>Sat, 24 Feb 2024 10:54:32 +0000</pubDate>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[IntelliJ IDEA]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Web App]]></category>
		<guid isPermaLink="false">https://jasta.io/?p=2668</guid>

					<description><![CDATA[Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into how to create a powerful Java Web Application with Spring, providing a step-by-step guide to help you accomplish this on your computer. Whether you’re a seasoned tech guru or just starting your digital journey, our straightforward instructions will make the process a breeze. Let’s jump in and create a powerful Java Application with Spring.</p>



<div class="wp-block-rank-math-toc-block" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#create-your-project-with-spring-initializr">Create your Project with Spring Initializr</a></li><li><a href="#import-your-java-web-application-with-spring-into-intelli-j-idea">Import your Java Web Application with Spring into IntelliJ IDEA</a><ul><li><a href="#open-a-project-from-the-starting-screen">Open a Project from the starting screen</a></li><li><a href="#open-a-project-inside-intelli-j-idea">Open a Project inside IntelliJ IDEA</a></li></ul></li><li><a href="#adding-rest-methods-to-your-java-web-application-with-spring">Adding REST Methods to your Java Web Application with Spring</a></li><li><a href="#try-out-your-java-web-application">Try out your Java Web Application</a></li></ul></nav></div>



<h2 class="wp-block-heading" id="create-your-project-with-spring-initializr">Create your Project with Spring Initializr</h2>



<p>To create a Java web application with Spring you first have to create the project via the <a href="https://start.spring.io/" target="_blank" rel="noopener">Spring Initializr</a>. There you have a quit similar screen to the IntelliJ IDEA project creation window. </p>



<p>First you have to set the build tool with a corresponding language. As in the Java tutorials you should pick Gradle with Kotlin, since Gradle and Kotlin are supiror to Maven and Groovy. After choosing the build tool you have to choose the language for the Project, which in this case is Java. Below you can select the wanted Spring Boot version. It is recommended to just use the most revent final version which in this case is 3.2.3.</p>



<p>After setting the build tool, language and Spring Boot version you now have to enter some information about your Java web application with Spring. You can change these as you like, but you can also just leave all the prefilled values or just give the project another name.</p>



<p>Below these settings you can set the packaging and Java version. For the packaging I would recommend to just use the already selected option, Jar. For the Java version it is the best to pick the newest one. In this case this is 21.</p>



<p>On the right side of the Spring Initializr you can see the dependencies for the project. Because we are later adding some REST methods, we are going to add a certain dependency. For that you have to click on ADD DEPENDENCIES or press CTRL + B to open the dependencies window. There you have to select &#8216;Spring Web&#8217; which is also marked in the screenshot below.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" width="759" height="1024" src="https://jasta.io/wp-content/uploads/2024/02/SpringDependencies-759x1024.webp" alt="Spring Initializr dependencies" class="wp-image-2692" style="width:644px" srcset="https://jasta.io/wp-content/uploads/2024/02/SpringDependencies-759x1024.webp 759w, https://jasta.io/wp-content/uploads/2024/02/SpringDependencies-222x300.webp 222w, https://jasta.io/wp-content/uploads/2024/02/SpringDependencies-768x1036.webp 768w, https://jasta.io/wp-content/uploads/2024/02/SpringDependencies-512x691.webp 512w, https://jasta.io/wp-content/uploads/2024/02/SpringDependencies.webp 800w" sizes="auto, (max-width: 759px) 100vw, 759px" /></figure>
</div>


<p>Now after filling out all necessary information to create the Java web application with Spring, your Screen should look similar to the screenshot below. If this is the case, you can now click on GENERATE button on the bottom or start generating with CTRL + ENTER to generate the project and download it automatically.</p>


<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="748" src="https://jasta.io/wp-content/uploads/2024/02/SpringInitializrAllSettings-1024x748.webp" alt="Java Web Application with Spring" class="wp-image-2691" srcset="https://jasta.io/wp-content/uploads/2024/02/SpringInitializrAllSettings-1024x748.webp 1024w, https://jasta.io/wp-content/uploads/2024/02/SpringInitializrAllSettings-300x219.webp 300w, https://jasta.io/wp-content/uploads/2024/02/SpringInitializrAllSettings-768x561.webp 768w, https://jasta.io/wp-content/uploads/2024/02/SpringInitializrAllSettings-1536x1123.webp 1536w, https://jasta.io/wp-content/uploads/2024/02/SpringInitializrAllSettings-512x374.webp 512w, https://jasta.io/wp-content/uploads/2024/02/SpringInitializrAllSettings-920x672.webp 920w, https://jasta.io/wp-content/uploads/2024/02/SpringInitializrAllSettings.webp 1587w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>
</div>


<h2 class="wp-block-heading" id="import-your-java-web-application-with-spring-into-intelli-j-idea">Import your Java Web Application with Spring into IntelliJ IDEA</h2>



<p>After generating and downloading your project, you now have a zip file inside your Downloads folder. If this is the case, you should now relocate the zip file to a folder where you want to locate the project and unzip it there. After unzipping it, you can now open IntelliJ IDEA.</p>



<p>There are two different methods to open your Java Web application with Spring depending if you have already opened a project or not.</p>



<h3 class="wp-block-heading" id="open-a-project-from-the-starting-screen">Open a Project from the starting screen</h3>



<p>If you currently don&#8217;t have an open project inside IntelliJ you should see the following screen when starting the program up.  If this is the case, you have to click on open and find your project. Inside your project folder you have to select your build.gradle.kts file and click on the OK button.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="778" height="636" src="https://jasta.io/wp-content/uploads/2024/02/OpenProjectIntelliJ.webp" alt="Open project" class="wp-image-2681" style="width:644px" srcset="https://jasta.io/wp-content/uploads/2024/02/OpenProjectIntelliJ.webp 778w, https://jasta.io/wp-content/uploads/2024/02/OpenProjectIntelliJ-300x245.webp 300w, https://jasta.io/wp-content/uploads/2024/02/OpenProjectIntelliJ-768x628.webp 768w, https://jasta.io/wp-content/uploads/2024/02/OpenProjectIntelliJ-512x419.webp 512w" sizes="auto, (max-width: 778px) 100vw, 778px" /></figure>
</div>

<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="417" height="485" src="https://jasta.io/wp-content/uploads/2024/02/OpenProjectIntelliJBuildGradle.webp" alt="Select build.gradle" class="wp-image-2682" style="width:344px" srcset="https://jasta.io/wp-content/uploads/2024/02/OpenProjectIntelliJBuildGradle.webp 417w, https://jasta.io/wp-content/uploads/2024/02/OpenProjectIntelliJBuildGradle-258x300.webp 258w" sizes="auto, (max-width: 417px) 100vw, 417px" /></figure>
</div>


<p>After clicking on OK you will see the dialog from the screenshot below on your screen, because IntelliJ is understanding that the build.gradle.kts file belongs to a project and now asks you if you want to open the whole project or just the file. So you have to click on Open as Project.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="480" height="138" src="https://jasta.io/wp-content/uploads/2024/02/OpenAsProjectIntelliJ.webp" alt="Open as Project" class="wp-image-2683" srcset="https://jasta.io/wp-content/uploads/2024/02/OpenAsProjectIntelliJ.webp 480w, https://jasta.io/wp-content/uploads/2024/02/OpenAsProjectIntelliJ-300x86.webp 300w" sizes="auto, (max-width: 480px) 100vw, 480px" /></figure>
</div>


<h3 class="wp-block-heading" id="open-a-project-inside-intelli-j-idea">Open a Project inside IntelliJ IDEA</h3>



<p>If you have already opened a Project in IntelliJ you firstly have to click on File on the top navigation bar, select new and then click on &#8216;Project from Existing Sources&#8230;&#8217;. You then have to find your unzipped project and select the build.gradle.kts file inside the project folder.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="643" height="578" src="https://jasta.io/wp-content/uploads/2024/02/ProjectFromExistingSourceIntellij.webp" alt="Project from Existing Sources inside IntelliJ" class="wp-image-2684" style="width:644px" srcset="https://jasta.io/wp-content/uploads/2024/02/ProjectFromExistingSourceIntellij.webp 643w, https://jasta.io/wp-content/uploads/2024/02/ProjectFromExistingSourceIntellij-300x270.webp 300w, https://jasta.io/wp-content/uploads/2024/02/ProjectFromExistingSourceIntellij-512x460.webp 512w" sizes="auto, (max-width: 643px) 100vw, 643px" /></figure>
</div>

<div class="wp-block-image">
<figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" width="422" height="570" src="https://jasta.io/wp-content/uploads/2024/02/ProjectFromExistingSourceIntelliJBuildGradle.webp" alt="Selecting project file (build.gradle)" class="wp-image-2685" style="width:344px" srcset="https://jasta.io/wp-content/uploads/2024/02/ProjectFromExistingSourceIntelliJBuildGradle.webp 422w, https://jasta.io/wp-content/uploads/2024/02/ProjectFromExistingSourceIntelliJBuildGradle-222x300.webp 222w" sizes="auto, (max-width: 422px) 100vw, 422px" /></figure>
</div>


<p>Wheter you have already opened a Project or not you will probably see the warning message from the screenshot below on your computer. Since you created that project by yourself on an official website of Spring you can just select Trust Project. If you don&#8217;t want to see such warning messages in the future again you can also set the checkbox above the buttons to trust the whole parent folder of the just opened project.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="509" height="222" src="https://jasta.io/wp-content/uploads/2024/02/IntelliJTrustProject.webp" alt="IntelliJ trust project" class="wp-image-2686" srcset="https://jasta.io/wp-content/uploads/2024/02/IntelliJTrustProject.webp 509w, https://jasta.io/wp-content/uploads/2024/02/IntelliJTrustProject-300x131.webp 300w" sizes="auto, (max-width: 509px) 100vw, 509px" /></figure>
</div>


<p>After all those steps your project structure on the left looks like that.</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="397" height="491" src="https://jasta.io/wp-content/uploads/2024/02/ImportedSpringProject.webp" alt="Final Project structure" class="wp-image-2688" srcset="https://jasta.io/wp-content/uploads/2024/02/ImportedSpringProject.webp 397w, https://jasta.io/wp-content/uploads/2024/02/ImportedSpringProject-243x300.webp 243w" sizes="auto, (max-width: 397px) 100vw, 397px" /></figure>
</div>


<h2 class="wp-block-heading" id="adding-rest-methods-to-your-java-web-application-with-spring">Adding REST Methods to your Java Web Application with Spring</h2>



<p>Since your just imported demo project will do nothing, we are going to add two REST Methods to your project and try them out later on. </p>



<p>First of all you have to add a new class inside your project. How to do that is already covered in <a href="https://jasta.io/java-basics/create-your-first-java-program-with-ease/">this</a> article. You can choose whatever name you like. For this example, I am naming it &#8216;DemoController&#8217;. To tell the Java web application with Spring that this class will carry REST methods, you have to add the @RestController annotation like below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.example.demo;

import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
}</pre>



<p>Now we are going to add two different REST methods to your DemoController. The first method is to just greet you. This can be done with the following code.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {
    
    @GetMapping("/greet/{name}")
    public String greetMe(@PathVariable String name) {
        return "Hello " + name + "!";
    }
}</pre>



<p>The @GetMapping annotation tells the program that this is a GET method and can be accessed when you add /greet to your web address. With the {name} inside the @GetMapping the program knows, that it should use everything after the /greet/ as the method parameter which is annotated with @PathVariable. It is important, that the method parameter and the variable name inside the curly brackets are the same.</p>



<p>The second method we are going to add will sum up two numbers. This is archived with adding the sumOfTwoNumbers method like below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.example.demo;

import org.springframework.web.bind.annotation.*;

@RestController
public class DemoController {

    @GetMapping("/greet/{name}")
    public String greetMe(@PathVariable String name) {
        return "Hello " + name + "!";
    }

    @GetMapping("/sum")
    public String sumOfTwoNumbers(@RequestParam("num1") int number1, @RequestParam("num2") int number2) {
        return "Sum: " + (number1 + number2);
    }
}</pre>



<p>As above the @GetMapping is telling us where to find the method. But now we don&#8217;t want to use PathVariables like in the greetMe method but rather use @RequestParam instead so the parameters are now not getting filled with the value behind /sum/. Instead of that we are now interested in parameters like the following: /sum?num1=5&amp;num2=10 .</p>



<h2 class="wp-block-heading" id="try-out-your-java-web-application">Try out your Java Web Application</h2>



<p>To try out your just-added REST methods, you have to go back to the DemoApplication class and click on the play button next to your code. You should then see the bootup process in your build output window at the bottom. After you see Completed initialization in the build window you can test your methods.</p>



<p>To test the greet method you simply have to open your browser and type http://localhost:8080/ to get to your web application and then add /greet/&lt;YourName&gt; to it so your address bar should look like this: http://localhost:8080/greet/&lt;YourName&gt;. If you then hit enter you see &#8216;Hello &lt;YourName&gt;!&#8217;.</p>



<p>If that was working fine, you can now try the second method. For that you have to remove the /greet/&lt;YourName&gt; part of the url so you just have http://localhost:8080/ again and then add /sum with two request parameters named num1 and num2. So the final request should look like this: http://localhost:8080/sum?num1=&lt;Number1&gt;&amp;num2=&lt;Number2&gt;. After clicking enter again you can now see the sum of the two numbers you entered.</p>



<p>Assuming everything is working fine, you have successfully created a Java web application with Spring. If you have any troubles feel free to leave a comment.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jasta.io/web-development/create-a-java-web-application-with-spring/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Getting Started: Create Your First Java Program with Ease</title>
		<link>https://jasta.io/java-basics/create-your-first-java-program-with-ease/</link>
					<comments>https://jasta.io/java-basics/create-your-first-java-program-with-ease/#respond</comments>
		
		<dc:creator><![CDATA[Jakob]]></dc:creator>
		<pubDate>Sun, 18 Feb 2024 16:29:45 +0000</pubDate>
				<category><![CDATA[Java Basics]]></category>
		<category><![CDATA[IntelliJ IDEA]]></category>
		<category><![CDATA[Java]]></category>
		<guid isPermaLink="false">https://jasta.io/?p=2630</guid>

					<description><![CDATA[Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Hello tech enthusiasts! Welcome back to jasta, your go-to destination for all things tech. Today, we’re diving into how to create your first Java program with ease, providing a step-by-step guide to help you accomplish this on your computer. Whether you’re a seasoned tech guru or just starting your digital journey, our straightforward instructions will make the process a breeze. Let’s jump in and create your first Java program.</p>



<div class="wp-block-rank-math-toc-block" id="rank-math-toc"><h2>Table of Contents</h2><nav><ul><li><a href="#create-your-first-java-program">Create your first Java program</a></li><li><a href="#start-your-program">Start your program</a></li><li><a href="#modify-the-source-code-of-your-first-java-program">Modify the source code of your first Java program</a></li></ul></nav></div>



<h2 class="wp-block-heading" id="create-your-first-java-program">Create your first Java program</h2>



<p>To create your first Java program you have to start IntelliJ IDEA. If you don&#8217;t already have installed IntelliJ you can follow <a href="https://jasta.io/how-tos/set-up-a-powerful-java-development-environment/">this</a> guide to do so. After the program is started, your screen should look like the screenshot below. There you can click on new Project to create your first Java program.</p>


<div class="wp-block-image">
<figure data-wp-context="{&quot;imageId&quot;:&quot;69656c89bde1e&quot;}" data-wp-interactive="core/image" data-wp-key="69656c89bde1e" class="aligncenter size-full is-resized wp-lightbox-container"><img loading="lazy" decoding="async" width="775" height="638" data-wp-class--hide="state.isContentHidden" data-wp-class--show="state.isContentVisible" data-wp-init="callbacks.setButtonStyles" data-wp-on--click="actions.showLightbox" data-wp-on--load="callbacks.setButtonStyles" data-wp-on-window--resize="callbacks.setButtonStyles" src="https://jasta.io/wp-content/uploads/2024/02/JavProject.webp" alt="Create Your First Java Program" class="wp-image-2641" style="width:644px" srcset="https://jasta.io/wp-content/uploads/2024/02/JavProject.webp 775w, https://jasta.io/wp-content/uploads/2024/02/JavProject-300x247.webp 300w, https://jasta.io/wp-content/uploads/2024/02/JavProject-768x632.webp 768w, https://jasta.io/wp-content/uploads/2024/02/JavProject-512x421.webp 512w" sizes="auto, (max-width: 775px) 100vw, 775px" /><button
			class="lightbox-trigger"
			type="button"
			aria-haspopup="dialog"
			aria-label="Enlarge"
			data-wp-init="callbacks.initTriggerButton"
			data-wp-on--click="actions.showLightbox"
			data-wp-style--right="state.imageButtonRight"
			data-wp-style--top="state.imageButtonTop"
		>
			<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="none" viewBox="0 0 12 12">
				<path fill="#fff" d="M2 0a2 2 0 0 0-2 2v2h1.5V2a.5.5 0 0 1 .5-.5h2V0H2Zm2 10.5H2a.5.5 0 0 1-.5-.5V8H0v2a2 2 0 0 0 2 2h2v-1.5ZM8 12v-1.5h2a.5.5 0 0 0 .5-.5V8H12v2a2 2 0 0 1-2 2H8Zm2-12a2 2 0 0 1 2 2v2h-1.5V2a.5.5 0 0 0-.5-.5H8V0h2Z" />
			</svg>
		</button></figure>
</div>


<p>Now you will see the project configuration screen. In the middle of this window, you will see the section JDK with a drop-down list. If you have never programmed Java before, the text &#8220;&lt;No SDK&gt;&#8221; will be selected in the menu. To add a SDK you can simply open the drop-down and click Download JDK. In the following windows, you should select the newest available LTS version. LTS stands for Long-Term-Support. To find the newest LTS Java version, you can visit the official <a href="https://www.oracle.com/java/technologies/java-se-support-roadmap.html" target="_blank" rel="noopener">Oracle Java SE Support Roadmap</a> website. In this case, the newest version is 21.</p>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow"><div class="wp-block-image">
<figure data-wp-context="{&quot;imageId&quot;:&quot;69656c89be52e&quot;}" data-wp-interactive="core/image" data-wp-key="69656c89be52e" class="aligncenter size-full is-resized wp-lightbox-container"><img loading="lazy" decoding="async" width="891" height="696" data-wp-class--hide="state.isContentHidden" data-wp-class--show="state.isContentVisible" data-wp-init="callbacks.setButtonStyles" data-wp-on--click="actions.showLightbox" data-wp-on--load="callbacks.setButtonStyles" data-wp-on-window--resize="callbacks.setButtonStyles" src="https://jasta.io/wp-content/uploads/2024/02/JavaProjectNoJDK2-1.webp" alt="Download JDK" class="wp-image-2644" style="width:644px" srcset="https://jasta.io/wp-content/uploads/2024/02/JavaProjectNoJDK2-1.webp 891w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectNoJDK2-1-300x234.webp 300w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectNoJDK2-1-768x600.webp 768w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectNoJDK2-1-512x400.webp 512w" sizes="auto, (max-width: 891px) 100vw, 891px" /><button
			class="lightbox-trigger"
			type="button"
			aria-haspopup="dialog"
			aria-label="Enlarge"
			data-wp-init="callbacks.initTriggerButton"
			data-wp-on--click="actions.showLightbox"
			data-wp-style--right="state.imageButtonRight"
			data-wp-style--top="state.imageButtonTop"
		>
			<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="none" viewBox="0 0 12 12">
				<path fill="#fff" d="M2 0a2 2 0 0 0-2 2v2h1.5V2a.5.5 0 0 1 .5-.5h2V0H2Zm2 10.5H2a.5.5 0 0 1-.5-.5V8H0v2a2 2 0 0 0 2 2h2v-1.5ZM8 12v-1.5h2a.5.5 0 0 0 .5-.5V8H12v2a2 2 0 0 1-2 2H8Zm2-12a2 2 0 0 1 2 2v2h-1.5V2a.5.5 0 0 0-.5-.5H8V0h2Z" />
			</svg>
		</button></figure>
</div></div>
</div>


<div class="wp-block-image">
<figure data-wp-context="{&quot;imageId&quot;:&quot;69656c89becad&quot;}" data-wp-interactive="core/image" data-wp-key="69656c89becad" class="aligncenter size-full is-resized wp-lightbox-container"><img loading="lazy" decoding="async" width="483" height="203" data-wp-class--hide="state.isContentHidden" data-wp-class--show="state.isContentVisible" data-wp-init="callbacks.setButtonStyles" data-wp-on--click="actions.showLightbox" data-wp-on--load="callbacks.setButtonStyles" data-wp-on-window--resize="callbacks.setButtonStyles" src="https://jasta.io/wp-content/uploads/2024/02/JavaProjectInstallJDK-1.webp" alt="Select JDK" class="wp-image-2645" style="width:422px" srcset="https://jasta.io/wp-content/uploads/2024/02/JavaProjectInstallJDK-1.webp 483w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectInstallJDK-1-300x126.webp 300w" sizes="auto, (max-width: 483px) 100vw, 483px" /><button
			class="lightbox-trigger"
			type="button"
			aria-haspopup="dialog"
			aria-label="Enlarge"
			data-wp-init="callbacks.initTriggerButton"
			data-wp-on--click="actions.showLightbox"
			data-wp-style--right="state.imageButtonRight"
			data-wp-style--top="state.imageButtonTop"
		>
			<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="none" viewBox="0 0 12 12">
				<path fill="#fff" d="M2 0a2 2 0 0 0-2 2v2h1.5V2a.5.5 0 0 1 .5-.5h2V0H2Zm2 10.5H2a.5.5 0 0 1-.5-.5V8H0v2a2 2 0 0 0 2 2h2v-1.5ZM8 12v-1.5h2a.5.5 0 0 0 .5-.5V8H12v2a2 2 0 0 1-2 2H8Zm2-12a2 2 0 0 1 2 2v2h-1.5V2a.5.5 0 0 0-.5-.5H8V0h2Z" />
			</svg>
		</button></figure>
</div>


<p>After downloading the JDK it should be automatically selected on your project configuration screen &#8211; if not just select it from the drop-down menu. Now you have to fill out the remaining project configurations. </p>



<p>For the project name and the location, you can choose whatever you want. The preselected language Java is already correct so we leave that as it is. When choosing the build system you can choose whatever you like the best, but it is recommended to use Gradle for various factors. This includes customizability and performance. Sometimes after changing the build system, the just downloaded JDK will be deselected. If that happens, you can just reselect it.</p>



<p>Below the JDK menu, you can select the Gradle DSL which simply means in what language the Gradle files are written. While it does not matter that much, it is recommended to choose Kotlin, because it is superior to Groovy.</p>



<p>If you want you can check the two checkboxes below to add sample code and to generate the code with onboarding tips. But you can also uncheck them and just copy the necessary code which is provided later in this post. </p>



<p>You can also open the advanced settings by clicking on it. Sometimes there might be a version conflict between your JDK and your Gradle version. For example, you need to use at least Gradle version 8.5 for the JDK version 21. If there is a lower version selected, you have to deselect Auto-select and enter the required version. For every other field, you can leave with the prefilled values. </p>



<p>Now your project configuration window should look similar to the screenshot provided below. If this is the case, you can now create your first Java program via the Create button.</p>


<div class="wp-block-image">
<figure data-wp-context="{&quot;imageId&quot;:&quot;69656c89bf3db&quot;}" data-wp-interactive="core/image" data-wp-key="69656c89bf3db" class="aligncenter size-full is-resized wp-lightbox-container"><img loading="lazy" decoding="async" width="781" height="695" data-wp-class--hide="state.isContentHidden" data-wp-class--show="state.isContentVisible" data-wp-init="callbacks.setButtonStyles" data-wp-on--click="actions.showLightbox" data-wp-on--load="callbacks.setButtonStyles" data-wp-on-window--resize="callbacks.setButtonStyles" src="https://jasta.io/wp-content/uploads/2024/02/JavaProjectCreate.webp" alt="Finished Project configuration" class="wp-image-2649" style="width:644px" srcset="https://jasta.io/wp-content/uploads/2024/02/JavaProjectCreate.webp 781w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectCreate-300x267.webp 300w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectCreate-768x683.webp 768w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectCreate-512x456.webp 512w" sizes="auto, (max-width: 781px) 100vw, 781px" /><button
			class="lightbox-trigger"
			type="button"
			aria-haspopup="dialog"
			aria-label="Enlarge"
			data-wp-init="callbacks.initTriggerButton"
			data-wp-on--click="actions.showLightbox"
			data-wp-style--right="state.imageButtonRight"
			data-wp-style--top="state.imageButtonTop"
		>
			<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="none" viewBox="0 0 12 12">
				<path fill="#fff" d="M2 0a2 2 0 0 0-2 2v2h1.5V2a.5.5 0 0 1 .5-.5h2V0H2Zm2 10.5H2a.5.5 0 0 1-.5-.5V8H0v2a2 2 0 0 0 2 2h2v-1.5ZM8 12v-1.5h2a.5.5 0 0 0 .5-.5V8H12v2a2 2 0 0 1-2 2H8Zm2-12a2 2 0 0 1 2 2v2h-1.5V2a.5.5 0 0 0-.5-.5H8V0h2Z" />
			</svg>
		</button></figure>
</div>


<p>Now IntelliJ does create your first Java program with the provided configuration and your screen will look like this.</p>


<div class="wp-block-image">
<figure data-wp-context="{&quot;imageId&quot;:&quot;69656c89bf9ff&quot;}" data-wp-interactive="core/image" data-wp-key="69656c89bf9ff" class="aligncenter size-large wp-lightbox-container"><img loading="lazy" decoding="async" width="1024" height="541" data-wp-class--hide="state.isContentHidden" data-wp-class--show="state.isContentVisible" data-wp-init="callbacks.setButtonStyles" data-wp-on--click="actions.showLightbox" data-wp-on--load="callbacks.setButtonStyles" data-wp-on-window--resize="callbacks.setButtonStyles" src="https://jasta.io/wp-content/uploads/2024/02/JavaProjectFirstLook-1024x541.webp" alt="Project building process" class="wp-image-2650" srcset="https://jasta.io/wp-content/uploads/2024/02/JavaProjectFirstLook-1024x541.webp 1024w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectFirstLook-300x158.webp 300w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectFirstLook-768x405.webp 768w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectFirstLook-1536x811.webp 1536w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectFirstLook-512x270.webp 512w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectFirstLook-920x486.webp 920w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectFirstLook-1600x845.webp 1600w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectFirstLook.webp 1879w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><button
			class="lightbox-trigger"
			type="button"
			aria-haspopup="dialog"
			aria-label="Enlarge"
			data-wp-init="callbacks.initTriggerButton"
			data-wp-on--click="actions.showLightbox"
			data-wp-style--right="state.imageButtonRight"
			data-wp-style--top="state.imageButtonTop"
		>
			<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="none" viewBox="0 0 12 12">
				<path fill="#fff" d="M2 0a2 2 0 0 0-2 2v2h1.5V2a.5.5 0 0 1 .5-.5h2V0H2Zm2 10.5H2a.5.5 0 0 1-.5-.5V8H0v2a2 2 0 0 0 2 2h2v-1.5ZM8 12v-1.5h2a.5.5 0 0 0 .5-.5V8H12v2a2 2 0 0 1-2 2H8Zm2-12a2 2 0 0 1 2 2v2h-1.5V2a.5.5 0 0 0-.5-.5H8V0h2Z" />
			</svg>
		</button></figure>
</div>


<p>In the screenshot, you can see two highlighted sections. The one on the bottom indicates if there is a process running. While creating your project it will be visible. After it is finished building, the progress bar will disappear. <br>The marked section on the top will also appear when creating your project. You can either wait till the processes which are shown at the bottom bar are finished or you can press Setup SDK.</p>



<h2 class="wp-block-heading" id="start-your-program">Start your program</h2>



<p>After your project is finished building, you can now run it. If you did not select the checkbox to create some example code when creating the project, you first have to create a new class. You can do this by right-clicking on your Java folder which is inside src-main and saying New and clicking on Java Class.</p>


<div class="wp-block-image">
<figure data-wp-context="{&quot;imageId&quot;:&quot;69656c89c00b6&quot;}" data-wp-interactive="core/image" data-wp-key="69656c89c00b6" class="aligncenter size-full is-resized wp-lightbox-container"><img loading="lazy" decoding="async" width="969" height="948" data-wp-class--hide="state.isContentHidden" data-wp-class--show="state.isContentVisible" data-wp-init="callbacks.setButtonStyles" data-wp-on--click="actions.showLightbox" data-wp-on--load="callbacks.setButtonStyles" data-wp-on-window--resize="callbacks.setButtonStyles" src="https://jasta.io/wp-content/uploads/2024/02/JavaCreateClass.webp" alt="Add a new Java class" class="wp-image-2651" style="width:644px" srcset="https://jasta.io/wp-content/uploads/2024/02/JavaCreateClass.webp 969w, https://jasta.io/wp-content/uploads/2024/02/JavaCreateClass-300x293.webp 300w, https://jasta.io/wp-content/uploads/2024/02/JavaCreateClass-768x751.webp 768w, https://jasta.io/wp-content/uploads/2024/02/JavaCreateClass-512x501.webp 512w, https://jasta.io/wp-content/uploads/2024/02/JavaCreateClass-920x900.webp 920w" sizes="auto, (max-width: 969px) 100vw, 969px" /><button
			class="lightbox-trigger"
			type="button"
			aria-haspopup="dialog"
			aria-label="Enlarge"
			data-wp-init="callbacks.initTriggerButton"
			data-wp-on--click="actions.showLightbox"
			data-wp-style--right="state.imageButtonRight"
			data-wp-style--top="state.imageButtonTop"
		>
			<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="none" viewBox="0 0 12 12">
				<path fill="#fff" d="M2 0a2 2 0 0 0-2 2v2h1.5V2a.5.5 0 0 1 .5-.5h2V0H2Zm2 10.5H2a.5.5 0 0 1-.5-.5V8H0v2a2 2 0 0 0 2 2h2v-1.5ZM8 12v-1.5h2a.5.5 0 0 0 .5-.5V8H12v2a2 2 0 0 1-2 2H8Zm2-12a2 2 0 0 1 2 2v2h-1.5V2a.5.5 0 0 0-.5-.5H8V0h2Z" />
			</svg>
		</button></figure>
</div>


<p>Now you can enter whatever name you like. For this tutorial, you should name it &#8216;Main&#8217;. With that window, you can also create other things like Interfaces and Records but for this program, we need a Class. You can confirm your choices by pressing the enter key.</p>


<div class="wp-block-image">
<figure data-wp-context="{&quot;imageId&quot;:&quot;69656c89c06df&quot;}" data-wp-interactive="core/image" data-wp-key="69656c89c06df" class="aligncenter size-full wp-lightbox-container"><img loading="lazy" decoding="async" width="325" height="196" data-wp-class--hide="state.isContentHidden" data-wp-class--show="state.isContentVisible" data-wp-init="callbacks.setButtonStyles" data-wp-on--click="actions.showLightbox" data-wp-on--load="callbacks.setButtonStyles" data-wp-on-window--resize="callbacks.setButtonStyles" src="https://jasta.io/wp-content/uploads/2024/02/JavaCreateClassName.webp" alt="Create a new Java class" class="wp-image-2652" srcset="https://jasta.io/wp-content/uploads/2024/02/JavaCreateClassName.webp 325w, https://jasta.io/wp-content/uploads/2024/02/JavaCreateClassName-300x181.webp 300w" sizes="auto, (max-width: 325px) 100vw, 325px" /><button
			class="lightbox-trigger"
			type="button"
			aria-haspopup="dialog"
			aria-label="Enlarge"
			data-wp-init="callbacks.initTriggerButton"
			data-wp-on--click="actions.showLightbox"
			data-wp-style--right="state.imageButtonRight"
			data-wp-style--top="state.imageButtonTop"
		>
			<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="none" viewBox="0 0 12 12">
				<path fill="#fff" d="M2 0a2 2 0 0 0-2 2v2h1.5V2a.5.5 0 0 1 .5-.5h2V0H2Zm2 10.5H2a.5.5 0 0 1-.5-.5V8H0v2a2 2 0 0 0 2 2h2v-1.5ZM8 12v-1.5h2a.5.5 0 0 0 .5-.5V8H12v2a2 2 0 0 1-2 2H8Zm2-12a2 2 0 0 1 2 2v2h-1.5V2a.5.5 0 0 0-.5-.5H8V0h2Z" />
			</svg>
		</button></figure>
</div>


<p>After your class is created you can now insert the example code from below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public class Main {
    public static void main(String[] args) {
        System.out.printf("Hello and welcome!");

        for (int i = 1; i &lt;= 5; i++) {
            System.out.println("i = " + i);
        }
    }
}</pre>



<p>To run your first Java program you have to either click on the play button at the top right or click on the play button next to your code and select Run Main.</p>



<figure data-wp-context="{&quot;imageId&quot;:&quot;69656c89c0cb1&quot;}" data-wp-interactive="core/image" data-wp-key="69656c89c0cb1" class="wp-block-image size-full wp-lightbox-container"><img loading="lazy" decoding="async" width="874" height="548" data-wp-class--hide="state.isContentHidden" data-wp-class--show="state.isContentVisible" data-wp-init="callbacks.setButtonStyles" data-wp-on--click="actions.showLightbox" data-wp-on--load="callbacks.setButtonStyles" data-wp-on-window--resize="callbacks.setButtonStyles" src="https://jasta.io/wp-content/uploads/2024/02/JavaProjectStartProgram.webp" alt="Run your first Java program" class="wp-image-2655" srcset="https://jasta.io/wp-content/uploads/2024/02/JavaProjectStartProgram.webp 874w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectStartProgram-300x188.webp 300w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectStartProgram-768x482.webp 768w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectStartProgram-512x321.webp 512w" sizes="auto, (max-width: 874px) 100vw, 874px" /><button
			class="lightbox-trigger"
			type="button"
			aria-haspopup="dialog"
			aria-label="Enlarge"
			data-wp-init="callbacks.initTriggerButton"
			data-wp-on--click="actions.showLightbox"
			data-wp-style--right="state.imageButtonRight"
			data-wp-style--top="state.imageButtonTop"
		>
			<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="none" viewBox="0 0 12 12">
				<path fill="#fff" d="M2 0a2 2 0 0 0-2 2v2h1.5V2a.5.5 0 0 1 .5-.5h2V0H2Zm2 10.5H2a.5.5 0 0 1-.5-.5V8H0v2a2 2 0 0 0 2 2h2v-1.5ZM8 12v-1.5h2a.5.5 0 0 0 .5-.5V8H12v2a2 2 0 0 1-2 2H8Zm2-12a2 2 0 0 1 2 2v2h-1.5V2a.5.5 0 0 0-.5-.5H8V0h2Z" />
			</svg>
		</button></figure>



<p>Now IntelliJ will compile your project. While compiling, an output window will open at the bottom of your IDE. There you can see some messages regarding the building of the project and you will also see the result of your first Java program. Since this is a rather small project the output will be displayed very quickly.</p>



<figure data-wp-context="{&quot;imageId&quot;:&quot;69656c89c1167&quot;}" data-wp-interactive="core/image" data-wp-key="69656c89c1167" class="wp-block-image size-large wp-lightbox-container"><img loading="lazy" decoding="async" width="1024" height="640" data-wp-class--hide="state.isContentHidden" data-wp-class--show="state.isContentVisible" data-wp-init="callbacks.setButtonStyles" data-wp-on--click="actions.showLightbox" data-wp-on--load="callbacks.setButtonStyles" data-wp-on-window--resize="callbacks.setButtonStyles" src="https://jasta.io/wp-content/uploads/2024/02/JavaProjectResult-1024x640.webp" alt="Output of your first Java program" class="wp-image-2656" srcset="https://jasta.io/wp-content/uploads/2024/02/JavaProjectResult-1024x640.webp 1024w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectResult-300x188.webp 300w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectResult-768x480.webp 768w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectResult-1536x960.webp 1536w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectResult-512x320.webp 512w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectResult-920x575.webp 920w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectResult-1600x1000.webp 1600w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectResult.webp 1774w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><button
			class="lightbox-trigger"
			type="button"
			aria-haspopup="dialog"
			aria-label="Enlarge"
			data-wp-init="callbacks.initTriggerButton"
			data-wp-on--click="actions.showLightbox"
			data-wp-style--right="state.imageButtonRight"
			data-wp-style--top="state.imageButtonTop"
		>
			<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="none" viewBox="0 0 12 12">
				<path fill="#fff" d="M2 0a2 2 0 0 0-2 2v2h1.5V2a.5.5 0 0 1 .5-.5h2V0H2Zm2 10.5H2a.5.5 0 0 1-.5-.5V8H0v2a2 2 0 0 0 2 2h2v-1.5ZM8 12v-1.5h2a.5.5 0 0 0 .5-.5V8H12v2a2 2 0 0 1-2 2H8Zm2-12a2 2 0 0 1 2 2v2h-1.5V2a.5.5 0 0 0-.5-.5H8V0h2Z" />
			</svg>
		</button></figure>



<p>The result displays firstly the sentence &#8216;Hello and welcome!&#8217; which is done with the command System.out.printf(). After that, you can see the numbers from 1 to 5. This is done via the for loop which is simply counting from 1 (i = 1) to 5 (i &lt;= 5) while i++ says i should be incremented by 1 with every run. Inside the for loop, you can see a slightly different version of the first command to output the &#8216;Hello and welcome!&#8217;. The only real difference is that System.out.println prints every output inside a new line. To see what is happening inside the for loop it is printing out the current number which is assigned to i in the output window.</p>



<h2 class="wp-block-heading" id="modify-the-source-code-of-your-first-java-program">Modify the source code of your first Java program</h2>



<p>Now that you have created and started your first Java program, you can modify it a bit. Just replace your current code with the code from below. If your current code has &#8216;package XXX&#8217; in the first line, you have to leave it there and just replace everything below.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("What is your name?");

        Scanner reader = new Scanner(System.in);
        System.out.println("Hello " + reader.next() + "!");
    }
}</pre>



<p>If you execute the program now, you will see that it is asking you for your name. Just enter your name at that point and press enter. The program will now greet you. </p>



<p>From this code, you will already recognize the &#8216;System.out.println()&#8217; which is printing something out in your output window. The only new part is the Scanner, which is there to read your input, in this case, your name.<br>The last &#8216;System.out.println()&#8217; now combines your input which we get via reader.next() with &#8216;Hello&#8217; and a &#8216;!&#8217;.</p>



<p>Maybe you have also noticed the import statement on top of the code. This is necessary so that we can use the Scanner class inside our Main class. But you do not have to worry about this too much because IntelliJ creates the imports for you automatically while programming.</p>


<div class="wp-block-image">
<figure data-wp-context="{&quot;imageId&quot;:&quot;69656c89c1810&quot;}" data-wp-interactive="core/image" data-wp-key="69656c89c1810" class="aligncenter size-large wp-lightbox-container"><img loading="lazy" decoding="async" width="1024" height="643" data-wp-class--hide="state.isContentHidden" data-wp-class--show="state.isContentVisible" data-wp-init="callbacks.setButtonStyles" data-wp-on--click="actions.showLightbox" data-wp-on--load="callbacks.setButtonStyles" data-wp-on-window--resize="callbacks.setButtonStyles" src="https://jasta.io/wp-content/uploads/2024/02/JavaProjectNameProgram-1024x643.webp" alt="Output of your modified Java program" class="wp-image-2657" srcset="https://jasta.io/wp-content/uploads/2024/02/JavaProjectNameProgram-1024x643.webp 1024w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectNameProgram-300x188.webp 300w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectNameProgram-768x482.webp 768w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectNameProgram-1536x964.webp 1536w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectNameProgram-512x321.webp 512w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectNameProgram-920x578.webp 920w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectNameProgram-1600x1005.webp 1600w, https://jasta.io/wp-content/uploads/2024/02/JavaProjectNameProgram.webp 1771w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /><button
			class="lightbox-trigger"
			type="button"
			aria-haspopup="dialog"
			aria-label="Enlarge"
			data-wp-init="callbacks.initTriggerButton"
			data-wp-on--click="actions.showLightbox"
			data-wp-style--right="state.imageButtonRight"
			data-wp-style--top="state.imageButtonTop"
		>
			<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="none" viewBox="0 0 12 12">
				<path fill="#fff" d="M2 0a2 2 0 0 0-2 2v2h1.5V2a.5.5 0 0 1 .5-.5h2V0H2Zm2 10.5H2a.5.5 0 0 1-.5-.5V8H0v2a2 2 0 0 0 2 2h2v-1.5ZM8 12v-1.5h2a.5.5 0 0 0 .5-.5V8H12v2a2 2 0 0 1-2 2H8Zm2-12a2 2 0 0 1 2 2v2h-1.5V2a.5.5 0 0 0-.5-.5H8V0h2Z" />
			</svg>
		</button></figure>
</div>


<p>Now you have successfully created your first Java program and also modified it.<br>Have fun coding!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://jasta.io/java-basics/create-your-first-java-program-with-ease/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
