{"id":153,"date":"2025-08-18T10:43:39","date_gmt":"2025-08-18T10:43:39","guid":{"rendered":"https:\/\/www.examtopics.info\/blog\/?p=153"},"modified":"2026-10-29T23:10:40","modified_gmt":"2026-10-29T23:10:40","slug":"essential-java-program-examples-with-detailed-outputs-for-beginners","status":"publish","type":"post","link":"https:\/\/www.examtopics.info\/blog\/essential-java-program-examples-with-detailed-outputs-for-beginners\/","title":{"rendered":"Essential Java Program Examples with Detailed Outputs for Beginners"},"content":{"rendered":"<p>Java examples become useful when a learner can type the source, compile it, predict the output and explain why it appears. These five small programs demonstrate output, input, decisions, arrays and maps. Run each one separately in a file named <code>Main.java<\/code>; a file containing <code>public class Main<\/code> must use the same base name. The examples work with a modern supported JDK and require no third-party dependencies.<\/p>\n<h2>Prepare a repeatable compile-and-run workflow<\/h2>\n<p>Install a current supported JDK, open a terminal in the folder containing <code>Main.java<\/code>, and check both <code>java -version<\/code> and <code>javac -version<\/code>. The first command reports the runtime; the second establishes that the compiler is available. Running <code>java Main<\/code> looks for the compiled class. If Java reports that it cannot find the main class, check the working directory, file spelling and compilation errors before changing code.<\/p>\n<pre><code class=\"language-bash\">javac Main.java\njava Main<\/code><\/pre>\n<p>Compile a program after every edit. A program may run successfully from an old <code>Main.class<\/code> even when the current source contains a typo, so do not ignore compiler diagnostics. Use one code example at a time and compare its actual output with the example shown below.<\/p>\n<h2>Example 1: print a message and a calculated value<\/h2>\n<pre><code class=\"language-java\">public class Main {\n    public static void main(String[] args) {\n        int price = 12;\n        int quantity = 3;\n        System.out.println(&quot;Order total: &quot; + price * quantity);\n    }\n}<\/code><\/pre>\n<p>Expected output: <code>Order total: 36<\/code>. The multiplication happens before string concatenation, so Java computes the total and then appends it to the message. For financial calculations involving fractional currency values, do not automatically switch to <code>double<\/code>; consider <code>BigDecimal<\/code> with explicit rounding rules.<\/p>\n<h2>Example 2: read a number and classify it<\/h2>\n<pre><code class=\"language-java\">import java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        try (Scanner input = new Scanner(System.in)) {\n            System.out.print(&quot;Enter an integer: &quot;);\n            int value = input.nextInt();\n            if (value &gt; 0) {\n                System.out.println(&quot;Positive&quot;);\n            } else if (value &lt; 0) {\n                System.out.println(&quot;Negative&quot;);\n            } else {\n                System.out.println(&quot;Zero&quot;);\n            }\n        }\n    }\n}<\/code><\/pre>\n<p>When the user enters <code>-4<\/code>, the program prints <code>Negative<\/code>. When the user enters <code>0<\/code>, it prints <code>Zero<\/code>. <code>nextInt()<\/code> throws an input-mismatch exception for non-integer text; production input handling should validate and recover instead of displaying a stack trace. The <code>try<\/code> block closes the scanner when it is no longer used.<\/p>\n<h2>Example 3: count even numbers with a loop<\/h2>\n<pre><code class=\"language-java\">public class Main {\n    public static void main(String[] args) {\n        int count = 0;\n        for (int n = 1; n &lt;= 10; n++) {\n            if (n % 2 == 0) {\n                count++;\n            }\n        }\n        System.out.println(&quot;Even numbers: &quot; + count);\n    }\n}<\/code><\/pre>\n<p>Expected output: <code>Even numbers: 5<\/code>. The remainder operator <code>%<\/code> makes parity visible: even integers have a remainder of zero when divided by two. A frequent beginner error is using <code>n &lt; 10<\/code> when the requirement includes 10; test the boundaries rather than only the middle of a loop.<\/p>\n<h2>Example 4: find the largest value in an array<\/h2>\n<pre><code class=\"language-java\">public class Main {\n    public static void main(String[] args) {\n        int[] scores = {8, 12, 5, 17, 9};\n        int largest = scores[0];\n        for (int score : scores) {\n            if (score &gt; largest) {\n                largest = score;\n            }\n        }\n        System.out.println(&quot;Largest: &quot; + largest);\n    }\n}<\/code><\/pre>\n<p>Expected output: <code>Largest: 17<\/code>. Initializing from the first element handles all-negative arrays correctly, unlike initializing a maximum to zero. It also assumes the array is nonempty. For reusable code, reject empty input or return an optional result explicitly rather than accessing index zero without checking.<\/p>\n<h2>Example 5: count repeated words with a map<\/h2>\n<pre><code class=\"language-java\">import java.util.HashMap;\nimport java.util.Map;\n\npublic class Main {\n    public static void main(String[] args) {\n        String[] words = {&quot;java&quot;, &quot;python&quot;, &quot;java&quot;, &quot;go&quot;, &quot;java&quot;};\n        Map&lt;String, Integer&gt; counts = new HashMap&lt;&gt;();\n        for (String word : words) {\n            counts.merge(word, 1, Integer::sum);\n        }\n        System.out.println(&quot;java appears: &quot; + counts.get(&quot;java&quot;));\n    }\n}<\/code><\/pre>\n<p>Expected output: <code>java appears: 3<\/code>. A map associates each distinct word with a count, and <code>merge<\/code> increments its value. A <code>HashMap<\/code> does not promise iteration order, so avoid comparing a printed whole-map representation as though the key order were guaranteed.<\/p>\n<h2>Practice problems and debugging<\/h2>\n<ul>\n<li>Change the loop bound to 9 and predict the even-number count before running the code.<\/li>\n<li>Replace the array with only negative numbers and verify the maximum still works.<\/li>\n<li>Add a new word to the map and display its count.<\/li>\n<li>Enter nonnumeric input in the scanner example; note which exception occurs and design a user-friendly retry.<\/li>\n<\/ul>\n<p>The goal is not to memorize console screenshots but to reason about inputs, state changes, and expected outputs. If classes and object construction still feel unfamiliar, the existing explanation of <a href=\"https:\/\/www.examtopics.info\/blog\/essential-core-java-concepts-every-developer-should-master-for-career-growth\/\">Java classes and objects<\/a> provides useful conceptual context. For language changes and current JDK tooling, refer to the official Dev.java learning material rather than relying on outdated applet-era examples.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Java examples become useful when a learner can type the source, compile it, predict the output and explain why it appears. These five small programs demonstrate output, input, decisions, arrays and maps. Run each one separately in a file named Main.java; a file containing public class Main must use the same base name. The examples [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2,14],"tags":[],"class_list":["post-153","post","type-post","status-publish","format-standard","hentry","category-post","category-software-development"],"_links":{"self":[{"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/posts\/153","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/comments?post=153"}],"version-history":[{"count":3,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/posts\/153\/revisions"}],"predecessor-version":[{"id":5934,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/posts\/153\/revisions\/5934"}],"wp:attachment":[{"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/media?parent=153"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/categories?post=153"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.examtopics.info\/blog\/wp-json\/wp\/v2\/tags?post=153"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}