<?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 Basics &#8211; jasta</title>
	<atom:link href="https://jasta.io/java-basics/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 Basics &#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>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;695d27cb43760&quot;}" data-wp-interactive="core/image" data-wp-key="695d27cb43760" 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;695d27cb43dd2&quot;}" data-wp-interactive="core/image" data-wp-key="695d27cb43dd2" 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;695d27cb444a8&quot;}" data-wp-interactive="core/image" data-wp-key="695d27cb444a8" 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;695d27cb44ad5&quot;}" data-wp-interactive="core/image" data-wp-key="695d27cb44ad5" 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;695d27cb44fff&quot;}" data-wp-interactive="core/image" data-wp-key="695d27cb44fff" 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;695d27cb45598&quot;}" data-wp-interactive="core/image" data-wp-key="695d27cb45598" 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;695d27cb45a70&quot;}" data-wp-interactive="core/image" data-wp-key="695d27cb45a70" 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;695d27cb45fc7&quot;}" data-wp-interactive="core/image" data-wp-key="695d27cb45fc7" 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;695d27cb465e9&quot;}" data-wp-interactive="core/image" data-wp-key="695d27cb465e9" 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;695d27cb46dad&quot;}" data-wp-interactive="core/image" data-wp-key="695d27cb46dad" 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>
