{"id":15042907,"url":"https://github.com/in28minutes/java-tutorial-for-beginners","last_synced_at":"2025-05-15T08:08:57.200Z","repository":{"id":39415639,"uuid":"182059398","full_name":"in28minutes/java-tutorial-for-beginners","owner":"in28minutes","description":"Java Tutorial For Beginners with 500 Code Examples","archived":false,"fork":false,"pushed_at":"2023-11-26T21:01:07.000Z","size":1335,"stargazers_count":1557,"open_issues_count":13,"forks_count":1461,"subscribers_count":83,"default_branch":"master","last_synced_at":"2025-04-07T03:13:57.900Z","etag":null,"topics":["java","java-8","java8","programming","programming-challenges","programming-fundamentals"],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/in28minutes.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-04-18T09:34:41.000Z","updated_at":"2025-04-06T16:24:37.000Z","dependencies_parsed_at":"2024-10-12T15:50:33.867Z","dependency_job_id":null,"html_url":"https://github.com/in28minutes/java-tutorial-for-beginners","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/in28minutes%2Fjava-tutorial-for-beginners","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/in28minutes%2Fjava-tutorial-for-beginners/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/in28minutes%2Fjava-tutorial-for-beginners/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/in28minutes%2Fjava-tutorial-for-beginners/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/in28minutes","download_url":"https://codeload.github.com/in28minutes/java-tutorial-for-beginners/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248889907,"owners_count":21178321,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["java","java-8","java8","programming","programming-challenges","programming-fundamentals"],"created_at":"2024-09-24T20:48:14.549Z","updated_at":"2025-04-14T13:41:20.464Z","avatar_url":"https://github.com/in28minutes.png","language":null,"funding_links":[],"categories":["Programming languages"],"sub_categories":["Java"],"readme":"# Java Tutorial For Beginners\n\nWelcome to this book on **\"Learning Java In 150 Steps\"**. \n\nI am **Ranga Karanam**, and I have more than two decades of programming experience. \n\nI love Programming. One of the aims I had when I started ```in28minutes``` was to make learning programming easy. Thanks for helping us provide amazing courses to 300,000 learners across the world.\n\nAt **In28Minutes**, we ask ourselves one question every day: \"How do we create awesome learning experiences?\" \n\nIn this book, you will learn to write **object** **oriented** code with Java. You will be exposed to a lot of examples, exercises and tips. We will take up a lot of examples, and try and see how to write code for those in Java. \n\nHelp us improve this guide - **Fork, Pull Requests, Shares and Likes are recommended**!\n\n## Table of Contents\n\n* [Chapter 01 - Introduction to Programming with Print-Multiplication-Table](#introduction-to-programming-with-print-multiplication-table)\n* [Chapter 02 - Understanding Methods](#understanding-methods)\n* [Chapter 03 - Understanding the Java Platform](#understanding-the-java-platform)\n* [Chapter 04 - Eclipse](#eclipse)\n* [Chapter 05 - Object Oriented Progamming (OOP)](#object-oriented-progamming-oop)\n* [Chapter 06 - Primitive Data Types](#primitive-data-types)\n* [Chapter 07 - Introducing Conditionals - if, switch and more](#introducing-conditionals---if-switch-and-more)\n* [Chapter 08 - Loops](#loops)\n* [Chapter 09 - Reference Types](#reference-types)\n* [Chapter 10 - Arrays and ArrayList](#arrays-and-arraylist)\n* [Chapter 11 - Object Oriented Programming (*OOP*) - Revisited](#object-oriented-programming-oop---revisited)\n* [Chapter 12 - Introducing Collections](#introducing-collections)\n* [Chapter 13 - Introducing Generics](#introducing-generics)\n* [Chapter 14 - Introduction to Functional Programming](#introduction-to-functional-programming)\n* [Chapter 15 - Threads and Concurrency](#threads-and-concurrency)\n* [Chapter 16 - Introduction To Exception handling](#introduction-to-exception-handling)\n* [Chapter 17 - File Operations](#file-operations)\n* [Chapter 18 - Concurrency : Advanced Topics](#concurrency--advanced-topics)\n\n## Our Approach\n\nWe did a study on why students give up on programming?\n\nThe popular answer was\n\n\u003e Difficulty in writing their first program\n\nPut yourselves in the shoes of a beginner and look at this typical ```Java Hello World Example```.\n\n```java\npackage com.in28minutes.firstjavaproject; \npublic class HelloWorld \n{   \n     public static void main(String[] args) {           \n            System.out.println(\"Hello World\");   \n     } \n}\n```\n\nA ```Programming Beginner``` will be overwhelmed by this. I remember how I felt when I saw this almost 20 years back. Stunned.\n\nWhy?\n- There are a number of keywords and concepts - package, public, class, static, void, String[] and a lot more..\n- What if the programmer makes a typo? Will he be able to fix it?\n\n\n**We believe that there has to be a better way to learn programming.**\n\n- Why don't we learn programming step by step? \n- Why should it not be a lot of fun? \n- Why don't we solve a lot of problems and learn programming as a result?\n\nThis is the approach we took to writing this guide and develop our introductory programming courses for Java and Python. \n\n\u003e Do you know? The first 3 hours of our Java Course is available [here](https://courses.in28minutes.com/p/java-tutorial-for-beginner-in-250-steps).\n\n\n\n## Introduction to Programming with Print-Multiplication-Table\n\n### Step 01: First Challenge : The Print-Multiplication-Table (*PMT-Challenge*)\n\nLearning to program is a lot like learning to ride a bicycle. The first few steps are the most challenging ones. \n\nOnce you use this stepwise approach to solve a few problems, it becomes a habit. \n\nIn this book, we will introduce you to Java programming by taking on a few simple problems to start off. \n\n\u003e Having fun along the way is what we will aim to do.\n \n_Are you all geared up, to take on your first programming challenge? **Yes**?  Let's get started then!_\n\nOur first *programming challenge* aims to do, what every kid does in math class: reading out a multiplication table.\n\n#### The *PMT-Challenge*\n\n1. Compute the multiplication table for ```5```, with entries from ```1``` to ```10```.\n2. Display this table.\n\n```\n5 * 1  =  5\n5 * 2  = 10\n5 * 3  = 15\n5 * 4  = 20\n5 * 5  = 25\n5 * 6  = 30\n5 * 7  = 35\n5 * 8  = 40\n5 * 9  = 45\n5 * 10 = 50\n```\n\nAs part of solving the multiplication table problem, you will be introduced to:\n* **JShell**\n* **Statements**\n* **Expressions**\n* **Variables**\n* **Literals**\n* **Conditionals**\n* **Loops**\n* **Methods** \n\n#### Summary\n\nIn this step, we:\n\n* Stated our first programming challenge, *PMT-Challenge*\n* Identified basic Java concepts to learn, to solve this challenge\n\n### Step 02: Introducing ```JShell```\n- - - \n\n```JShell``` is a programming tool, introduced in Java SE 9. JShell is a **_REPL_** interface. The term **REPL** refers to this:\n\n* **_'R'_** stands for **R**ead; *Read* the input Java code\n* **_'E'_** means **E**val; *Evaluate* the source code\n* **_'P'_** translates to **P**rint; *Print* out the result\n* **_'L'_** indicates **L**oop; *Loop* around, and wait for the next input\n\nHow about starting off exploring Java? Are you game?\n\n##### Snippet-1: Check the Java programming environment\n\nYou can use [https://tryjshell.org/](https://tryjshell.org/) to run the code for the first 25 steps. Or you can [Install Java 12+](https://github.com/in28minutes/java-a-course-for-beginners/blob/master/00-02-java-eclipse-installation.md#installing-java). Here's the [troubleshooting section](https://github.com/in28minutes/java-a-course-for-beginners/blob/master/00-02-java-eclipse-installation.md#troubleshooting) if you face problems.\n\nLaunch up command prompt or Terminal.\n\nLet type in ```java -version``` on the terminal and press enter.\n\n```\n\n\tin28minutes$\u003ejava -version\n\tjava version \"x.0.1\"\n\tJava(TM) SE Runtime Environment (build x.0.1+11)\n\tJava HotSpot(TM) 64-bit Server VM (build x.0.1+11, mixed mode)\n\tin28minutes$\u003e\n\n```\n\nA successful execution displays the version of Java installed your system. You need to have atleast Java 9 to pursue this book.\n\n##### Snippet-2: Launch JShell\n\nYou can launch JShell by typing ```jshell``` at your terminal. \n\n```java\n\n\tin28minutes$\u003ejshell\n\n\t|  Welcome to JShell version x.0.1\n \t|  For an introduction type: /help intro\n\tjshell\u003e\n\n```\n\nWhen run, this command displays basic information about the installed ```JShell``` program. A ```jshell``` prompt then appears, which waits for your input.\n\n##### Snippet-3: Sample JShell input, using a built-in command\n\nThe ```JShell``` command ```/help```, with a parameter ```intro```, gives you basic guidelines on how you use the tool.\n\n```java\n\n\tjshell\u003e /help intro\n\n\t|\n\t| intro\n\t| The jshell tool allows you to execute Java code, getting immediate results.\n\t| You can enter a Java definition (variable, method, class, etc), like: int x =8\n\t| or a Java expression, like: x + x\n\t| or a Java statement or import.\n\t| These little chunks of Java code are called 'snippets'.\n\t| There are also jshell commands that allow you to understand and\n\t| control what you are doing, like: /list\n\t|\n\t| For a list of commands: /help\n\t\n\tjshell\u003e\n\n```\n\n\n##### Snippet-4: Evaluating an expression\n\nType ```3+4``` at the Jshell prompt\n\n```java\n\n\tjshell\u003e 3 + 4\n\t$1 ==\u003e 7\n\tjshell\u003e\n\n```\n\nThis was your first real **REPL** cycle! When you type in  ```3 + 4```, JShell evaluates it and prints the result. \n\n\u003e The entity ```$1``` is actually a variable name assigned to the result. We will talk about this later. \n\n##### Snippet-5: Getting out of JShell\n\nThe ```/exit``` command terminates the ```JShell``` program, and we are back to the terminal prompt.\n\n\n```java\n\n\tjshell\u003e /exit\n\t|  Goodbye\n\t\n\tin28minutes$\u003e\n\n```\n\n\n##### Snippet-6: Again, enter JShell and Exit it!\n\nYou can now effortlessly launch, feed code to, and exit from  ```JShell```!\n\n```java\n\n\tin28minutes$\u003e jshell\n\t\n\t|  Welcome to JShell version 9.0.1\n\t|  For an introduction type: /help intro\n\tjshell\u003e /exit\n\t|  Goodbye\n\t\n\tin28minutes$\u003e\n\n```\n\n#### Summary\n\nIn this step, we learned:\n\n* How to launch ```JShell``` from our terminal, and run a few commands on it\n* How to run Java code on the ```JShell``` prompt\n\n### Step 03: Welcome to Problem Solving\n\nLets try to break down the *PMT-Challenge* problem to be able to solve it.\n\n```\n5 * 1  =  5\n5 * 2  = 10\n5 * 3  = 15\n5 * 4  = 20\n5 * 5  = 25\n5 * 6  = 30\n5 * 7  = 35\n5 * 8  = 40\n5 * 9  = 45\n5 * 10 = 50\n```\n\n\nHere is how our draft steps look like\n* Calculate ```5 * 3``` and print result as ```15```\n* Print ```5 * 3 = 15``` (```15``` is result of previous calculation)\n* Do this ten times, once for each table entry (going from ```1``` to ```10```)\n\n#### Summary\n\nIn this step, we:\n\n* Broke down the *PMT-Challenge* problem into sub-problems\n\n### Step 04: Introducing Expressions \n\nThe first part of solving our *PMT-Challenge* is to calculate the product of ```5``` and another number, say ```3```.\n\nLet's start up jshell and type ```5 X 3```.\n\n```java\n\n\tin28minutes$\u003e jshell\n\n\t|  Welcome to JShell version x.0.1\n\t|  For an introduction type: /help intro\n\tjshell\u003e 5 X 3\n\t| Error:\n\t| ';' expected\n\t| 5 X 3\n\t|  ^\n\t| Error:\n\t| not a statement\n\t| 5 X 3\n\t|   ^\n\t| Error:\n\t| ';' expected\n\t| 5 X 3\n\t|    ^\n\t| Error:\n\t| missing return statement\n\t| 5 X 3\n\t| ^---^\n```\nYou probably look at the symbol 'X' as a multiplier, remembering your school days.\n\nJava does not identify '```X```' as the multiplication operator! Java supports multiplication, but only if you use its *predefined* operator, ```*```.\n\nLet's type in code shown below:\n\n```java\n\tjshell\u003e 5 * 3\n\t$1 ==\u003e 15\n\tjshell\u003e\n\n```\n\nSuccess!\n\nLet's look at some terminology:\n- ```5 * 3 ``` is an expression.\n- ```5``` and ```3``` are operands. They are also called **literals** or constant values.\n- ```*``` is an operator.\n\n\nJava also has built-in operators to perform other numerical tasks, such as:\n\n* Addition: ```+``` \n* Subtraction: ```-```\n* Division: ```/```\n* Modulo arithmetic: ```%``` \n\nThe following examples illustrate how to use them.\n \n```java\n\n\tjshell\u003e 5 * 10\n\t$2 ==\u003e 50\n\tjshell\u003e 5 + 10\n\t$3 ==\u003e 15\n\tjshell\u003e 5 - 10\n\t$4 ==\u003e -5\n\tjshell\u003e 10 / 2\n\t$5 ==\u003e 5\n\tjshell\u003e\n\n```\n\nYour school math memories are still fresh, and the operators don't seem to disappoint either! ```+```, ```-``` and ```/``` are your bread-and-butter operators.\n\n```%``` is the modulo operator, which gives you the remainder when integer division is performed. \n\n```java\n\n\tjshell\u003e 9 % 2\n\t$6 ==\u003e 1\n\tjshell\u003e 8 % 2\n\t$7 ==\u003e 0\n\tjshell\u003e\n\n```\n\n##### Snippet: Complex Expressions, Anyone?\n\nJava allows you to use more than one operator within an expression.\n\nLet's look at some simple expressions with multiple operators.\n\n```java\n \n\tjshell\u003e 5 + 5 + 5\n\t$8 ==\u003e 15\n\tjshell\u003e 5 + 10 - 15\n\t$9 ==\u003e 0\n\tjshell\u003e 5 * 5 + 5\n\t$10 ==\u003e 30\n\tjshell\u003e 5 * 15 / 3\n\t$11 ==\u003e 25\n\n```\n\nEach of above expressions have two operators and three operands.\n\n#### Summary\n\nIn this step, we:\n\n* Learned how to construct numeric expressions\n* Discovered that operators are predefined symbols\n* Combined several operators to form larger expressions\n \n### Step 05: Programming Exercise PE-1 (With Solutions)\n\nAt this stage, your smile tells us that you enjoy evaluating Java expressions. What if we tickle your mind a bit, to make sure it hasn't fallen asleep? \n\nOkay, here comes a couple of programming exercises.\n\n1. Write an expression to calculate the number of minutes in a day.\n2. Write an expression to calculate the number of seconds in a day.\n\n#### Solution 1\n\n60 (minutes in an hour) multipled by 24 (hours in a day)\n\n```java\n\n\tjshell\u003e 60 * 24\n\t$1 ==\u003e 1440\n```\n\n#### Solution 2\n\n60 (seconds in a minute) multipled by 60 (minutes in an hour) multipled by 24 (hours in a day)\n\n```java\n$jshell\u003e60 * 60 * 24\n\n$1 ==\u003e 86400\n```\n\n### Step 06: Operators\n\nLets look at a few more examples to understand operators.\n\n#### Invalid Operators\n\nLet's type in ```5 ** 6``` followed by ```5 $ 6``` in JShell\n\n```java\n\tjshell\u003e 5 ** 6\n\t| Error:\n\t| Illegal start of expression\n\t| 5 ** 6\n\t|     ^\n\n\tjshell\u003e 5 $ 6 \n\t| Error:\n\t| ';' expected\n\t| 5 $ 6\n\t|  ^\n\t| Error:\n\t| not a statement\n\t| 5 $ 6\n\t|   ^\n\t| Error:\n\t| ';' expected\n\t| 5 $ 6\n\t|    ^\n\n\tjshell\u003e 5 */ 6\n\t| Error:\n\t| Illegal start of expression\n\t| 5 */ 6\n\t|     ^\n\t\n```\n\n```JShell``` was not impressed with our efforts at all! \n\nJava has a set of grammar rules, called its **syntax**. Code that does not follow these rules throw errors. The compiler informs you by listing the errors, and also provides hints on how you can correct them. \n\nNow, why is an error being thrown?\n\nOperators in Java are all predefined, and limited in number.  ```*``` is a valid operator, whereas ```**``` and ```$```  were rejected, with error messages.\n\n#### Understanding Result of Expression with Mixed Types\n\nLet's look at another example:\n\n```java\n\n\tjshell\u003e 5 / 2\n\t$1 ==\u003e 2\n\tjshell\u003e\n\n```\n\nSurprise, Surprise! ```JShell``` seems to evaluate ``` 5 / 2 ``` to ``` 2 ``` instead of ```2.5```. Where did we go wrong?\n\nRead what follows, with the biggest magnifying lens you can find:\n\n**The result of an expression when evaluated, depends on the operator context**. This context is determined by the operands passed to it\n\nThere are two kinds of numbers typically used in programming : integer (1,2,3,...) and floating-point (1.1,2.3, 56.7889 etc). These values are represented by different **types** in Java. Integers are commonly of type ```int```, and the floating-point numbers are ```double``` by default.\n\nIn the expression ```5/2```, both ```5``` and ```2``` are of type ```int```. So, the result is also of type ```int```. \n\nLet's try with a few floating point numbers: \n\n```java\n\n\tjshell\u003e 5.0 / 2.0\n\t$2 ==\u003e 2.5\n```\nBoth ```5.0``` and ```2.0``` are of type ```double```, the result is ```double```. We get a result of ```2.5```, as expected. \n\nLet's do a mixed operation - using a floating point number and integer.\n\n```java\n\tjshell\u003e 5.0 / 2\n\t$3 ==\u003e 2.5\n\tjshell\u003e\n\n```\n\nAmong the types ```int``` and ```double```, ```double``` is considered to be a *wider type*. When you perform a numeric operation between two types, the result will be of the wider type.\n\n\n\n#### Understanding Precedence of Operators\n\nLet's look at few complex examples of expressions with more than one operator.\n\n```java\n\n\tjshell\u003e 5 + 5 * 6\n\t$1 ==\u003e 35\n\tjshell\u003e 5 - 2 * 2\n\t$2 ==\u003e 1\n\tjshell\u003e 5 - 2 / 2\n\t$3 ==\u003e 4\n\tjshell\u003e\n\n```\n\nSurprised with the results?  You might expect 5 + 5 * 6 evaluate to 10 * 6 i.e. 60. Howeever, we got ```35```! \n\n\u003e We write English left-to-right, and carry this habit to calculations as well. \n\n_In expressions with multiple operators, the order of sub-expression evaluation depends on **operator precedence**._\n\nThe basic rules for operator precedence are actually quite simple (we will look at other rules a little later). \n\nThe operators in the set  {```*```, ```/```, ```%```} have higher precedence than the operators in the set {```+```, ```-```}.\n\nIn the expression ```5 + 5 * 6``` : 5*6 is evaluated first. So, 5 + 5 * 6 becomes 5 + 30 i.e. 35.\n\n```5 - 2 * 2``` and ```5 - 2 / 2``` are evaluated by following the same rules.\n\n#### Use paranthesis for clear code \n\nJava provides syntax elements, called **parentheses** ```(```   and   ```)```, to group parts of an expression.\n\n```java\n\n\tjshell\u003e (5 - 2) * 2\n\t$4 ==\u003e 6\n\tjshell\u003e 5 - (2 * 2)\n\t$5 ==\u003e 1\n\tjshell\u003e\n\n```\n\nWhen you put an expression in parenthesis, it is evaluated first. (5 - 2) * 2 =\u003e 3 * 2 =\u003e 6.\n\nParentheses lead to better readability as they reduce confusion and help avoid errors. \n\nThe old adage **_A stitch in time saves nine_** rings very true here. Use parentheses to make your code easy to read, even when they might not be necessary.\n\n#### Summary\n\nIn this step, we:\n\n* Discovered that operators are all predefined\n* Learned that result of operation depends on operand types\n* Understood what operator precedence means\n* Used parentheses to group parts of an expression\n \n### Step 07: Introducing Console Output \n\nWe have computed the product of two literals (as in ```5 * 3```) in earlier steps. \n\nThe next step is to print this result in a customized format - ```5 * 3 = 15```.\n\nHow do we do this?\n\nLet try typing it in into JShell\n\n```java\njshell\u003e 5 * 3 = 15\n|  Error:\n|  unexpected type\n|    required: variable\n|    found:    value\n|  5 * 3 = 15\n|  ^---^\n```\n\nHmm! Error.\n\nHow do we print text?\n\nJava has a built-in utility method called ```System.out.println()```, that displays text on the console. \n\n```java\njshell\u003e System.out.println(3*4)\n12\n```\n\nWe formed an expression, ```3*4```, and *passed* it to ```System.out.println()```, which is a built-in Java **method**.\n\n```System.out.println(3*4)``` is an example of a **statement**. It is a **method call**.\n\nThe syntax rules for method calls are quite strict, and all its parts are mandatory.\n\n```java\njshell\u003e System.out.println3*4)\n| Error:\n| ';' expected\n| System.out.println3*4)\n|___________________^\n| Error:\n| cannot find symbol\n|       symbol: variable println3\n| System.out.println3*4)\n| ^---------------------^\n\njshell\u003e System.out.println 3*4\n|  Error:\n|  ';' expected\n|  System.out.println 3*4\n|                    ^\n|  Error:\n|  cannot find symbol\n|    symbol:   variable println\n|  System.out.println 3*4\n|  ^----------------^\n\n```\n\nWhat if we want to print an entry of the Multiplication Table, as part of our solution to *PMT-Challenge*? In other words, how do we print the exact text ```5 * 2 = 10``` on the console? \n\n```java\n\n\tjshell\u003e System.out.println(5 * 2 = 10)\n\t| Error:\n\t| unexpected type\n\t| required:  variable\n\t| found:     value\n\t| System.out.println(5 * 2 = 10)\n\t|____________________^--------^\n\n```\n\nYou wanted to print ```5 * 2 = 10``` on the console. However, we see that we cannot pass ```5 * 2 = 10``` as an argument to ```System.out.println()```.\n\n```5 * 2 = 10``` is not a single value. It is a piece of text with numeric characters, ```*``` and ```=```. \n\nIn Java, we represent text using ```String```. A ```String literal``` is a sequence of characters, enclosed within **double quotes**: ```\"``` and ```\"```. \n\n```java\n\tjshell\u003e System.out.println(\"5 * 2 = 10\")\n\t| 5 * 2 = 10\n```\n\nCongratulations! You have now figured out how to display not just numbers on the console, but text as well!\n\n#### Summary\n\nIn this step, we:\n\n* Were introduced to the ```System.out.println()``` method for console output\n* Used this utility to print a single *PMT-Challenge* table entry\n\n### Step 08: Programming Exercise PE-02\n\nTry and solve the following exercises:\n\n1. Print ```Hello World``` onto the console.\n\n2. Print ```5 * 3```, as is.\n\n3. Print the calculated value of ```5 * 3```.\n\n4. Print the number of seconds in a day, using the ```System.out.println``` method.\n\n5. Do a syntax revision for the code that you write for each of the above exercises. In your code, identify the following elements:\n\t* Numeric and string literals\n\t* Expressions\n\t* Operators\n\t* Operands\n\t* Method calls\n\n### Step 09: Solutions to PE-02\n\n#### Solution 1\n\n```java\n\n\tjshell\u003e System.out.println(\"Hello World\")\n\tHello World\n\n```\n\n#### Solution 2\n\n```java\n\n\tjshell\u003e System.out.println(\"5 * 3\")\n\t5 * 3\n\tjshell\u003e\n```\n\n#### Solution 3\n\n```java\n\n\tjshell\u003e System.out.println(5 * 3)\n\t15\n\n```\n\n#### Solution 4\n\n```java\n\n\tjshell\u003e System.out.println(60 * 60 * 24)\n\t86400\n\n```\n\n### Step 10: Whitespace, Case sensitiveness and Escape Characters\nThe term *whitespace* refers to any sequence of continuous space, tab or newline characters.\n\n#### Whitespace\n\nLet's see a few examples of whitespace in action.\n\nWhitespace affects the output when used in-and-around string literals.\n\n```java\njshell\u003e System.out.println(\"Hello World\")\nHello World\njshell\u003e System.out.println(\"Hello      World\")\nHello      World\njshell\u003e System.out.println(\"HelloWorld\")\nHelloWorld\n```\n\n\nWhitespace is ignored by the compiler when used around numeric expressions. \n```java\n\n\tjshell\u003e System.out.println(24 * 60 * 60)\n\t86400\n\tjshell\u003e System.out.println(24    *    60    *    60)\n\t86400\n\tjshell\u003e\n\n```\n\n#### Case Sensitive\n\nJava is case sensitive.\n\n```System.out.println()``` involve pre-defined Java elements : the ```System``` **class** name, the ```out``` **variable** name,and the  ```println``` **method** name. All are *case-sensitive*. If any character in these names is used with a different case, you get an error. \n\n```java\n\n\tjshell\u003e system.out.println(\"Hello World\")\n\t| Error:\n\t| package system does not exist\n\t| system.out.println(\"Hello World\")\n\t| ^-------^\n\n\tjshell\u003e System.Out.println(\"Hello World\")\n\t| Error:\n\t| cannot find symbol\n\t| symbol: variable Out\n\t| System.Out.println(\"Hello World\")\n\t| ^------------^\n\n\tjshell\u003e System.out.Println(\"Hello World\")\n\t| Error:\n\t| cannot find symbol\n\t| symbol: method Println(java.lang.string)\n\t| System.out.Println(\"Hello World\")\n\t| ^---------------------^\n\n\tjshell\u003e\n\n```\n\n Inside a string literal, the case of characters do not cause errors. The literal will be taken in and printed, as-is.\n\n```java\njshell\u003e System.out.println(\"hello world\")\nhello world\njshell\u003e System.out.println(\"HELLO WORLD\")\nHELLO WORLD\n```\n\n#### Escape Characters\n\nAn **escape character** is a special symbol, used with another regular symbol to form an **escape sequence**. In Java, the '```\\```' (*back-slash*) character plays the role of an escape character. This escape sequence changes the original usage of the symbols.\n\nIf you want to print the string **delimiter**, the ```\"``` character, you need to escape it with a ```\\```. Without it, a ```\"``` character within a string literal causes an error!\n\n```java\n\n\tjshell\u003e System.out.println(\"Hello \"World\")\n\t| Error:\n\t| ')' expected\n\t| System.out.println(\"Hello \"World\")\n\t|                            ^\n\n\tjshell\u003e System.out.println(\"Hello \\\"World\")\n\tHello \"World\n\tjshell\u003e\n\n```\n\nThe escape sequence ```\\n``` inserts a *newline*.\n```java\n\njshell\u003e System. out.println(\"Hello \\n World\")\nHello\n World\njshell\u003e System.out.println(\"Hello n World\")\nHello n World\njshell\u003e System.out.println(\"Hello\\nWorld\")\nHello \nWorld\njshell\u003e\n\n```\n\nThe escape sequence ```\\t``` inserts a *tab*.\n```java\n\n\tjshell\u003e System.out.println(\"Hello \\t World\")\n\tHello    World\n\tjshell\u003e System.out.println(\"Hello t World\")\n\tHello t World\n\tjshell\u003e System.out.println(\"Hello\\tWorld\")\n\tHello    World\n\tjshell\u003e\n\n```\n\nHow do you print a ```\\```?\n\n```\njshell\u003e System.out.println(\"Hello \\ World\")\n|  Error:\n|  illegal escape character\n|  System.out.println(\"Hello \\ World\")\n```\n\nYou would need to escape it with another ```\\```. Printing ```\\\\``` outputs  the symbol ```\\``` to the console.\n\n```java\n\n\tjshell\u003e System.out.println(\"Hello \\\\ World\")\n\tHello \\ World\n\tjshell\u003e System.out.println(\"Hello \\\\\\\\ World\")\n\tHello \\\\ World\n\n```\n\n\n#### Summary\n\nIn this step, we:\n\n* Were introduced to method call syntax, with ```System.out.println()```\n* Discovered the uses of whitespace characters\n* Learned about Java escape sequences \n\n### Step 11: More On Method Calls\n\nLet's look at method calls with a few more examples.\n\nYou know how to invoke a method with a single argument, courtesy ```System.out.println(3*4)```. Other scenarios do exist, such as \n* Calling a method without any arguments\n* Calling a method with several arguments\n\nLet's check them out, using the built-in methods in Java ```Math``` class. \n\n\n#### Method without parameters\n\nIn method calls, parentheses are a necessary part of the syntax. Don't leave them out!\n\n```Math.random()``` prints a random real number in the range ```[0 .. 1]```, a different one on each call\n\n```java\n\n\tjshell\u003e Math.random\n\t| Error:\n\t| cannot find symbol\n\t|    symbol: Math.random\n\t| Math.random\n\t| ^------------- ^\n\tjshell\u003e Math.random()\n\t$1 ==\u003e 0.0424279106074651_\n\tjshell\u003e Math.random()\n\t$2 ==\u003e 0.8696879746593543 \n\tjshell\u003e Math.random()\n\t$3 ==\u003e 0.8913591586787125\n```\n\n\n#### Method with multiple parameters\n\nHow do we call ```Math.min``` with two parameters ```23``` and ```45```?\n\n```java\n\n\tjshell\u003e Math.min 23 45\n\t| Error\n\t| cannot find symbol\n\t| symbol: variable min\n\t| Math.min 23 45\n\t| ^---------^\n\tjshell\u003e Math.min(23 45)\n\t| Error\n\t| ')' expected\n\t| Math.min 23 45\n\t| ---------------^\n```\n\nWhile making method calls, the programmer must \n* Enclose all the parameters within parentheses\n* Separate individual parameters within the list, using the comma symbol '```,```'.\n\n```java\n\tjshell\u003e Math.min(23, 45)\n\t$4 ==\u003e 23\n\tjshell\u003e Math.min(23, 2)\n\t$5 ==\u003e 2\n\tjshell\u003e Math.max(23, 45)\n\t$6 ==\u003e 45\n\tjshell\u003e Math.max(23, 2)\n\t$7 ==\u003e 2\n\tjshell\u003e\n\n```\n\n```Math.min()``` returns the minimum of two given numbers. ```Math.max()``` returns the maximum of two given numbers.\n\n\n#### Summary\n\nIn this step, we:\n* Understood how zero, or multiple parameters are passed during a method call\n\n### Step 12: More Formatted Output\n\n```System.out.println()``` can accept one value as an argument at a maximum. \n\nTo display the multiplication table for ```5``` with a calculated value, we need a way to print both numbers and strings. \n\nFor this we would need to use another built-in method ```System.out.printf()```.\n\nWhen ```System.out.printf()``` is called with a *single* string argument, it prints some illegible information. For now, it suffices to know, that this information is about the built-in type  ```java.io.PrintStream```.\n\n```java\n\tjshell\u003e System.out.printf(\"5 * 2 = 10\")\n\t5 * 2 = 10$1 ==\u003e java.io.PrintStream@4e1d422d\n\tjshell\u003e\n\n```\n\nThe good news is, that if we call the ```println()``` method on this, the illegible stuff disappears.\n\n```java\n\n\tjshell\u003e System.out.printf(\"5 * 2 = 10\").println()\n\t5 * 2 = 10\n```\n\nThe method ```System.out.printf()``` accepts a variable number of arguments:\n* The first argument specifies the print format. This is a string literal, having zero or more **format specifiers**. A format specifier is a predefined literal (such as ```%d```), that formats data of a particular type (```%d``` formats data of type ```int```).\n* The trailing arguments are expressions,\n\nLots of theory? Let's break it down.  Let's look at an example.\n```java\n\tjshell\u003e System.out.printf(\"5 * 2 = %d\", 5*2).println()\n\t5 * 2 = 10\n\tjshell\u003e\n\n```\n```System.out.printf(\"5 * 2 = %d\", 5*2).println()``` gives an output ```5 * 2 = 10```.  ```%d``` is replaced by the calculated value of ```5*2```.\n\nLet's play a little more with ```printf```:\n\n```java\n\n\tjshell\u003e System.out.printf(\"%d %d %d\", 5, 7, 5).println()\n\t5 7 5\n```\n\nLet's try to display a calculated value. In the example below ```5*7``` is calculated as ```35```.\n```java\n\tjshell\u003e System.out.printf(\"%d %d %d\", 5, 7, 5*7).println()\n\t5 7 35\n```\n\nLet's use this to print the output in the format that we want to use for multiplication table:\n\n```java\n\tjshell\u003e System.out.printf(\"%d * %d = %d\", 5, 7, 5*7).println()\n\t5 * 7 = 35\n```\n\nCongratulations. We are able to calculate ```5*7``` and print ```5 * 7 = 35``` successfully.\n\n#### Exercise\n\n1. Print the following output on the console: ```5 + 6 + 7 = 18```. Use three literals ```5```, ```6```, ```7```. Calculate 18 as ```5 + 6 + 7```.\n\n#### Solution\n\n```java\n\n\tjshell\u003e System.out.printf(\"%d + %d + %d = %d\", 5, 6, 7, 5 + 6 + 7).println()\n\t5 + 6 + 7 = 18\n\tjshell\u003e\n\n```\n\n#### Playing with ```System.out.printf()```\n\nIn the example below, there are four format specifiers (```%d```) and only three value arguments ```5, 6, 7```.\n\n```java\n\n\tjshell\u003e System.out.printf(\"%d + %d + %d = %d\", 5, 6, 7).println()\n\t5 + 6 + 7 = | java.util.MissingFormatArgumentException thrown: Format specifier '%d'\n\t| at Formatter.format (Formatter.java:2580)\n\t| at PrintStream.format (PrintStream.java:974)\n\t| at PrintStream.printf (PrintStream.java:870)\n\t| at (#52:1)\n```\n\nIn a call to ```System.out.printf()```, if the number of format specifiers exceeds the number of trailing arguments, the Java run-time throws an *exception*.\n\n\nIf the number of format specifiers is less than the number of trailing arguments, the compiler simply ignores the excess ones.\n\n```java\n\n\tjshell\u003e System.out.printf(\"%d + %d + %d\", 5, 6, 7, 8).println()\n\t5 + 6 + 7\n\tjshell\u003e\n\n```\n\n#### More Format Specifiers\n\nString values can be printed in ```System.out.printf()```, using the format specifier ```%s```.\n\n```java\n\n\tjshell\u003e System.out.printf(\"Print %s\", \"Testing\").println()\n\tPrint Testing\n\n```\n\nEarlier, we used %d to print an ```int``` value. You cannot use %d to display floating point values. \n```java\n\tjshell\u003e System.out.printf(\"%d + %d + %d\", 5.5, 6.5, 7.5).println()\n\t| java.util.IllegalFormatConversionException thrown: d != java.lang.Double\n\t| at Formatter$FormatSpecifier.failedConversion(Formatter.java:4331)\n\t| at Formatter$FormatSpecifier.printInteger(Formatter.java:2846)\n\t| at Formatter$FormatSpecifier.print(Formatter.java:2800)\n\t| at Formatter.format(Formatter.java:2581)\n\t| at PrintStream.format(PrintStream.java:974)\n\t| at PrintStream.print(PrintStream.java:870)\n\t| at #(57:1)\n\n```\n\nFloating point literals (or expressions) can be formatted using ```%f```.\n```java\n\n\tjshell\u003e System.out.printf(\"%f + %f + %f\", 5.5, 6.5, 7.5).println()\n\t5.500000 + 6.500000 + 7.500000\n\tjshell\u003e\n\n```\n\n#### Summary\n\nIn this step, we:\n\n* Discovered how to do formatted output, using ```System.out.printf()```\n* Stressed on the number and sequence of arguments for formatting\n* Explored the built-in format specifiers for primitive types\n\n### Step 13: Introducing Variables\n\nIn the previous steps, we worked out how to print a calculated value as part of our multiplication table.\n\n```java\n\tjshell\u003e System.out.printf(\"%d * %d = %d\", 5, 1, 5 * 1).println()\n\t5 * 1 = 5\n```\n\n**How do we print the entire multiplication table?**\n\nWe can do something like this.\n\n```java\n\tjshell\u003e System.out.printf(\"%d * %d = %d\", 5, 1, 5 * 1).println()\n\t5 * 1 = 5\n\tjshell\u003e System.out.printf(\"%d * %d = %d\", 5, 2, 5 * 2).println()\n\t5 * 2 = 10\n\tjshell\u003e System.out.printf(\"%d * %d = %d\", 5, 3, 5 * 3).println()\n\t5 * 3 = 15\n\tjshell\u003e System.out.printf(\"%d * %d = %d\", 5, 4, 5 * 4).println()\n\t5 * 4 = 20\n\tjshell\u003e\n\n```\n\nToo much work. Isn't it?\n\nIf you carefully observe the code, these statements are very similar. \n\n***What's changing?*** The number in the third and fourth parameter slots changes from 1 to 4.\n\nWouldn't it be great to have something to represent the changing value? \n\n***Welcome variables.***\n\n```java\n\n\tjshell\u003e int number = 10\n\tnumber ==\u003e 10\n\tjshell\u003e\n\n```\n\n#### Terminology and Background\n\nIn the statement ```int number = 10```,  \n* ```number``` is a **variable**. \n* The literal ```number``` is the variable **name**.\n* The Java *keyword* ```int``` specifies the **type** of ```number```.\n* The literal ```10``` provided ```number``` with an **initial value**. \n* This entire statement is a **variable definition**.\n\nThe effects of this variable definition are:\n* A specific location in the computer's memory is reserved for ```number```.\n* This location can now hold data of type ```int```.\n* The value ```10``` is stored here.\n\nYou can change the value of number variable:\n```java\n\n\tjshell\u003e number = 11\n\tnumber ==\u003e 11\n```\n\nAbove statement is called  variable **assignment**. \n\nAn assignment causes the value stored in the memory location to change. In this case, ```10``` is replaced with the value ```11```.\n\nYou can look up the value of number variable.\n```java\n\tjshell\u003e number\n\tnumber ==\u003e 11\n```\n\nYou can change the value of a variable multiple times.\n```\n\tjshell\u003e number = 12\n\tnumber ==\u003e 12\n\tjshell\u003e number\n\tnumber ==\u003e 12\n\n```\n\nLet's create another variable:\n\t\n```java\n\n\tjshell\u003e int number2 = 100\n\tnumber2 ==\u003e 100\n\tjshell\u003e number2 = 101\n\tnumber2 ==\u003e 101\n\tjshell\u003e number2\n\tnumber2 ==\u003e 101\n\tjshell\u003e\n\n```\n\nThe statement ```int number2 = 100``` defines a *distinct* variable ```number2```. \n\n***How do we use variables to simplify and improve the solution to *PMT-Challenge*?*** \n\nLet's take a look.\n\n```java\n\n\tjshell\u003e System.out.printf(\"%d * %d = %d\", 5, 4, 5*4).println()\n\t5 * 4 = 20\n```\n\nLet's define a variable ```i```, and initialize it to ```1```.\n```java\n\tjshell\u003eint i = 1\n\ti ==\u003e 1\n\tjshell\u003e i\n\ti ==\u003e 1\n\tjshell\u003e 5*i\n\t$1 ==\u003e 5\n```\n\nLet's update the multiplication table printf to use the variable i.\n```java\n\tjshell\u003e System.out.printf(\"%d * %d = %d\", 5, i, 5*i).println()\n\t5 * 1 = 5\n```\n\n***How do we print ```5 * 2 = 10```?***\n\nWe update ```i``` to ```2``` and execute the same code as before. \n\n```java\n\n\tjshell\u003e i = 2\n\ti ==\u003e 2\n\tjshell\u003e 5*i\n\t$2 ==\u003e 10\n\tjshell\u003e System.out.printf(\"%d * %d = %d\", 5, i, 5*i).println()\n\t5 * 2 = 10\n\tjshell\u003e\n\n```\n\nYou can update the value of ```i``` to any number. \n\nThe previous statement would print the corresponding multiple with 5.\n\n```java\n\n\tjshell\u003e i = 3\n\ti ==\u003e 3\n\tjshell\u003e System.out.printf(\"%d * %d = %d\", 5, i, 5*i).println()\n\t5 * 3 = 15\n\tjshell\u003e i = 10\n\ti ==\u003e 10_\n\tjshell\u003e System.out.printf(\"%d * %d = %d\", 5, i, 5*i).println()\n\t5 * 10 = 50\n\tjshell\u003e\n\n```\n\nBy varying the value of ```i```, we are able to print different multiples of 5 with the same statement.\n\nCongratulations! You made a major discovery. Variables.\n\n#### Summary\n\nIn this step, we:\n\n* Understood the need for variables\n* Observed what different parts of a variable definition mean\n* Seen what goes on behind-the-scenes when a variable is defined\n\n### Step 14: Programming Exercise PE-03 (With solution)\n\n1. Create three integer variables ```a```, ```b``` and ```c```. \n\t* Write a statement to print the sum of these three variables.\n\t* Change the value of ```a```, and then print this sum.\n\t* Then again, change the value of ```b``` and print this sum.\n\n#### Solution to PE-03\n\n```java \n\n\tjshell\u003eint a = 5\n\ta ==\u003e 5\n\tjshell\u003eint b = 7\n\tb ==\u003e 7\n\tjshell\u003eint c = 11\n\tc ==\u003e 11\n\tjshell\u003eSystem.out.printf(\"a + b + c = %d\", a+b+c).println()\n\ta + b + c = 23\n\tjshell\u003ea = 2\n\ta ==\u003e 2\n\tjshell\u003eSystem.out.printf(\"a + b + c = %d\", a+b+c).println()\n\ta + b + c = 20\n\tjshell\u003eb = 9\n\tb ==\u003e 9\n\tjshell\u003eSystem.out.printf(\"a + b + c = %d\", a+b+c).println()\n\ta + b + c = 22\n\tjshell\u003e\n\t\n```\n\n### Step 15: Using Variables\n\nVariables should be declared before use.\n\n```java\n\n\tjshell\u003enewVariable\n\t| Error:\n\t| cannot find symbol\n\t| symbol: newVariable\n\t| newVariable\n\t  ^------------^\n```\n\nJava is a **strongly typed** programming language. This means two things:\n* Every variable in a program must be declared, with a type.\n* Values assigned to a variable should be:\n\t* same type as the variable's type, or\n\t* **compatible** with the variable's type\n\n```java\n\n\tjshell\u003e int number = 5.5\n\t| Error:\n\t| incompatible types: possible lossy conversion from double to int\n\t| int number = 5.5\n\t|_____________^---^\n\tjshell\u003e\n\n```\n\nThe variable ```number``` is an integer, mathematically a  number. The constant ```5.5``` is a number as well. \n\nWhy does it result in error?\n\t\n```5.5``` is a floating-point number of type ```double```. We are trying to store a ```double``` inside a memory slot meant for ```int```.\n\nLet's consider another example:\n\n```java\n\n\tjshell\u003e int number = \"Hello World\"\n\t| Error:\n\t| incompatible types: java.lang.String cannot be converted to int\n\t| int number = \"Hello World\"\n\t|_____________^--------------^\n\tjshell\u003e\n\n```\n```number``` is an ```int``` variable, and we are trying to store a ```String``` value ```\"Hello World\"```. ***Not allowed.***\n\n#### Summary\n\nIn this step, we:\n\n* Observed how declaring a variable is important\n* Understood the compatibility rules for basic Java types  \n\n### Step 16: Variables: Behind-The-Scenes\n\nGiving a value to a variable, during its declaration, is called its initialization. \n\n```java\n\n\tjshell\u003e int number = 5\n\tnumber ==\u003e 5\n\tjshell\u003e\n\n```\n\nThe statement ```int number = 5``` combines a declaration and the initialization of ```number```.\n\nThe next statement ```int number2 =  number``` is a little different. \n\n```java\n\n\tjshell\u003e int number2 = number\n\tnumber2 ==\u003e 5\n\tjshell\u003e number2\n\tnumber2 ==\u003e 5\n\tjshell\u003e\n\n```\n\nThe initial value for ```number2``` is another variable, which is previously defined (```number```). \n\nHere's what goes on behind the scenes with ```int number2 = number```:\n* A memory slot is allocated for ```number2``` with size of ```int```.\n* Value stored in ```number```'s slot is copied to ```number2```'s slot.\n\nIn example below, ```a = 100```, ```c = a + b```, ``` a = c``` are called ```assignments```.\n\n```java\n\n\tjshell\u003e int a = 5\n\ta ==\u003e 5\n\tjshell\u003e int b = 10\n\tb ==\u003e 10\n\tjshell\u003e a = 100\n\ta ==\u003e 100\n\tjshell\u003e int c\n\tc ==\u003e 0\n\tjshell\u003e c = a + b\n\tc ==\u003e 110\n\tjshell\u003e a = c\n\ta ==\u003e 110\n\tjshell\u003e int d = b + c\n\td ==\u003e 120\n\tjshell\u003e\n\n```\n\nVariable **assignment** is allowed to happen in multiple ways:\n* From a literal value, to a variable, having compatible types. The statement ```a = 100``` is one such example.\n* From a variable to another variable, of compatible types.The statement ```a = c``` illustrates this case.\n* From a variable expression to a variable. This expression can be formed with  variables and literals of compatible types, and is evaluated before the assignment. The statement ```c = a + b```below is an example of this.\n\nAn assignment to a constant literal is **not allowed**. \n```java\n\n\tjshell\u003e 20 = var\n\t| Error:\n\t| unexpected type\n\t| required : variable\n\t| found : value\n\t| 20 = var\n\t| ^^\n\n\tjshell\u003e\n\n```\n \n#### Summary\n\nIn this step, we discussed how to provide variables with initial values and the basics of assigment.\n\n### Step 17: Naming Variables \n\nThe syntax rules for variable definition are quite strict. Do we have any freedom with the way we name variables? The answer is \"yes\", to some extent. \n\n### Variable Name Rules\n\nHere are the Java rules for variable names, in a nutshell:\n\nA variable name can be a sequence, in any order, of\n* Letters [```A-Z, a-z```]\n* Numerical digits [```0-9```]\n* The special characters '```$```' (\"dollar\") and '```_```' (\"underscore\")\n\nWith the following exceptions:\n* The name cannot start with a numerical digit [```0-9```]\n* The name must not match with a predefined Java **keyword**\n\nLet's now see what kinds of errors the compiler throws if you violate these naming rules.\n\n***Error : Using a invalid character ```-```***\n\n```java\n\n\tjshell\u003e int test-test\n\t| Error:\n\t| ';' expected\n\t| int test-test\n\t|         ^\n\n```\n\n***Error : Starting name of a variable with a number***\n\n```java\n\n\tjshell\u003e int 2test\n\t| Error:\n\t| '.class' expected \n\t| int 2test\n\t|     ^\n\t| Error:\n\t| not a statement\n\t| int 2test\n\t|      ^--^\n\t| Error:\n\t| unexpected type\n\t| required: value\n\t| found: class\n\t| int 2test\n\t| ^--^\n\t| Error:\n\t| missing return statement\n\t| int 2test\n\t| ^-------^\n\n\tjshell\u003e\n\n```\n\n***Error : Using a keyword as the name of variable***\n\nIn Java, certain special words are called ```keywords```. For example, some of the data types we looked at - ```int```, ```double```. These ```keywords``` cannot be used as variable names.\n\n```java\n\n\tjshell\u003e int int\n\t   ...\u003e ;\t\n\t| Error:\n\t| '.class' expected\n\t| int int\n\t|     ^\n\t| Error:\n\t| unexpected type\n\t| required: value\n\t| found: class\n\t| int int\n\t| ^--^\n\t| Error:\n\t| missing return statement\n\t| int int\n\t| ^------...\n\n```\n\n### Variable Naming Conventions\n\nGood programmers write readable code. Giving proper names to your variables makes your code easy to read. \n\nIn a football scorecard application, using a name ```s``` for a score variable is vague. Something like ```score``` carries more meaning, and is preferred.\n```java\n\n\tjshell\u003e int s\n\ts ==\u003e 0\n\tjshell\u003e int score\n\tscore ==\u003e 0\n\tjshell\u003e\n\n```\n\n\u003e The Java community, with its wealth of experience, *suggests* that programmers follow some **naming conventions**. Above examples is one of these. Violation of these rules does not result in compilation errors. That's why, these are called **conventions**.\n\nIn Java, another convention is to use **CamelCase** when we have multiple words in variable name.\n```java \n \n\tjshell\u003e int noOfGoals\n\tnoOfGoals ==\u003e 0\n\n```\n\n```noOfGoals``` is easier to read than ```noofgoals```.\n\nBoth ```noOfGoals``` and ```NoOfGoals``` are equally readable. \n\nBut in Java, the convention followed is to start variable names with a lower case letter. So, for a variable, ```noOfGoals``` is preferred. \n\n*** NOT RECOMMENDED*** \n```\n\tjshell\u003e int NoOfGoals\n\tNoOfGoals ==\u003e 0\n```\n\nYour variable names can be very long. \n\n```java\n\n\tjshell\u003e int iThinkThisIsQuiteALongName\n\tiThinkThisIsQuiteALongName ==\u003e 0\n\tjshell\u003e int iThinkThisIsSuchALongNameThatIMightNeverUseSuchALongNameAgain\n\tiThinkThisIsSuchALongNameThatIMightNeverUseSuchALongNameAgain ==\u003e 0\n\n```\n\nHowever, avoid using very long variable names.\n\n***Use the shortest meaningful and readable name possible for your variables.***\n\n#### Summary\n\nIn this step, we:\n\n* Explored the Java language rules for variable names\n* Understood that there are conventions to guide us\n* Looked at a popular variable naming conventions\n\n### Step 18: Introducing Primitive Types\n\nThe table below lists the **primitive types** in Java.\n\n| Type of Values | Java Primitive Type | Size (in bits) | Range of Values | Example |\n| :---: | :---: |:---: |:---: |:---:|\n| Integral Values |byte|8|```-128``` to ```127```|```byte b = 5;```|\n| Integral Values |short|16|```-32,768``` to ```32,767```|```short s = 128;```|\n| Integral Values |int|32|```-2,147,483,648``` to ```2,147,483,647```|```int i = 40000;```|\n| Integral Values |long|64|```-9,223,372,036,854,775,808``` to ```9,223,372,036,854,775,807```|```long l = 2222222222;```|\n|Floating-Point Values| float| 32 | approximately ±3.40282347E+38F. NOT very precise (avoid for financial/scientific math)|```float f = 4.0f;```|\n|Floating-Point Values|double|64| approximately ±1.79769313486231570E+308. NOT very precise, but better than float (also avoid for financial/scientific  math)|```double d = 67.0;```|\n|Character Values|char|16|```'\\u0000``` to ```'\\uffff```|```char c = 'A';```|\n|Boolean Values| boolean|1| ```true``` or ```false```|```boolean isTrue = false;```|\n\nLet's now look at how we create data of these types, and store them in memory.\n\nWe choose type for data, based on:\n* The type of data we want to store\n* The range of values we would want to store\n\n\u003e Note: In the above examples, we used semi-colon ```;``` character at the end. This is the Java **statement separator**, which is not mandatory in ```JShell``` for single statements. However, it is a must when you use *code editors* and *IDE*'s, to write Java code.\n\n#### Integer Types\n\nThe only difference among the integer types is their storage capacity.\n\n```java\n\n\tjshell\u003e byte b = 5\n\tb ==\u003e 5\n\tjshell\u003e short s = 128\n\ts ==\u003e 128\n\tjshell\u003e int i = 40000\n\ti ==\u003e 40000\n\tjshell\u003e long l = 2222222222\n\tl ==\u003e 2222222222\n\tjshell\u003e\n\n```\n\n#### Floating Value Types\n\n```double``` is the default type for floating type values with size 64 bits. \n\n```\n\tjshell\u003e double d = 67.0\n\td ==\u003e 67.0\n```\n\n```float``` occupies 32 bits. ```float``` literals need to have a suffix '```f```' (as in ```4.0f```).\n\n```\n\n\tjshell\u003e float f = 4.0f\n\tf ==\u003e 4.0\n```\n\nIf this suffix ```f``` is omitted, a floating-point  number is assumed to be a ```double```. You cannot store a 64 bit value into 32 bits.\n```java\n\tjshell\u003e float f2 = 4.0\n\t| Error:\n\t| incompatible types: possible lossy conversion from double to float\n\t| float f2 = 4.0\n\t|            ^-^\n\n```\n\nYou can store ```float``` value in ```double```. Remember, both types store similar kind of values and a ```float``` value is only 32 bits where as ```double``` has 64 bits.\n```\n\tjshell\u003e double d2 = 67.0f\n\td2 ==\u003e 67.0\n```\n\n#### Character Type\n\nThe character type ```char``` can store a single character symbol. The symbol must be enclosed within a pair of single quotes, ```'``` and ```'```.\n\n```java\n\n\tjshell\u003e char c = 'A'\n\tc ==\u003e 'A'\n```\n\nFollowing are a few char declaration errors: Not using single quotes and trying to store multiple characters.\n```\n\tjshell\u003e char ch = A\n\t| Error:\n\t| cannot find symbol\n\t| symbol: variable A\n\t| char ch = A\n\t|           ^\n\n\tjshell\u003e char cab = 'AB'\n\t| Error:\n\t| unclosed character literal\n\t| char cab = 'AB'\n\t|            ^\n\n```\n\n#### Boolean Type\n\nThe concept of a ```boolean``` type is rooted in mathematical logic. The data type can store two possible values, ```true``` and ```false```. Both are case-sensitive labels, but  not enclosed in  quotes. \n\n```java\n\n\tjshell\u003e boolean isTrue = false\n\tisTrue ==\u003e false\n\tjshell\u003e isTrue = true\n\tisTrue ==\u003e true\n\tjshell\u003e boolean isFalse = True\n\t| Error:\n\t| cannot find symbol\n\t| symbol: variable True\n\t| boolean isFalse = True\n\t|                   ^--^\n\n\tjshell\u003e isFalse = False\n\t| Error:\n\t| cannot find symbol\n\t| symbol: variable False\n\t| isFalse = False\n\t|           ^---^\n\n```\n\n```boolean``` data are mostly used in expressions used to form logical conditions in your code. We will talk more about this - when we explore Java conditionals.\n\n\n#### Summary\n\nIn this step, we:\n\n* Looked at the primitive data types provided in Java\n* Understood the categories into which these types are divided\n* Saw what kind of data can be stored in each primitive type\n\n### Step 19: Choosing A Data Type\n\nHow do we choose the data type for a variable? Let's look at a few examples.\n\n#### Example 1 : Goals in a Football match\n\nConsider a sports broadcaster that writes a program to track football scores. In a football game there are two teams playing. A game is generally 90 minutes long, with extra time pushing it to 120 minutes at the most. Practically speaking, the scorelines are never huge. From a practical standpoint, the number of goals scored in a match would never exceed 7200 (the number of seconds in 120 minutes). Playing it a bit safe, a ```short``` data type would be enough to store the score of each side (though a ```byte``` would be more than enough).\n\n```java\n\n\tjshell\u003e short numTeamAGoals = 0\n\tnumTeamAGoals ==\u003e 0\n\tjshell\u003e short numTeamBGoals = 0\n\tnumTeamBGoals ==\u003e 0\n\tjshell\u003e\n\n```\n\n#### Example 2 : How do we store population of the world?\n\nWe know that the global count of humans is well over 7 billion now, so the only integer data type that can store it is a ```long```.\n\n```java\n\n\tjshell\u003e long globalPopulation = 7500000000;\n\tglobalPopulation ==\u003e 7500000000\n\tjshell\u003e\n\n```\n\n#### Example 3 : How do we store average rainfall in a month?\n\nRainfall is usually measured in millimeters (*mm*), and we know computing an average over 30 days is very likely to yield a floating-point number. Hence we can use a ```float```, or for more accuracy, a ```double``` to store that average.\n\n```java\n\n\tjshell\u003e float avgJanRainfall = 31.77f;\n\tavgJanRainfall ==\u003e 31.77\n\tjshell\u003e double averageJanRainfall = 31.77\n\taverageJanRainfall ==\u003e 31.77\n\tjshell\u003e\n\n```\n#### Example 4 : Grades of a Student\n\nClassroom grades in high school are generally A, B, C , .... \n\nFor a program that generates a grade report, a ```char``` type would be the best bet.\n\n```java\n\n\tjshell\u003e char gradeA = 'A'\n\tgradeA ==\u003e 'A'\n\tjshell\u003e char gradeB = 'B'\n\tgradeB ==\u003e 'B'\n\tjshell\u003e char gradeC = 'C'\n\tgradeC ==\u003e 'C'\n\tjshell\u003e char gradeD = 'D'\n\tgradeD ==\u003e 'D'\n\tjshell\u003e char gradeF = 'F'\n\tgradeF ==\u003e 'F'\n\tjshell\u003e\n\n```\n\n#### Example 5 : Is a Number Odd or Even?\n\nA ```boolean isNumEven``` is a good bet, with a default initial value of ```false```. It can be changed to ```true``` if the number turns out to be even.    \n\n```java\n\n\tjshell\u003e boolean isNumEven\n\tisNumEven ==\u003e false\n\tjshell\u003e isNumEven = true\n\tisNumEven ==\u003e true\n\tjshell\u003e\n\n```\n\n#### Summary\n\nIn this step, we:\n\n* Understood how to think while choosing a data type\n* Explored cases for integer, floating-point, character and boolean data\n\n### Step 20: The Assignment Operator ```=```\n\nWe were first exposed to the assignment operator while discussing variable assignment. \n\nWe are allowed to use expressions to assign values to variables, using code such as ```c = a + b```. \n\nLet's look at a few additional ways assignment can be done.\n\n```java\n\n\tjshell\u003e int i = 10\n\ti ==\u003e 10\n\tjshell\u003e int j = 15\n\tj ==\u003e 15\n\tjshell\u003e i = j\n\ti ==\u003e 15\n\tjshell\u003e\n\n```\n\nLet's consider the following example:\n```java\n\tjshell\u003e i = i * 2\n\ti ==\u003e 30\n\tjshell\u003e\n\n```\n\nThe same variable ```i``` appears on both the right-hand-side (*RHS*) and left-hand-side (*LHS*). How would that make any sense? \n\nThe expression on the *RHS* is *independently* evaluated first. The value we get is next copied into the memory slot of the *LHS* variable.\n\nUsing the logic above, the assignment  ```i = i * 2``` actually updates the value of ```i``` (initially ```15```) to ```30``` (doubles it). \n\nJava also does the right thing when it encounters the puzzling statement  ```i = i + i```, where ```i``` is all over the place! The code doubles the value of ```i```, and this reflects on the ```JShell``` output. \n\n```java\n\n\tjshell\u003e i = i + i\n\ti ==\u003e 60\n```\n\nThe next example is self explanatory.\n\n```\n\tjshell\u003e i = i - i\n\ti ==\u003e 0\n```\n\n#### Variable Increment and Decrement\n\nWe have already seen increment by assignment:\n\n```java\n\n\tjshell\u003e int i = 0\n\ti ==\u003e 0\n\tjshell\u003e i = i + 1\n\ti ==\u003e 1\n\tjshell\u003e i = i + 1\n\ti ==\u003e 2\n\tjshell\u003e i = i + 1\n\ti ==\u003e 3\n\tjshell\u003e\n\n```\n\nConversely, the statement ```i = i - 1``` is called a variable **decrement**. This can also be done repeatedly, and ```i``` changes  value every time.\n\n\n```java\n\n\tjshell\u003e i = i - 1\n\ti ==\u003e 2\n\tjshell\u003e i = i - 1\n\ti ==\u003e 1\n\tjshell\u003e i = i - 1\n\ti ==\u003e 0\n\tjshell\u003e\n\t\n```\n\n#### Summary \n\nIn this step, we:\n\n* Looked at the assignment operator ```=``` in a more formal way\n* Looked at heavily used scenarios for assignment, such as increment and decrement\n\n### Step 21: Assignment Puzzles, and *PMT-Challenge* revisited\n\nNow that we understand how to define, assign to, and use variables in expressions, it's time to push the boundaries a bit. The following examples explore how we could play around with variables in our code.\n\n##### Snippet-1 : Pre- and Post- Increment and Decrement\n\nThere are two short-hand versions for increment. ```number++``` denotes *post-increment*. Conversely, ```++number``` means **pre-increment**.\n\nOperator ```++``` can be applied only to variables of integer types, which are ```byte```, ```short```, ```int``` and ```long```.\n\n```number++``` is equivalent to the statement ```number = number + 1```\n\n```java\n\n\tjshell\u003e int number = 5\n\tnumber ==\u003e 5\n\tjshell\u003e number++\n\t$1 ==\u003e 5\n\tjshell\u003e number\n\tnumber ==\u003e 6\n\tjshell\u003e ++number\n\t$2 ==\u003e 7\n\tjshell\u003e number\n\tnumber ==\u003e 7\n\tjshell\u003e\n\n```\n\n```number--``` is *post-decrement*. On the other hand, ```--number``` is **pre-decrement**.\n\n```java\n\n\tjshell\u003e number--\n\t$3 ==\u003e 7\n\tjshell\u003e number\n\tnumber ==\u003e 6\n\tjshell\u003e --number\n\t$4 ==\u003e 5\n\tjshell\u003e number\n\tnumber ==\u003e 5\n\tjshell\u003e\n\n```\n\n***What is the difference between prefix and postfix vesions?***\n\nAlthough both prefix and postfix versions achieve the same visible result in above examples, there is a slight difference. We will explore this later.\n\n##### Snippet-2 : Compound Assignment Operators\n\nThe compound assignment operator combines the ```=``` with a numeric operator. \n\n```i += 2``` : Add ```2``` to the current value of ```i```\n\n```java\n\n\tjshell\u003e int i = 1\n\ti ==\u003e 1\n\tjshell\u003e i = i + 2\n\ti ==\u003e 3\n\tjshell\u003e i += 2\n\t$1 ==\u003e 5\n\tjshell\u003e\n\n```\n\n\n```i -= 1``` : Subtract ```1``` from the current value of ```i```\n\n```java\n\n\tjshell\u003e i\n\ti ==\u003e 5\n\tjshell\u003e i -= 1\n\t$2 ==\u003e 4\n\tjshell\u003e i\n\ti ==\u003e 4\n\tjshell\u003e\n\n```\n\n\n```i *= 4``` : Multiply ```i``` with ```4```, and store the result back into ```i```\n\n```java\n\n\tjshell\u003e i *= 4\n\t$3 ==\u003e 20\n\tjshell\u003e i\n\ti ==\u003e 20\n\tjshell\u003e\n\n```\n\n```i /= 4``` : Divide ```i``` by ```4```, and store the result back into ```i```\n\n```java\n\n\tjshell\u003e i /= 4\n\t$4 ==\u003e 5\n\tjshell\u003e i\n\ti ==\u003e 5\n\tjshell\u003e\n\n```\n\n```i %= 2``` : Divide ```i``` by ```2```, and store the **remainder** back into ```i```\n\n```java\n\n\tjshell\u003e i %= 2\n\t$5 ==\u003e 1\n\tjshell\u003e i\n\ti ==\u003e 1\n\tjshell\u003e\n\n```\n#### Summary\n\nIn the step, we:\n\n* Looked at the built-in Java increment and decrement operators\n* Explored the side-effects of prefix and postfix versions of these operators\n* Seen the advantages of compound assignment\n\n### Step 22: Some ```JShell``` Usage Tips \n\n* Shortcuts\n\t1. Toggling to limits of current prompt entry\n\t\t* '```Ctrl+a```' : to start of line\n\t\t* '```Ctrl+e```' : to end of line\n\t2. Moving up and down history of completed prompt inputs \n\t\t* *up-arrow* key : move back in time\n\t\t* *down-arrow* key : move forward in time\n\t3. Reverse-keyword-search\n\t\t* Search for a term, in reverse order of JShell prompt inputs history : input '```Ctrl+r```'\n\t\t* Scrolling within matches (in reverse order of history) : repeatedly input '```Ctrl+r```'\n* ```/exit``` : resets and exits the JShell session, clearing all stored variables values.\n* JShell internal variables : ```$1```, ```$2```, and so on.\n\t* When expressions involving literals and/or previously declared variables are entered as-is, without assignment, those expressions are still evaluated. The result is stored in such an internal variable, and is available for use until the JShell session is reset.\n* Variable Declaration rules relaxation\n\t1. Single Java statements need not be terminated with the separator '```;```'.\n\t2. If multiple statements are entered on a single line at the prompt, successive statements must be separated by the '```;```'. However, the trailing '```;```' can still be omitted.\n\n#### Summary\n\nIn this step, we:\n\n* Explored some useful keyboard shortcuts for ```JShell``` commands\n* Understood the idea behind ```JShell``` internal variables\n* Observed how ```JShell``` reduces typing effort, by relaxing some coding rules\n\n### Step 23: Introducing Conditionals - the ```if```\n\nThe *PMT-Challenge* needs us to print a total of 10 table entries. The  ```for``` **loop** is a suitable iteration mechanism to get this done. The word *loop* means exactly what the English dictionary says. \n\n*As ```i``` varies from ```1``` through ```10```, do some stuff involving ```i```*\n\nFor the *PMT-Challenge*, ```do some stuff``` would be the call to ```System.out.printf()```.\n\nThe way a ```for``` loop is structured is:\n\n```java\n\n\tfor(initialization; condition; update) {\n\t\tstatement1;\n\t\tstatement2;\n\t}\n\n```\n\nHere's how above code runs\n1. Execute ```initialization``` code. \n2. If ```condition``` evaluates to true, execute ```statements```. Else, go out of loop.\n3. Execute ```update```\n4. Repeat 2 and 3\n\n***Does it sound complex?*** Let's break it down.\n\nLet's start with understanding what ```condition``` is all about.\n\n#### Logical Operators\n\n```condition``` represents a logical value(a ```true``` or  a ```false```). \n\nTurns out Java has a class of **logical operators**, which can be used with operands within **logical expressions**, evaluating to a ```boolean``` value. \n\nWhile in school, you probably used the ```=``` symbol to compare numbers. \n\n***The world of Java is a little different.***  ```=``` is assignment operator. ```==``` is the comparison operator. \n\n```java\n\n\tjshell\u003e int i = 10\n\ti ==\u003e 10\n\tjshell\u003e i == 10\n\t$1 ==\u003e true\n\tjshell\u003e i == 11\n\t$2 ==\u003e false\n\n```\n\nThese are other comparison operators as well, such as ```\u003c``` and ```\u003e```. \n```java\n\n\tjshell\u003e i \u003c 5\n\t$3 ==\u003e false\n\tjshell\u003e i \u003e 5\n\t$4 ==\u003e true\n\n```\n\n```\u003c=``` and ```\u003e=``` are simple extensions.\n\n```java\n\n\tjshell\u003e i \u003c= 5\n\t$4 ==\u003e false\n\tjshell\u003e i \u003c= 10\n\t$5 ==\u003e true\n\tjshell\u003e i \u003e= 10\n\t$6 ==\u003e true\n\tjshell\u003e\n\n```\n\n#### Conditionals: The \"if\" Statement \n\nWe would want to execute specific lines of code only when a condition is true. \n\nEnter ```if``` statement.\n\nAn ```if``` statement is structured this way:\n\n```java\n\n\tif (condition) {\n\t\tstatement;\n\t}\n\n```\n\n```statement``` is executed only if ```condition``` evaluates to ```true```.\n\n\nTypically, all the code that we write is executed always. \n\nIn the example below, ```i is less than 5``` is always printed.  \n\n```java\n\n\tjshell\u003e int i = 10\n\ti ==\u003e 10\n\tjshell\u003e System.out.println(\"i is less than 5\")\n\ti is less than 5\n```\n\nUsing the ```if``` statement, we can control the execution of ```System.out.println(\"i is less than 5\");```.\n\n```java\n\n\tjshell\u003e if (i \u003c 5)\n\t   ...\u003e System.out.println(\"i is less than 5\");\n\tjshell\u003e \n```\n\nThe condition ```i \u003c 5``` will evaluate to ```false```, since ```i``` is currently ```10```. Nothing is printed to console.\n\n\nLet's change ```i``` to ```4``` and execute the ```if``` condition.\n\n```java\n\n\tjshell\u003e i = 4\n\ti ==\u003e 4\n\tjshell\u003e if (i \u003c 5)\n\t   ...\u003e System.out.println(\"i is less than 5\");\n\ti is less than 5\n\tjshell\u003e\n\n```\n\n```i is less than 5``` is printed to console.\n\nBy controlling the value stored in the variable ```i```, we are able to control whether the statement  ```System.out.println(\"i is less than 5\");``` actually runs. \n\n***Hurrah! We just achieved *conditional execution*!***\n\n\nJust as we can compare a variable with a literal, it is possible to compare the values of two variables. The same set of comparison operators, namely ```==```, ```\u003c```, ```\u003e```, ```\u003c=``` and ```\u003e=``` can be used.  \n\n```java\n\n\tjshell\u003e int number1 = 5\n\tnumber1 ==\u003e 5\n\tjshell\u003e int number2 = 7\n\tnumber2 ==\u003e 7\n\tjshell\u003e if (number2 \u003e number1)\n\t   ...\u003e System.out.println(\"number2 is greater than number1\");\n\tnumber2 is greater than number1\n\n\tjshell\u003e number2 = 3\n\tnumber2 ==\u003e 3\n\tjshell\u003e if (number2 \u003e number1)\n\t   ...\u003e System.out.println(\"number2 is greater than number1\");\n\n\tjshell\u003e\n\n```\n\n#### Summary\n\nIn this step, we:\n\n* Understood the need for a conditionals\n* Were introduced to the concept of logical expressions, and conditional operators\n* Explored usage of the Java ```if``` statement\n\n### Step 24: Programming Exercise PE-04 \n- - - \n\n1. Create four integer variables ```a```, ```b```, ```c``` and ```d```. Write an ```if``` statement to print if the sum of ```a``` and ```b``` is greater than the sum of ```c``` and ```d```.\n2. Store three numerical values as proposed angles of a triangle in integer variables ```angle1```, ```angle2``` and ```angle3```. Create an ```if``` statement to state whether these three angles together can form a triangle.\n\n\t_Hint: A triangle is a closed geometric figure with three angles, whose sum must  exactly equal ```180 degrees```._\n3. Have a variable store an integer. Create an ```if``` statement to find out if it's an even number.\n\n\t_Hint: Use operator ```%```._\n\n### Step 25: Solution to PE-04\n\n#### Solution 1\n\n```java\n\n\tjshell\u003e int a = 5\n\ta ==\u003e 5\n\tjshell\u003e int b = 7\n\tb ==\u003e 7\n\tjshell\u003e int c = 4\n\tc ==\u003e 4\n\tjshell\u003e int d = 3\n\td ==\u003e 3\n\tjshell\u003e if (a + b \u003e c + d)\n\t   ...\u003e System.out.println(\"a and b together tower above c plus d\");\n\ta and b together tower above c plus d\n\n\tjshell\u003e\n\n```\n\n#### Solution 2\n\n```java\n\n\tjshell\u003e int angleOne = 55\n\tangleOne ==\u003e 55\n\tjshell\u003e int angleTwo = 65\n\tangleOne ==\u003e 55\n\tjshell\u003e int angleThree = 60\n\tangleOne ==\u003e 55\n\tjshell\u003e if (angleOne + angleTwo + angleThree == 180)\n\t   ...\u003e System.out.println(\"The three angles together form a triangle\");\n\tThe three angles together form a triangle\n\n\tjshell\u003e angleThree = 75\n\tangleOne ==\u003e 55\n\tjshell\u003e if (angleOne + angleTwo + angleThree == 180)\n\t   ...\u003e System.out.println(\"The three angles together form a triangle\");\n\n\tjshell\u003e\n\n```\n\n#### Solution 3\n\n```java\n\n\tjshell\u003e int num = 10\n\tnum ==\u003e 10\n\tjshell\u003e if (num % 2 == 0)\n\t   ...\u003e System.out.println(\"The number is even\");\n\tThe number is even\n\n\tjshell\u003e num++\n\tnum ==\u003e 11\n\tjshell\u003e if (num % 2 == 0)\n\t   ...\u003e System.out.println(\"The number is even\");\n\n\tjshell\u003e\n```\n\n### Step 26:  ```if``` Statement again\n\nLet's look at a few more examples of if statements.\n\n##### Snippet-1 \n\nHere's a basic example of conditional execution.\n\n```java\n\n\tjshell\u003e int i = 5\n\ti ==\u003e 5\n\tjshell\u003e if (i == 5)\n\t   ...\u003e System.out.println(\"i is odd\");\n\ti is odd\n```\n\nLet's add two statements to the second line.\n```java\n\tjshell\u003e if (i == 5)\n\t   ...\u003e System.out.println(\"i is odd\"); System.out.println(\"i is prime\");\n\ti is odd\n\ti is prime\n\n\tjshell\u003e\n\n``` \nBoth text messages are printed out.\n\nLet's change value of ```i``` to ```6``` and execute again.\n\n```java\n\n\tjshell\u003e i = 6\n\ti ==\u003e 6\n\tjshell\u003e if (i == 5)\n\t   ...\u003e System.out.println(\"i is odd\"); System.out.println(\"i is prime\");\n\ti is prime\n\n\tjshell\u003e\n\n```\n\n```i is prime``` is printed to console. Why? \n\nWhy is this statement executed when the condition is ```false```?\n\n\nThe ```if``` statement, by default, binds only to the next statement. \n\nIt does not control the execution of ```System.out.println(\"i is prime\");```, which in fact runs unconditionally, always.\n\nIs there a way we can ensure conditional execution of a two statements? And more than two? \n \n##### Snippet-2 : ```if``` with statement blocks\n\nWe seem to have pulled a rabbit out of the hat here, haven't we! The rabbit lies in the  pair of *braces* : '```{```' and '```}```'. \n\nThey are used to group a sequence of statements together, into a **block**. Depending on the condition value (```true``` or ```false```), either all the statements in this block are run, or none at all. \n\n```java\n\n\tjshell\u003e int i = 5\n\ti ==\u003e 5\n\tjshell\u003e if (i == 5) {\n\t   ...\u003e System.out.println(\"i is odd\");\n\t   ...\u003e System.out.println(\"i is prime\");\n\t   ...\u003e }\n\ti is odd\n\ti is prime\n\n\tjshell\u003e i = 6\n\ti ==\u003e 6\n\tjshell\u003e if (i == 5) {\n\t   ...\u003e System.out.println(\"i is odd\");\n\t   ...\u003e System.out.println(\"i is prime\");\n\t   ...\u003e }\n\n\tjshell\u003e\n\n```\n\nIt is considered good programming practice to *always* use blocks in an ```if``` conditional. Here is an example:\n\n```java\n\n\tif (i == 5) {\n\t\tSystem.out.println(\"i is odd\");\n\t}\n\n```\n\t\nA block can also consist of a single statement! This improves readability of code.\n\n#### Summary\n\nIn this step, we:\n\n* Saw the importance of using statement blocks with ```if``` conditionals\n* Understood how control flow can be made more readable\n\n### Step 27: Introducing Loops: The ```for``` Statement \n\nThe *PMT-Challenge* needs us to print a total of 10 table entries. The  ```for``` **loop** is a suitable iteration mechanism to get this done. \n\nThe word *loop* means exactly what the English dictionary says. \n*As ```i``` varies from ```1``` through ```10```, do some stuff involving ```i```*\n\n```for``` loop is built this way:\n\n```java\n\n\tfor(initialization; condition; update) {\n\t\tstatement1;\n\t\tstatement1;\n\t}\n\n```\n\n***Here's how above code runs:***\n1. Execute ```initialization``` code. \n2. If ```condition``` evaluates to true, execute ```statements```. Else, go out of loop.\n3. Execute ```update```\n4. Repeat 2 and 3\n\nWe've already seen these components in isolation:\n\n* _initialization_ : ```int i = 1```\n* _condition_ : ```i \u003c= 10```\n* _update_ : ```i++```\n\nLet's now put them together to get the bigger picture. Here is how it might look:\n\n```java\n\n\tfor (int i = 1; i \u003c= 10; i++) {\n\t\tSystem.out.println(\"Hello World\");\n\t}\n\n```\n\nThis loop, when executed, prints the message \"Hello World\" on a separate line, for a total of ```10``` times. \n\n##### Snippet-1 : *PMT-Challenge* Solution\n\nWe need to replace the \"Hello World\" message with the console print of a table entry. This print is controlled by ```i``` taking values from ```1``` through ```10```.\n\n```java\n\n\tjshell\u003e int i\n\ti ==\u003e 0\n\tjshell\u003e for (i=0; i\u003c=10; i++) {\n\t   ...\u003e System.out.printf(\"%d * %d = %d\", 5, i, 5*i).println();\n\t   ...\u003e }\n\t5 * 1 = 5\n\t5 * 2 = 10\n\t5 * 3 = 15\n\t5 * 4 = 20\n\t5 * 5 = 2\n\t5 * 6 = 30\n\t5 * 7 = 35\n\t5 * 8 = 40\n\t5 * 9 = 45\n\t5 * 10 = 50\n\n```\n\n##### Snippet-1 Explained \n\n1. The first step is the initialization: ```i = 1```. \n2. After this, the statement ```System.out.printf(\"%d * %d = %d\", 5, i, 5*i).println();```  is executed once. \n3. Then, the update occurs: ```i++```.\n4. Immediately after, the condition ```i\u003c=10``` is evaluated. It returns ```true```. Progress happens. Since it is a ```for``` *loop*, the statement is executed again.\n5. Thereafter, this sequence is executed until ```i``` gets a value of ```11``` (due to successive updates).\n6. The moment ```i``` reaches ```11```, , the condition becomes ```false```. The looping within the ```for``` terminates.\n\nMeanwhile, the Multiplication Table for ```5```, for entries ```1``` through ```10``` has been displayed! \n\nNow, wasn't that really elegant? It sure was! \n\nLet's pat ourselves on the back for having reached this stage of learning. This elegant, yet powerful technique (*loops*) is used in almost every Java program that's written. \n\n#### Summary\n\nIn this step, we:\n\n* Observed why we need a looping construct, such as the ```for```\n* Understood the mechanism of a ```for``` loop\n* Used a ```for``` loop in iteration, to solve our *PMT-Challenge*\n\n### Step 28: Programming Exercise PE-05\n\n1. Repeat the entire process at arriving at the Multiplication Table Print problem, now for the number ```7```. Start with a fresh ```JShell``` session, if you're still using an existing one for quite some time (Rinse, and repeat!).\n2. Use the final solution to print Multiplication Tables for ```6``` and ```10```.\n3. Print the integers from ```1``` to ```10```.\n4. Print the integers from ```10``` to ```1```.\n5. Print the squares of the integers from ```1``` to ```10```.\n6. Print the squares of the first ```10``` even integers.\n7. Print the squares of the first ```10``` odd integers.\n\n### Step 29: Solution to PE-05\n\n#### Solution 2\n\n```java\n\n\tjshell\u003e int i\n\ti ==\u003e 0\n\tjshell\u003e for (i=0; i\u003c=10; i++) {\n\t   ...\u003e System.out.printf(\"%d * %d = %d\", 6, i, 6*i).println();\n\t   ...\u003e }\n\t6 * 1 = 6\n\t6 * 2 = 12\n\t6 * 3 = 18\n\t6 * 4 = 24\n\t6 * 5 = 30\n\t6 * 6 = 36\n\t6 * 7 = 42\n\t6 * 8 = 48\n\t6 * 9 = 54\n\t6 * 10 = 60\n\n\tjshell\u003e i = 0\n\ti ==\u003e 0\n\tjshell\u003e for (i=0; i\u003c=10; i++) {\n\t   ...\u003e System.out.printf(\"%d * %d = %d\", 10, i, 10*i).println();\n\t   ...\u003e }\n\t10 * 1 = 10\n\t10 * 2 = 20\n\t10 * 3 = 30\n\t10 * 4 = 40\n\t10 * 5 = 50\n\t10 * 6 = 60\n\t10 * 7 = 70\n\t10 * 8 = 80\n\t10 * 9 = 90\n\t10 * 10 = 100\n\n```\n\n#### Solution 3\n\n```java\n\n\tjshell\u003e for (int i=1; i\u003c=10; i++) {\n\t   ...\u003e System.out.printf(i).println();\n\t   ...\u003e }\n\t1\n\t2\n\t3\n\t4\n\t5\n\t6\n\t7\n\t8\n\t9\n\t10\n\n```\n\n#### Solution 4\n\nThis is the first time we are using ```i--```. Isn't this interesting?\n\n```java\n\n\tjshell\u003e for (int i=10; i\u003e0; i--) {\n\t   ...\u003e System.out.printf(i).println();\n\t   ...\u003e }\n\t10\n\t9\n\t8\n\t7\n\t6\n\t5\n\t4\n\t3\n\t2\n\t1\n\n```\n\n#### Solution 5\n\n```java\n\n\tjshell\u003e for (int i=1; i\u003c=10; i++) {\n\t   ...\u003e System.out.printf(i*i).println();\n\t   ...\u003e }\n\t1\n\t4\n\t9\n\t16\n\t25\n\t36\n\t49\n\t64\n\t81\n\t100\n\n```\n\n#### Solution 6\n\n```update``` of a for loop can do a lot of things. Here, we are using ```i += 2```.\n\n```java\n\n\tjshell\u003e for (int i=2; i\u003c20; i += 2) \n\t   ...\u003e System.out.printf(i*i).println();\n\t   ...\u003e }\n\t4\n\t16\n\t36\n\t64\n\t100\n\t144\n\t196\n\t256\n\t324\n\t400\n\n```\n\n#### Solution 7\n\n```java\n\n\tjshell\u003e for (int i=1; i\u003c=19; i += 2) {\n\t   ...\u003e System.out.printf(i*i).println();\n\t   ...\u003e }\n\t1\n\t9\n\t25\n\t49\n\t81\n\t121\n\t169\n\t225\n\t289\n\t361\n\n```\n\n### Step 30: Puzzling You With ```for``` \n\nIn the conceptual form of the ```for``` construct:\n\n```java\n\n\tfor (initialization; condition; updation) {\n\t\tstatement;\n\t\tstatement;\n\t\t//...\n\t\tstatement;\n\t}\n\n```\n  \nIt may surprise you that each one of *initialization*, *condition*, *updation* and *statements block* is **optional**. They can all be left out individually, in combination, or all altogether!! Let's examine a few interesting cases in code.\n\n1. Empty initialization, Empty Statement\n\nIncrements the control variable in quick succession until the condition evaluates to false.\n```java\n\n\tjshell\u003e int i = 1\n\ti ==\u003e 1\n\tjshell\u003e for (; i\u003c=10; i++);\n\tjshell\u003e i\n\ti ==\u003e 11\n\tjshell\u003e\n\n```\n\n2. Multiple initializations, Empty Statement\n\nYou can have multiple statements in ```initialization``` and ```update``` separated by ```,```.\n\n```java\n\n\tjshell\u003e int j\n\ti ==\u003e 11\n\tjshell\u003e for (i=1, j=2; i\u003c=10; i++, j++);\n\tjshell\u003e i\n\ti ==\u003e 11\n\tjshell\u003e j\n\tj ==\u003e 12\n\tjshell\u003e\n\n```\n\n\nIn the example below, i is incremented and j is decremented.\n\n```java\n\n\tjshell\u003e for (i=1, j=2; i\u003c=10; i++, j--);\n\tjshell\u003e i\n\ti ==\u003e 11\n\tjshell\u003e j\n\tj ==\u003e -8\n\tjshell\u003e\n\n```\n\n3. Infinite Loop\n\nAn infinite loop is one where the *condition* is left *empty*. An empty condition always evaluates to ```true```. Since a ```for``` loop only terminates when the condition becomes ```false```, such a loop this never terminates. \n\nIt can only be terminated externally with a keyboard interrupt (```CTRL + c```).\n\n```java\n\n\tjshell\u003e for (;;);\n\n\t^C\n\tjshell\u003e\n\n```\n\n\n4. Statement Block in for\n\nAs in case of the ```if``` conditional statement, we can have statement blocks in ```for``` loops as well. As before, we enclose the statement set between braces ('```{```' and '```}```'). The statements are executed repeatedly, in the same order as they appear in the block.\n\n```java\n\n\tjshell\u003e for (i=1; i\u003c=5; i++) {\n\t   ...\u003e System.out.println(\"No 1\");\n\t   ...\u003e System.out.println(\"No 2\");\n\t   ...\u003e }\n\tNo 1\n\tNo 2\n\tNo 1\n\tNo 2\n\tNo 1\n\tNo 2\n\tNo 1\n\tNo 2\n\tNo 1\n\tNo 2\n\n```\n\n\n#### Summary\n\nIn this step, we saw that all components of a ```for``` loop are optional:\n* *initialization*\n* *condition*\n* *updation*\n* *statement block*\n\n### Step 31: A Review Of Basic Concepts\nBefore we go further, let's quickly get a Big Picture of what we are doing here!\n\nA **computer** is a *machine* that does a job for you and me. It is can be used to run tasks that we find complicated, time-consuming, or even boring! For instance, a laptop can play music from a CD, videos from the web, or fire a print job. \n\nWe have mobile phones around us, which are mini versions of computers. Then there are others, ranging from blood-sugar monitors to weather-forecast systems. Computers surround us, wherever we go!\n\nAny computer is made up of two basic layers: \n\n* The **hardware**: Consists of all the *electronic* and *mechanical* parts of the computer, including the *electronic circuits*.\n* The **software**: Describes the *instructions* fed into the computer, which are stored and run on its *hardware*.\n\nIf the human body were a computer,\n\n* Its *hardware* would consist of the various organs (such as limbs, blood and heart)\n* Its *software* would be the signals from the nervous system, which drive these organs.\n\n**Computer programming** involves writing software instructions to run tasks on a computer. The user who gives these instructions is called the **programmer**. Often, computer programming  involves solving challenging, and very interesting problems.\n\n\nIn the previous steps, we introduced you to the basic Java language concepts and constructs.\n\nWe solved a programming challenge, the *PMT-Challenge* using basic Java constructs.\n\nWe used JShell REPL to learn the following concepts, Step by-step:\n* Expressions, Operators and Statements\n* Variables and Formatted Output\n* Conditionals and Loops\n\nAt each step, we applied fresh knowledge to enhance our solution to the *PMT-Challenge*\n\nHope you liked the journey thus far. Next sections delve deeper into Java features, using the same Step by-step approach. We will catch up again soon, hopefully!\n\n## Understanding Methods\n\nFeeling good about where you are right now? You just created an elegant, yet powerful solution to the *PMT-Challenge*, using:\n\n* Operators, variables and expressions\n* Built-in formatted output\n* Conditionals for control-flow, and \n* Iteration through loops\n \nAnd guess what we ended up with? A good-looking display of a Multiplication Table! There's a good chance people in your circles want to see it, use it and maybe share it among their friends. \n\nHowever, some might be unhappy that it works only for ```5```, and not for ```8``` and ```7```. Maybe it would, but then they would need to type in those lines of code again. This might disappoint them, and your new found popularity would slide downhill. \n\nSurely a more elegant solution exists, a pattern waiting to unravel itself.\n\nExist it does, and the mechanism to use it lies with Java **methods**. A ```method``` is a feature that allows you to group together a set of statements, and give it a name. This name represents the *functionality* of that set, which can be re-used when necessary.\n\nA method is essentially a *routine* that performs a certain task, and can do it any number of times it is asked to. It may also return a result for the task it performs. The syntax for a ***method definition*** is along these lines:\n\n```\nReturnType   methodName () {\n  method-body\n}\n\n```\n\nWhere \n\n* ```methodName``` is the name of the routine\n* ```method-body``` is the set of statements\n* a pair of braces ```{``` and ```}``` enclose ```method-body```\n* ```ReturnType``` is the type of ```methodName```'s return value\n\n\n#### Summary\n\nIn this step, we:\n\n* Examined the need for labeling code, and its reuse\n* Learned that a Java method fits the bill\n* Saw how a method definition looks like, conceptually\n\n### Step 01 : Defining A Simple Method\n\nWe will start off, by writing a simple method that prints \"```Hello World```\" twice on your screen.\n\n```java\n\n\tjshell\u003e void sayHelloWorldTwice() {\n\t   ...\u003e System.out.println(\"Hello World\");\n\t   ...\u003e System.out.println(\"Hello World\");\n\t   ...\u003e }\n\t| created method sayHelloWorldTwice()\n\n```\n\nA little bit of theory:\n* Above code for the method is called **method definition**. \n* ```void``` indicates that the method does not return any computed result - We will examine return values from methods, a little later.\n\n***When the code ran, it didn't exactly welcome us twice, did it?*** All we got was a boring message from ```JShell```, mumbling ```created method sayHelloWorldTwice()```. \n\nThat's because defining a method ***does NOT*** execute its statement body.\n\nSince the statement block is not stand-alone anymore, its functionality needs to be **invoked**. This is done by writing a **method call**. \n\nLet's look at a few examples for **method calls**.\n \n```java\n\n\tjshell\u003e sayHelloWorldTwice\n\t| Error:\n\t| cannot find symbol\n\t| symbol: variable sayHelloWorldTwice\n\t| sayHelloWorldTwice\n\t| ^----------------^\n\n\tjshell\u003e sayHelloWorldTwice()\n\tHello World\n\tHello World\n\t\n``` \n\nAll that we had to do was to add parantheses to name of the method.\n\n\u003e The trailing '```;```' can be left out in ```JShell```, and is another example of syntax rules being relaxed.\n\n\u003e Method names need to follow the same rules as variable names.\n\n#### Summary\n\nIn this step we:\n\n* Got our hands dirty coding our first method\n* Learned that defining and invoking methods are two different steps\n\n### Step 02: Exercise-Set PE-01\n\nLet's now reinforce our basic understanding of methods, by trying out a few exercises.\n\n#### Exercise Set -5\n\n1. Write and execute a method named ```sayHelloWorldThrice``` to print ```Hello World``` thrice.\n\n2. Write and execute a method that prints the following four statements:\n\t\n\t```I've created my first variable```\n\n\t```I've created my first loop```\n\t\n\t```I've created my first method```\n\t\n\t```I'm excited to learn Java```\t\n\n#### Solutions to PE-01\n\n#### Solution-1\n\n```java\n\n\tjshell\u003e void sayHelloWorldThrice() {\n\t   ...\u003e System.out.println(\"Hello World\");\n\t   ...\u003e System.out.println(\"Hello World\");\n\t   ...\u003e System.out.println(\"Hello World\");\n\t   ...\u003e }\n\t| created method sayHelloWorldThrice()\n\n\tjshell\u003e sayHelloWorldThrice()\n\tHello World\n\tHello World\n\tHello World\n\n```\n \n#### Solution-2\n\n```java\n \n\tjshell\u003e void sayFourThings() {\n\t   ...\u003e System.out.println(\"I've created my first variable\");\n\t   ...\u003e System.out.println(\"I've created my first loop\");\n\t   ...\u003e System.out.println(\"I've created my first method\");\n\t   ...\u003e System.out.println(\"I'm excited to learn Java\");\n\t   ...\u003e }\n\t| created method sayFourThings()\n\n\tjshell\u003e sayFourThings()\n\tI've created my first variable\n\tI've created my first loop\n\tI've created my first method\n\tI'm excited to learn Java\n\n```\n\n### Step 03: Editing A Method Definition (```Jshell``` Tips)\n\n##### Snippet-01: Editing sayHelloWorldTwice()\n\n```java\n\n\tjshell\u003e void sayHelloWorldTwice() {\n\t   ...\u003e System.out.println(\"Hello World\");\n\t   ...\u003e System.out.println(\"Hello World\");\n\t   ...\u003e }\n\t| created method sayHelloWorldTwice()\n```\n\nThe ```/methods``` command lists out the methods defined in the current session. \n```\n\tjshell\u003e /methods\n\t| void sayHelloWorldTwice()\n\tjshell\u003e\n\n```\n\nThe ```/list``` command lists the code of the specified method.\n\n```java\n\n\tjshell\u003e /list sayHelloWorldTwice\n\t59 : void sayHelloWorldTwice() {\n\tSystem.out.println(\"HELLO WORLD\");\n\tSystem.out.println(\"HELLO WORLD\");\n\t}\n\tjshell\u003e\n\n```\n\n\nThe ```/edit``` command allows you to modify the method definition, in a separate editor window.\n\n```java\n\n\tjshell\u003e /edit sayHelloWorldTwice\n\t| modified method sayHelloWorldTwice\n\tjshell\u003e sayHelloWorldTwice()\n\tHELLO WORLD\n\tHELLO WORLD\n\tjshell\u003e\n\n```\n\nThe ```/save``` method takes a file name as a parameter. When run, it saves the session method definitions to a file.\n\n```java\n\t\n\tjshell\u003e /save backup.txt\n\tjshell\u003e /exit\n\t| Goodbye\n\nin28minutes$\u003e\n\n```\n\n#### Summary\n\nIn this step, we explored a few ```JShell``` tips that make life easier for you while defining methods\n\n### Step 04: Methods with Arguments\n\nWe wrote the method ```sayHelloWorldTwice``` to say ```Hello World``` twice. In the programming exercise, we wanted to print ```Hello World``` thrice and we wrote a new method  ```sayHelloWorldThrice```. \n\nImagine you're in the Java classroom, where your teacher wants to test your Java skills by saying: \n_\"I want you to print_ ***```Hello World```*** _an arbitrary number of times\"_.\n\nNow, that probably would test your patience as well!\n\nHow to write a method to print ```Hello World``` an arbitrary number of times? \n\nThe thing to note is the word \"arbitrary\", which means the method body should have no clue! This number has to come from outside the method, which can only happen with a method call. \n\nExternal input to a method is given as a **method argument**, or *parameter*. \n\nTo support arguments during a call, the concept of a method needs to be tweaked to:\n\n```java\n\n\tReturnType methodName(ArgType argName) {\n\n\t\tmethod-body\n\n\t}\n\n``` \n\nThe only addition to the concept of a method, is the phrase\n\n```ArgType argName``` \n\nwithin the parentheses. ```argName``` represents the argument, and ```ArgType``` is its type. The next example should clear the air for you.\n\n##### Snippet-01: Method with an argument: Definition\n\nLet's look at a method definition using an argument ```numOfTimes```.\n\n```java\n\n\tjshell\u003e void sayHelloWorld(int numOfTimes) {\n\t   ...\u003e }\n\t| created method sayHelloWorld(int)\n```\n\nLet's try to call the method.\n```java\n\tjshell\u003e sayHelloWorld()\n\t| Error:\n\t| method sayHelloWorld in class cannot be applied to given types;\n\t| required : int\n\t| found : no arguments\n\t| reason : actual and formal argument lists differ in length\n\t| sayHelloWorld(\n\t|^-----------------^\n\tjshell\u003e sayHelloWorld(1)\n\tjshell\u003e\n\n```\n\nMethod call must include the same number and types of arguments, that it is defined to have. ```sayHelloWorld()``` is an error because ```sayHelloWorld``` is defined to accept one parameter. ```sayHelloWorld(1)``` works.\n\nHowever, the method does not do anything. Isn't it sad?\n\n##### Snippet-02 : Passing and accessing a parameter\n\nThe next example will show you how method body code can access arguments passed during a call. Not only that, the argument values can be used during computations.\n\n```java\n\nvoid sayHelloWorld(int numOfTimes) {\n\tSystem.out.println(numOfTimes);\n}\n\n```\n\n`System.out.println(numOfTimes)` prints the value of argument passed.\n\nA method can be invoked many times within a program, and each time different values could be passed to it. The following example will illustrate this fact.\n\n```java\n\n\tjshell\u003e sayHelloWorld(1)\n\t1\n\tjshell\u003e sayHelloWorld(2)\n\t2\n\tjshell\u003e sayHelloWorld(4)\n\t4\n\tjshell\u003e /edit sayHelloWorld\n\t| modified method sayHelloWorld(int)\n\tjshell\u003e\n\n```\n\n##### Snippet-03: More complex method\n\nCode inside a method can be any valid Java code! For instance, you could write code for iteration, such as a ```for``` loop.\n\nLet's look at an example:\n\n```java\n\n\tvoid sayHelloWorld(int numOfTimes) {\n\t\tfor (int i=1; i\u003c=numOfTimes; i++) {\n\t\t\tSystem.out.println(numOfTimes);\n\t\t}\n\t}\n\n```\n\nIn the above example, we printed ```numOfTimes``` a total of ```numOfTimes``` for each method call. \n \nWe print ```2``` two times and ```4``` four times.\n\n```java\n\n\tjshell\u003e sayHelloWorld(2)\n\t2\n\t2\n\tjshell\u003e sayHelloWorld(4)\n\t4\n\t4\n\t4\n\t4\n\tjshell\u003e\n\n```\n\n##### Snippet-4 : Saying \"Hello World\", Again and again...\n\nWe wanted to print \"Hello World\" multiple times. Let's update the method:\n\n```java\n\tvoid sayHelloWorld(int numOfTimes) {\n\t\tfor (int i=1; i\u003c=numOfTimes; i++) {\n\t\t\tSystem.out.println(\"Hello World\");\n\t\t}\n\t}\n```\n\nIsn't this cool?\n\n```java\n\tjshell\u003e sayHelloWorld(1)\n\tHello World\n\tjshell\u003e sayHelloWorld(2)\n\tHello World\n\tHello World\n\tjshell\u003e sayHelloWorld(4)\n\tHello World\n\tHello World\n\tHello World\n\tHello World\n\tjshell\u003e\n\n```\n\nYou can now proudly demonstrate this code to your Java instructor. Your program can print \"Hello World\" an arbitrary number of times! \n\nWhat started off giving you a headache, will probably keep you in her good books, for the rest of your course!\n\nArmed with this confidence booster, let's now see how Java treats mistakes you may make. \n.\n  \n##### Snippet-5 : Parameter type mismatch\n\nJava is a strongly typed language, with strict rules laid out for type compatibility. We saw that with variables, and how they play out with expressions and assignments. The same type compatibility rules are enforced by the compiler, when it needs to match the arguments from method calls with method definition.\n\n```java\n\n\tjshell\u003e sayHelloWorld(\"value\")\n\t| Error:\n\t| incompatible types: java.lang.String cannot be converted to int\n\t| sayHelloWorld(\"value\")\n\t|               ^-----^\n\tjshell\u003e sayHelloWorld(4.5)\n\t| Error:\n\t| incompatible types: possibly lossy conversion from double to int\n\t| sayHelloWorld(4.5)\n\t|               ^-^\n\tjshell\u003e\n\n```\n\n#### Summary\n\nIn this step, we:\n\n* Understood why Java supports method arguments, and how we may use them\n* Observed how method arguments lead to convenience and reuse\n* Decided to abide by type compatibility for actual arguments\n\n### Step 05: Exercise Set PE-02 (With Solutions)\n\n#### Exercises\n\n1. Write a method ```printNumbers(int n)``` that prints all successive integers from ```1``` to ```n```.\n2. Write a method ```printSquaresOfNumbers(int n)``` that prints the squares of all successive integers from ```1``` to ```n```.\n\n#### Solution-01\n\n```java\n\n\tjshell\u003e void printNumbers(int n) {\n\t   ...\u003e for(int i=0; i\u003c n; i++) {\n\t   ...\u003e System.out.println(i);\n\t   ...\u003e }\n\t   ...\u003e }\n\t| created method printNumbers(int)\n\t\n```\n\n**jshell\u003e**\n\n#### Solution 2\n\n```java\n\n\tjshell\u003e void printSquaresOfNumbers(int n) {\n\t   ...\u003e for(int i=0; i\u003c n; i++) {\n\t   ...\u003e System.out.println(i*i);\n\t   ...\u003e }\n\t   ...\u003e }\n\t| created method printSquaresOfNumbers(int)\n\tjshell\u003e\n\n```\n\n### Step 07: *PMT-Challenge* Revisited (And Some Puzzles)\n\nA method, in its own right, provides an elegant way to name and reuse a code block. In addition, its behavior can be controlled with parameters. \n\nCan we top-up the existing solution to the *PMT-Challenge*, with even more elegance? You're right, we're talking about:\n1. Writing a method to print the multiplication table for 5.\n2. Using this method to print the multiplication table for any number.\n\nWant to take a look? Dive right in.\n\nHere's what we did earlier:\n\n```java\n\n\tjshell\u003e for (int i=1; i\u003c=10; i++) {\n\t   ...\u003e System.out.printf(\"%d * %d = %d\", 5, i, 5*i).println();\n\t   ...\u003e }\n\t5 * 1 = 5\n\t5 * 2 = 10\n\t5 * 3 = 15\n\t5 * 4 = 20\n\t5 * 5 = 25\n\t5 * 6 = 30\n\t5 * 7 = 35\n\t5 * 8 = 40\n\t5 * 9 = 45\n\t5 * 10 = 50\n\n```\n\nLet's wrap this in a method:\n\n```java\n\n\tvoid printMultiplicationTable() {\n\t\tfor (int i=1; i\u003c=10; i++) {\n\t\tSystem.out.printf(\"%d * %d = %d\", 5, i, 5*i).println();\n\t\t}\n\t}\n\n```\n\nYou can call it to print 5 table.\n\n```java\n\n\tjshell\u003e printMultiplicationTable()\n\t5 * 1 = 5\n\t5 * 2 = 10\n\t5 * 3 = 15\n\t5 * 4 = 20\n\t5 * 5 = 25\n\t5 * 6 = 30\n\t5 * 7 = 35\n\t5 * 8 = 40\n\t5 * 9 = 45\n\t5 * 10 = 50\n\tjshell\u003e\n\t\n```\n\n#### Summary\n\nIn this step, we:\n\n* Revisited the *PMT-Challenge* solution we had earlier\n* Enclosed its logic within a method definition, ```printMultiplicationTable()```\n* Haven't fully explored its power yet!\n\n### Step 08: Methods With Arguments, And Overloading\n\nThe real power of a definition such as ```printMultiplicationTable()``` is when we arm it with arguments. Not verbal arguments, but \"value\" ones. That's right! \n\nWe will modify ```printMultiplicationTable()``` to have it accept a parameter, which would make it more flexible. \n\n```java\n\tvoid printMultiplicationTable(int number) {\n\t\tfor (int i=1; i\u003c=10; i++) {\n\t\t\tSystem.out.printf(\"%d * %d = %d\", number, i, number*i).println();\n\t\t}\n\t}\n```\n\nWe can now print the multiplication table of any number, by calling the method ```printMultiplicationTable(number)```.\n\n```java\n\n\tjshell\u003e printMultiplicationTable(6)\n\t6 * 1 = 6\n\t6 * 2 = 12\n\t6 * 3 = 18\n\t6 * 4 = 24\n\t6 * 5 = 30\n\t6 * 6 = 36\n\t6 * 7 = 42\n\t6 * 8 = 48\n\t6 * 9 = 54\n\t6 * 10 = 60\n\tjshell\u003e\n\t\n```\n\n Nothing new to explain here. We have only combined stuff you have been learning so far, most recently adding the flavor of methods to the existing  code. \n\n Soak in the power, simplicity and elegance of this program, folks!\n\n#### Overloaded Methods\n\nIt turns out we can call both versions of the method, `printMultiplicationTable()` and `printMultiplicationTable(5)` : \n\n```java\n\n\tjshell\u003e printMultiplicationTable()\n\t5 * 1 = 5\n\t5 * 2 = 10\n\t5 * 3 = 15\n\t5 * 4 = 20\n\t5 * 5 = 25\n\t5 * 6 = 30\n\t5 * 7 = 35\n\t5 * 8 = 40\n\t5 * 9 = 45\n\t5 * 10 = 50\n\tjshell\u003e\n\n```\n\n and \n\n```java\n\n\tjshell\u003e printMultiplicationTable(5)\n\t5 * 1 = 5\n\t5 * 2 = 10\n\t5 * 3 = 15\n\t5 * 4 = 20\n\t5 * 5 = 25\n\t5 * 6 = 30\n\t5 * 7 = 35\n\t5 * 8 = 40\n\t5 * 9 = 45\n\t5 * 10 = 50\n\tjshell\u003e\n\n```\n\nYou can have multiple methods with same name but different number of parameters. This is called ***method overloading***. \n\n#### Summary\n\nIn this step, we:\n\n* Enhanced the logic of ```printMultiplicationTable()``` by passing arguments\n* Added flexibility to the *PMT-Challenge* solution \n* Were introduced to the concept of method overloading\n\n### Step 09:  Methods With Multiple Arguments\n\nIt is possible, and pretty useful, to define methods that accept more than one argument. \n\nWe have already seen how to call two in-built Java methods, ```Math.max``` and ```Math.min```, which accept 2 arguments each. \n\nTime now to enrich our understanding, by writing one such method ourselves as well. \n\nA method ```void sum(int, int)``` that computes the sum of two integers, and prints their output.\n\n```java \n\n\tjshell\u003e void sum(int firstNum, int secondNum) {\n\t   ...\u003e int sum = firstNum + secondNum;\n\t   ...\u003e System.out.println(sum);\n\t   ...\u003e }\n\t| created method sum(int, int)\n\tjshell\u003e sum(5, 10)\n\t15\n\tjshell\u003e\n\n```\n\nA method ```void sum(int, int, int)``` that computes the sum of three integers, and prints their output.\n```java\n\n\tjshell\u003e void sum(int firstNum, int secondNum, int thirdNum) {\n\t   ...\u003e int sum = firstNum + secondNum + thirdNum;\n\t   ...\u003e System.out.println(sum);\n\t   ...\u003e }\n\t| created method sum(int,int,int)\n\tjshell\u003e sum(5, 10, 15)\n\t30\n```\n\nThere are overloaded methods. They have same name ```sum``` and have different number of arguments. \n\n#### Summary\n\nIn this step, we:\n\n* Used our understanding of method overloading to define our own methods\n\n### Step 10: Returning From A Method\n\nA method can also be coded to return the result of its computation. Such a result is called a  **return value**. \n\nA lot of built-in Java methods have return values, the most notable we have seen being ```Math.min()``` and ```Math.max()```. \n\n```java\n\tjshell\u003e Math.max(15, 25)\n\t$1 ==\u003e 25\n\tjshell\u003e $1\n\t$1 ==\u003e 25\n\n```\n\n```Math.max()``` does return a value, which is stored in the ```JShell``` variable ```$1```.\n\nA return mechanism is quite important, as it provides you the flexibility of:\n* Sharing computed results with other code and methods\n* Improving the breaking down of a problem, into sub-problems\n\nThe next example explains how you can collect a method's return value.\n\n```java\n\tjshell\u003e int max = Math.max(15, 25)\n\tmax ==\u003e 25\n\tjshell\u003e max\n\tmax ==\u003e 25\n\tjshell\u003e\n\n```\n\nWe are storing the return value in a variable ```int max```.\n \nWe could define our own method that returns a value, in a similar manner. In the method  ```sumOfTwoNumbers``` above, instead of displaying ```sum``` at once, we could ```return``` it to the calling-code. \n\n```java\n\n\tjshell\u003e int sumOfTwoNumbers(int firstNum, int secondNum) {\n\t   ...\u003e int sum = firstNum + secondNum;\n\t   ...\u003e return sum;\n\t   ...\u003e }\n\t| created method sumOfTwoNumbers(int,int)\n\tjshell\u003e sumOfTwoNumbers(1, 10)\n\t$2 =\u003e 11\n```\n\nThe statement ```return sum;``` is called a **return statement**.\n\nWhen the code ```sum = sumOfTwoNumbers(1, 10)``` is run, ```sum``` collects the result returned by ```sumOfTwoNumbers()```. You could now print ```sum``` on the console, store it in another variable, or even invoke a different method by passing it as an argument!\n\n```\n\tjshell\u003e sum = sumOfTwoNumbers(1, 10)\n\tsum =\u003e 11_\n\tjshell\u003e sum = sumOfTwoNumbers(15, 15)\n\tsum =\u003e 30\n\tjshell\u003e\n```\n\n#### Summary\n\nIn this step, we:\n* Understood the need for a return mechanism with methods\n* Explored the syntax for a return statement\n* Wrote our own method ```sumOfTwoNumbers()``` with a return value, and saw how it became more flexible\n\n### Step 11: Exercise-Set PE-04 (With Solutions)\n\nLet's now try a few exercises on methods that return values.\n\n#### Exercises\n\n1. Write a method that returns the sum of three integers.\n2. Write a method that takes as input two integers representing two angles of a triangle, and computes the third angle. *Hint: The sum of the three angles of a triangle is 180 degrees*. \n\n#### Solution-01\n\n```java\n\n\tjshell\u003e int sumOfThreeNumbers(int firstNum, int secondNum, int thirdNum) {\n\t   ...\u003e int sum = firstNum + secondNum + thirdNum;\n\t   ...\u003e return sum;\n\t   ...\u003e }\n\t| created method sumOfThreeNumbers(int,int, int)\n\tjshell\u003e\n\n```\n\n#### Solution-02\n\n```java\n\n\tjshell\u003e int getThirdAngle(int firstAngle, int secondAngle) {\n\t   ...\u003e int sumOfTwo = firstAngle + secondAngle;\n\t   ...\u003e return 180 - sum;\n\t   ...\u003e }\n\t| created method getThirdAngle(int,int)\n\tjshell\u003e\n\t\n```\n\n### Step 12: Java Methods, A Review\nIn this section, we introduced you to the concept of methods in Java.\n* We understood that methods are routines that perform a unit of computation. They group a set of statements together into a block, and need to be run by being invoked, through a method call. \n* We can define methods that accept no arguments, a single argument and multiple arguments.\n* A method can also be defined to return results of its computation, and this makes it your program more flexible.\n\n## Understanding the Java Platform\n\nJShell is amazing to start with the basics of Java programming. It abstracts all complexities behind writing, compiling and running Java code.\n\nWhat's happening behind the screens? Let's find out.\n\n### Step 01: The Java Platform - An Introduction\n\nA computer only understands binary code, which are sequences of ```0```’s and ```1```’s (called **bits**).  All instructions to a computer should be converted to ```0```’s and ```1```’s before execution.\n\n***When we wrote our code in JShell, how was it converted to binary code?***\n\nWe write our programs in a high-level language, such as Java, as it is easier to learn, remember and maintain. \n\nWho converts it to binary code?\n\nTypically, **Compiler** is a program which understands the syntax of your programming language and converts it into binary code.\n\nJava designers wanted it to be Platform independent. Compile the code once and run it anywhere.\n\nHowever, different Operating Systems have different instruction sets - different binary code. \n\nJava provides an interesting solution:\n- All Java compilers translate source code to an **intermediate representation** ( **bytecode** ). \n- To run Java programs (**bytecode**), you need a ***JVM*** (Java Virtual Machine). \n\t- ***JVM*** understands **bytecode** and runs it. \n\t- There are different JVM's for different operating systems. Windows JVM converts **bytecode** into Windows executable instructions. Linux JVM converts **bytecode** into Linux executable instructions. \n\nThe Java compiler translates Java source code to **bytecode**, which is stored as a **.class** file on the computer.\n\n#### Summary\n\nIn this step, we:\n\n* Understood the role of the Java compiler in translating source code\n* Realized the need for an Intermediate Representation (IR) such as bytecode\n* Understood how the (Compiler + JVM + OS) combination ensure source code portability\n\n### Step 02: Creating a Java ```class```\n\nFirst, let's understand the concept of a `class`.\n\nLet's consider an example: \n\nA **Country** is a *concept*. **India**, **USA** and **Netherlands** are *examples* or *instances* of **Country**.\n\nSimilarly, a `class` is a template. `Objects` are `instances` of a `class`.\n\nWe will discuss more about `class` and `object` in the section on Object Oriented Programming.\n\nThe syntax to create a class, and its objects, is very simple.\n\n```java\n\n\tjshell\u003e class Country {\n\t   ...\u003e }\n\tcreated class Country\n```\n\nLet's create an instance of the class:\n```java\n\tjshell\u003e Country india = new Country();\n\tindia ==\u003e Country@6e06451e\n```\n\nThe syntax is simple - `ClassName objectName = new ClassName()`.\n\n```india``` is an object of type ```Country```, and is stored in memory at a location indicated by ```6e06451e```.\n\nLet's create a few more instances of the class:\n```java\n\tjshell\u003e Country usa = new Country();\n\tusa ==\u003e Country@6e1567f1\n\tjshell\u003e Country netherlands = new Country();\n\tnetherlands ==\u003e Country@5f134e67\n\tjshell\u003e\n\n```\n\n ```india```, ```usa``` and ```netherlands``` are all different objects of type ```Country```. \n\n We actually left the contents of the ```class``` ```Country``` bare. \n\n A ```class``` does often include both data (member variables) and method definitions. More on this at a relevant time.\n\nLet's consider another example:\n\n```java\n\n\tjshell\u003e class Planet {\n\t   ...\u003e}\n\tcreated class Planet\n\tjshell\u003e Planet planet = new Planet();\n\tplanet ==\u003e Planet@56ef9176\n\tjshell\u003e Planet earth = new Planet();\n\tearth ==\u003e Planet@1ed4004b\n\tjshell\u003e Planet planet = new Planet();\n\tvenus ==\u003e Planet@25bbe1b6\n\n```\n\nWe can also create a ```class``` for a different concept, like a ```Planet```. \n\n```Planet``` is now a different template. ```planet```, ```earth``` and ```venus``` are instances of `Planet` class. \n\n#### Summary\n\nIn this step, we:\n\n* Saw how ```class``` creation actually creates a new type\n* Understood how to create instances of classes - objects\n\n### Step 03: Adding A Method To A ```class``` \n\nA method defined within a ```class```, denotes an action than can be performed on objects of that ```class```.\n\nLet's define a method inside ```Planet``` - to ```revolve()```!\n\n```java\n\n\t\tjshell\u003e class Planet {\n\t   ...\u003e void revolve() {\n\t   ...\u003e System.out.println(\"Revolve\");\n\t   ...\u003e }\n\t   ...\u003e }\n\treplaced class Planet\n\tupdate replaced variable planet, reset to null\n\tupdate replaced variable earth, reset to null\n\tupdate replaced variable venus, reset to null\n```\nSyntax of `revolve()` is similar to other methods we've created before. \n\n\u003e The ```class``` template got updated as a result of adding new method.\n\u003e Earlier instances ```planet```,```earth``` and ```venus``` got reset to ```null``` as they are based on the old template\n\nLet's re-instantiate a few objects.\n\n```java\n\tjshell\u003e Planet earth = new Planet();\n\tearth ==\u003e Planet@192b07fd\n\tjshell\u003e Planet planet = new Planet();\n\tvenus ==\u003e Planet@64bfbc86\n\tjshell\u003e\n\n```\n\nHow do we call the ```revolve``` method?\n\n```java\n\n\tjshell\u003e Planet.revolve();\n\t| Error:\n\t| non-static method revolve() cannot be referenced from a static context\n\t| Planet.revolve();\n\t|^-----------------^\n\tjshell\u003e earth.revolve();\n\tRevolve\n\tjshell\u003e venus.revolve();\n\tRevolve\n\tjshell\u003e\n\n```\n\nOur attempt to perform ```revolve()``` did not work with the syntax ```Planet.revolve()``` as it is not a static method (more on that in a later section). \n\nInvoking ```revolve()``` through syntax such as ```earth.revolve()``` succeeds, because ```earth``` is an object of type ```Planet```. \n\n#### Summary\n\nIn this step, we:\n\n* Learned how to add a method definition to an existing ```class```\n* Discovered how to invoke it, on objects of the ```class```\n\n### Step 04: Writing and Running Java Code in separate Source Files\n\nSo far, we have enjoyed creating classes and defining methods within them, all with our friendly neighborhood ```JShell```. \n\n```JShell``` kind of spoiled us kids, by relaxing some Java syntax rules, invoking the compiler on our behalf, and also running the code like room service.\n\nThe time has come for us frog princes to outgrow the proverbial well. Yes, you're right! Time to start writing code in a proper code editor, and smell the greener grass on that side.\n\nLet's start with creating a new source code file - 'Planet.java'. Choose any folder on your hard-disk and create the file shown below:\n\n_**Planet.java**_\n\n```java\n\n\tclass Planet {\n\t\tvoid revolve() {\n\t\t\tSystem.out.println(\"Revolve\");\n\t\t}\n\t}\n\n```\n\n\u003e You can get the code that we wrote earlier in JShell for ```Planet``` by running the command ```/list Planet```, and copying the code. \n\n\u003e You can use any text editor of your choice, for now. \n\nThe source file name must match the ```class``` name it contains. Here, we must name the file `Planet.java`.\n\nThe next course of action would be to compile this code (Stage 2). For that, exit out of ```JShell```, and run back to your system terminal or command prompt. Now, see what plays out!\n\n```java\n\n\tjshell\u003e /exit\n\t|  Goodbye\n```\n\n```cd``` to the folder where you have created the file `Planet.java`\n\n```\n\tin28minutes$\u003e cd in28Minutes/git/JavaForBeginners/\n\tcommand-prompt\u003e ls\n\tPlanet.java\n```\n\nCheck Java version.\n```\n\tcommand-prompt\u003e java -version\n\tjava version \"x.0.1\"\n\tJava(TM) SE Runtime Environment (build x.0.1+11)\n\tJava HotSpot(TM) 64-bit Server VM (build x.0.1+11, mixed mode)\n```\n\nYou can compile java code using ```javac Planet.java```. You can see that a new file is created `Planet.class`. This contains your `bytecode`.\n\n```\n\tcommand-prompt\u003e javac Planet.java\n\tcommand-prompt\u003e ls\n\tPlanet.class         Planet.java_\n```\n\nYou can run the class using command `java Planet`.\n\n```java\n\tcommand-prompt\u003e java Planet\n\tError: Main method not found inside class Planet, please define the main method as\n\tpublic static void main(String[] args)\n\tor a JavaFX application class must extend javax.application.Application\n\tcommand-prompt\u003e\t\n```\n\nWhy is there an error? Let's discuss that in the next step.\n\n#### Summary\n\nIn this step, we:\n\n* Ventured out of ```JShell``` into unexplored territory, to write source code\n* Learned how to invoke the compiler to compile source files, from the terminal\n\n### Step 05: Introducing ```main()```, And Running Bytecode\n\nIn the previous step, we compiled **_Planet.java_**. In this step, let's run the bytecode generated, which lies inside **_Planet.class_**.\n\n##### Snippet-01: Running ```Planet```\n\n**_Console Commands_**\n\n```java\n\n\tcommand-prompt\u003e ls\n\tPlanet.class         Planet.java\n\tcommand-prompt\u003e java Planet\n\tError: Main method not found inside class Planet, please define the main method as\n\tpublic static void main(String[] args)\n\tor a JavaFX application class must extend javax.application.Application\n\tcommand-prompt\u003e\n\n```\n\nThe code may have compiled without any errors, but what's the use if we cannot run the program to see what stuff it's got!\n\n**_The ```main()``` method is essential to run code defined within any ```class```._**\n\nThe definition of ```main()``` needs to have this exact synatx:\n\n`public static void main(String[] args) {  /* \u003cSome Code Goes In Here\u003e */ }`\n\nA few details:\n* `void` is its return type\n* `main` is its name\n* `args` is its formal argument. Here, it's an **array** of ```String```.\n* `public``` and ```static``` are reserved Java keywords. More on these later sections.\n\n\nLet's add one such definition within the ```Planet``` code. Open up your text editor and add the ```main``` method as shown below.\n\n**_Planet.java_**\n\n```java\n\n\tclass Planet {\n\t\tvoid revolve() {\n\t\t\tSystem.out.println(\"Revolve\");\n\t\t}\n\t\tpublic static void main(String[] args) {\n\n\t\t}\n\t}\n\n```\n\nLet's run it now:\n\n```java\n\n\tcommand-prompt\u003e java Planet\n\tError: Main method not found inside class Planet, please define the main method as\n\tpublic static void main(String[] args)\n\tor a JavaFX application class must extend javax.application.Application\n```\n\nWhy is there no change in result?\n\nAfter changing your Java source file, you need to compile the code again to create a new class file.\n\n```\n\tcommand-prompt\u003e javac Planet.java\n\tcommand-prompt\u003e ls\n\tPlanet.class         Planet.java_\n```\n\nLet's try it again.\n```\n\tcommand-prompt\u003e java Planet\n\tcommand-prompt\u003e\n\n```\n\nWe got a blank stare from the terminal. Why?\n\nWhat did we write in the ```main``` method? Nothing.\n\n```java\n\t\tpublic static void main(String[] args) {\n\n\t\t}\n\n```\n\nLet's fix it. We need to edit **_Planet.java_** once again!\n\n**_Planet.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fin28minutes%2Fjava-tutorial-for-beginners","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fin28minutes%2Fjava-tutorial-for-beginners","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fin28minutes%2Fjava-tutorial-for-beginners/lists"}