<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Learning Java from scratch - JBay Solutions - The Dev Blog]]></title><description><![CDATA[JBay Solutions Development Blog on Java, Android, Play2 and others]]></description><link>http://blog.jbaysolutions.com/</link><generator>Ghost 0.7</generator><lastBuildDate>Wed, 16 Oct 2024 01:15:04 GMT</lastBuildDate><atom:link href="http://blog.jbaysolutions.com/tag/learning-java-from-scratch/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Java Tutorial 7 - Starting Flow Control]]></title><description><![CDATA[This is where the fun part begins! Now we start looking at the implementation of flow control and logic.]]></description><link>http://blog.jbaysolutions.com/2016/04/01/java-tutorial-7-starting-flow-control-2/</link><guid isPermaLink="false">9f4fb1f1-1e5b-4923-b86c-09f778fa7151</guid><category><![CDATA[java]]></category><category><![CDATA[Learning Java from scratch]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Fri, 01 Apr 2016 17:01:46 GMT</pubDate><content:encoded><![CDATA[<ol>
<li><a href="http://blog.jbaysolutions.com/2016/04/01/java-tutorial-7-starting-flow-control-2/" onclick="gotonow('introduction');return false;">Introduction</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/04/01/java-tutorial-7-starting-flow-control-2/" onclick="gotonow('ifstatement');return false;">If Statement</a> <br>
<ul><li><a href="http://blog.jbaysolutions.com/2016/04/01/java-tutorial-7-starting-flow-control-2/" onclick="gotonow('equalityoperators');return false;">Equality Operators</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/04/01/java-tutorial-7-starting-flow-control-2/" onclick="gotonow('conditionaloperators');return false;">Conditional Operators</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/04/01/java-tutorial-7-starting-flow-control-2/" onclick="gotonow('else');return false;">Else</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/04/01/java-tutorial-7-starting-flow-control-2/" onclick="gotonow('not');return false;">Not</a></li></ul></li>
<li><a href="http://blog.jbaysolutions.com/2016/04/01/java-tutorial-7-starting-flow-control-2/" onclick="gotonow('switchstatement');return false;">Switch Statement</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/04/01/java-tutorial-7-starting-flow-control-2/" onclick="gotonow('wrappingup');return false;">Wrapping up</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/04/01/java-tutorial-7-starting-flow-control-2/" onclick="gotonow('references');return false;">References</a></li>
</ol>

<h3 id="introduction">Introduction</h3>

<p>This is where the fun part begins! With the previous tutorials we have and idea of the core building blocks, now we start looking at the implementation of flow control, or logic if you will. The most important statement for implementing logic, in my personal experience is the <strong>If statement</strong>.</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="ifstatement">If Statement</h3>

<p>Lets jump right into an example! The <em>If statement</em> works like this:</p>

<pre><code>if ( true )
    System.out.println("Evaluation was true");
</code></pre>

<p>We have the keywork <strong>if</strong> followed by a boolean expression that, as the name states, must evaluate to a boolean. In our particular example it will always evaluate to <code>true</code>.</p>

<p>If the expression evaluates to <code>true</code> (which is our example, it always does) , the next statement is executed. If the expression evaluates to <code>false</code>, then next statement is <strong>NOT executed</strong> , and the execution flow continues after the next statement.</p>

<p>Now lets look at the following modification we made:</p>

<pre><code>if ( false )
    System.out.println("Evaluation was true");
    System.out.println("Evaluation was true, part 2");
</code></pre>

<p>The if boolean evaluation is always <code>false</code> now, so the first statement after the <em>if</em> is not executed. But the second print statement will be executed, because the <em>if</em> statement only conditions one statement. If we only wanted to have the two <code>println</code> statements execute if the previous condition was true, then we need to user a <em>block</em>, like so:</p>

<pre><code>if ( false )  {
    System.out.println("Evaluation was true");
    System.out.println("Evaluation was true, part 2");
}
</code></pre>

<p>This would make the two <code>println</code> statements execute if the evaluation is <code>true</code>. Because in our previous example it is false, then the two <code>println</code> statement would not be executed.</p>

<p>Until now we have been using a <em>boolean</em> directly to define the behavior of the <em>if statement</em>, which makes this code execute always in the same way and no decision be actually made. </p>

<p>But, like it was said because, we can place any statement inside that <strong>if condition</strong> as long as it evaluates to a boolean. </p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="equalityoperators">Equality Operators</h3>

<p>For comparing primitive variables, we have these Equality Operators:</p>

<ul>
<li><code>==</code> : Equal to</li>
<li><code>!=</code> : Not equal to</li>
<li><code>&gt;</code> : Greater than</li>
<li><code>&gt;=</code> : Greater than or equal to</li>
<li><code>&lt;</code> : Less than</li>
<li><code>&lt;=</code> : Less than or equal to</li>
</ul>

<p>Look at the following code snippet:</p>

<pre><code>int age = 10;

if ( age &lt; 18 ) {
    System.out.println("Price of ticket : 50" );
}

if ( age == 18 ) {
    System.out.println("Price of ticket : 100" );
}

if ( age &gt; 18 ) {
    System.out.println("Price of ticket : 120" );
}
</code></pre>

<p>Very easy to understand, yes?  </p>

<ul>
<li>If the variable <code>age</code> is <em>smaller than</em> ( <code>&lt;</code> ) 18, the code will print : <em>Price of ticket : 50</em></li>
<li>If the variable <code>age</code> is <em>equal to</em> ( <code>==</code> ) 18, the code will print : <em>Price of ticket : 100</em></li>
<li>If the variable <code>age</code> is <em>greater than</em> ( <code>&gt;</code> ) 18, the code will print : <em>Price of ticket : 120</em></li>
</ul>

<p>Nothing special, but now, lets try something else:</p>

<pre><code>public static void main(String[] args) {

    String value1 = new String("good");
    String value2 = new String("good");

    if (value1 == value2) {
        System.out.println(" They are equal ");
    }

}
</code></pre>

<p>When we run this main method, we expected to see the program write <em>They are equal</em> to the console, but it produces nothing. The reason for this is that , like we said before, these operators are only to be used with <strong>Primitive Variables</strong>, and as we know, <code>String</code> is not a primitive type, it is an Object.</p>

<p>Objects are compared differently, but to fully understand the deal with Object, we must first talk about Reference Variables, which will happen in one or two tutorials. For now, lets focus on primitives and see what can be achieved with <em>If statements</em> .</p>

<blockquote>
  <p>Equality Operators are to be used with Primitive Variables. Comparing Objects with <code>==</code> might produce unexpected results.</p>
</blockquote>

<p>Equality Operators can also be combined with boolean operators to create more complex boolean expressions.</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="conditionaloperators">Conditional Operators</h3>

<p>These are some the available Conditional Operators:</p>

<ul>
<li><code>&amp;</code> - AND</li>
<li><code>|</code> - OR</li>
<li><code>&amp;&amp;</code> - Conditional AND</li>
<li><code>||</code> - Conditional OR</li>
</ul>

<p>Lets see them in use and understand the difference between an <strong>AND</strong> and a <strong>Conditional AND</strong> . We'll create a class for that purpose, and call it  <em>TestOperators</em>. It will look like this:</p>

<p>package tutorial7;</p>

<p>public class TestOperators {</p>

<pre><code>public void compareUsingAnd( int value1 , int value2) {

    if (  value1 &gt;= 10 &amp; value2 &lt; 100 ) {
        System.out.println(" Condition is true ");
    }

}
</code></pre>

<p>}</p>

<p>What it means is, if : </p>

<ul>
<li><code>value1 &gt;= 10</code>  : value1 variable is Greater or Equal than 10 </li>
<li><code>&amp;</code>  : AND</li>
<li><code>value2 &lt; 100</code>: value2 variable is Less than 100</li>
</ul>

<p>Then :</p>

<ul>
<li><code>System.out.println(" Condition is true ");</code></li>
</ul>

<p>Now, on our <em>Starter</em> class, we create an instance of the TestOperators class and call that method like this:</p>

<pre><code>public static void main(String[] args) {

    TestOperators test = new TestOperators();
    test.compareUsingAnd( 10, 50 );

}
</code></pre>

<p>When we run the code it produces:</p>

<pre><code> Condition is true 
</code></pre>

<p>Lets modify the code on the <code>compareUsingAnd</code> method like this :</p>

<pre><code>package tutorial7;

public class TestOperators {

    public void compareUsingAnd( int value1 , int value2) {

        if (  firstComparison(value1) &amp;   value2 &lt; 100 ) {
            System.out.println(" Condition is true ");
        }

    }

    private boolean firstComparison(int value) {
        if ( value &gt;= 10)
            return true;
        return false;
    }

}
</code></pre>

<p>It does exactly the same thing, but instead of doing the two individual comparisons inside the boolean expression, we create one method called <code>firstComparison</code> that performs exactly the same comparison and call that method instead. Lets just look at that method for a second :</p>

<pre><code>private boolean firstComparison(int value) {
System.out.println("- Running firstComparison");

    if ( value &gt;= 10)
        return true;

    return false;
}
</code></pre>

<p>From the signature of the method we know :</p>

<ul>
<li>It is a <code>private</code> method, because it just needs to be accessible from inside the <code>TestOperators</code> class, </li>
<li>it returns a `boolean* value, </li>
<li>it receives an <code>int</code> parameter that we simply call <code>value</code>. </li>
</ul>

<p>First it prints <em>"- Running firstComparison"</em>, just so we know the method was called.</p>

<p>Then, if the <code>value</code> provided is Greater or Equal to <code>10</code>, it returns <code>true</code> and the method finishs (a method finishes after the return statement).  </p>

<p>If the value is <strong>NOT</strong>  Greater or Equal to <code>10</code>, then it does not <code>return true;</code>, so it continues executing, and returns false.</p>

<p>We run our program and it produces:</p>

<pre><code>- Running firstComparison
 Condition is true 
</code></pre>

<p>So <code>firstComparison</code> evaluated to true, and <code>value2 &lt; 100</code> also evaluated to true. </p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<p>Now, as an exercise and because we need it to continue the rest of the tutorial, create a method called <code>secondComparison</code> and do the same thing we did with <code>firstComparison</code>. </p>

<p>The end result should look like this :</p>

<pre><code>package tutorial7;

public class TestOperators {

    public void compareUsingAnd( int value1 , int value2) {

        if (  firstComparison(value1)  &amp;  secondComparision(value2) ) {
            System.out.println(" Condition is true ");
        }

    }

    private boolean firstComparison(int value) {
        System.out.println("- Running firstComparison");

        if ( value &gt;= 10)
            return true;
        return false;
    }

    private boolean secondComparision(int value) {
        System.out.println("- Running secondComparision");

        if ( value &lt; 100)
            return true;
        return false;
    }
}
</code></pre>

<p>Running the previous <code>main</code> method will produce: </p>

<pre><code>- Running firstComparison
- Running secondComparision
 Condition is true 
</code></pre>

<p>With these two methods we can see when the evaluations are made, and it is easier to explain concepts. </p>

<p>Lets modify the <code>main</code> method to call the <code>compareUsingAnd</code> method with  values <code>1</code> and <code>50</code>:</p>

<pre><code>public static void main(String[] args) {

    TestOperators test = new TestOperators();
    test.compareUsingAnd( 1, 50 );

}
</code></pre>

<p>We compile and run this code and get:</p>

<pre><code>- Running firstComparison
- Running secondComparision
</code></pre>

<p>As you can see, this time around there was no <em>"Condition is true"</em> being printed, and the reason is, if you follow the code, method <code>firstComparison</code> evaluates to <code>false</code> even tho <code>secondComparision</code> evaluates to true, and because :</p>

<pre><code>false AND true = false
</code></pre>

<p>which is essencially what this mean :</p>

<pre><code>if (  false  &amp;  true ) {
    System.out.println(" Condition is true ");
}
</code></pre>

<p>The condition of the <code>if</code> is not meet, and the <code>println</code> statement is not executed. </p>

<p>If you have any doubts why <code>false AND true = false</code> then please check <a href="https://en.wikipedia.org/wiki/Truth_table">Wikipedia - Truth Tables</a>. It is essential to have an understanding of logic operations of this kind.</p>

<p>Notice that because the first evaluation  ( the <code>firstComparison</code> method) evaluates to <code>false</code>! Because we are using an <strong>AND</strong>, the <code>if</code> condition could never be satisfied, no matter what <code>secondComparision</code> evaluates to. </p>

<blockquote>
  <p>In an <strong>AND</strong> boolean operation , <strong>both arguments must be true for the result to be true</strong></p>
</blockquote>

<p>So :</p>

<ul>
<li><em>false</em> <strong>AND</strong> <em>false</em> = <em>false</em></li>
<li><em>true</em> <strong>AND</strong> <em>false</em> = <em>false</em></li>
<li><em>false</em> <strong>AND</strong> <em>true</em> = <em>false</em></li>
</ul>

<p>Only:</p>

<ul>
<li><em>true</em> <strong>AND</strong> <em>true</em> = <em>true</em></li>
</ul>

<p>Lets modify the <code>compareUsingAnd</code> method on the <em>TestOperators</em> class to this :</p>

<pre><code>public void compareUsingAnd( int value1 , int value2) {

    if (  firstComparison(value1) &amp;&amp; secondComparision(value2) ) {
        System.out.println(" Condition is true ");
    }

}
</code></pre>

<p>The only difference was changing <code>&amp;</code> to <code>&amp;&amp;</code> , so using <strong>Conditional AND</strong> instead of <strong>AND</strong> .</p>

<p>Compiling and running this new version produces the following:</p>

<pre><code>- Running firstComparison
</code></pre>

<p>So, as you can see, <code>secondComparision</code> was never called.</p>

<blockquote>
  <p>This is the difference between <strong>AND</strong> and  <strong>Conditional AND</strong> .  The <strong>AND</strong> operator ( <code>&amp;</code> ) evaluates both side of the <strong>AND</strong> before doing the boolean operation .  The <strong>Conditional AND</strong> ( <code>&amp;&amp;</code> ) first evaluates the first part , and only if the second part is necessary for the boolean operation, does it ever gets evaluated. </p>
</blockquote>

<p>In our last example, because the first part evaluated to <code>false</code> , it is unnecessary to evaluate the second part.</p>

<p>Now, using <code>&amp;&amp;</code> is not more or less correct that <code>&amp;</code> . They are different , have different behaviors, and a programmer needs to be aware of this. Most of the time <code>&amp;&amp;</code> is used, but there could be particular use-cases that require <code>&amp;</code> instead of  <code>&amp;&amp;</code> .</p>

<p><strong>OR</strong> and <strong>Conditional OR</strong> work exactly in the same way. <strong>OR</strong> ( <code>|</code> ) will evaluate both side of the boolean operation before evaluating the OR expression, while the <strong>Conditional OR</strong> ( <code>||</code> ) evaluates the first side, and only evaluates the second if necessary.</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="else">Else</h3>

<p>Again, we'll modify the <code>compareUsingAnd</code> method like this :</p>

<pre><code>public void compareUsingAnd( int value1 , int value2) {

    if (  firstComparison(value1) &amp;&amp; secondComparision(value2) ) {
        System.out.println(" Condition is true ");
    } else
        System.out.println(" Condition is false ");

    System.out.println(" Finished ");
}
</code></pre>

<p>Notice the <strong>else</strong> keyword. This keyword is used together with <em>If statements</em>, to execute something when the if evaluation is not meet.</p>

<p>Compiling and running this code will produce :</p>

<pre><code>- Running firstComparison
 Condition is false 
 Finished 
</code></pre>

<p>As like before, only the statement after the <code>else</code> keyword is execute. If the programmer wants to execute more statements in case the evaluation fails, then a block ( <code>{  }</code> ) must be used, like this :</p>

<pre><code>    if (  firstComparison(value1) &amp;&amp; secondComparision(value2) ) {
        System.out.println(" Condition is true ");
    } else {
        System.out.println(" Condition is false ");
        System.out.println(" Condition is false ");
    }
</code></pre>

<p>Which would print the same thing twice..... just to demonstrate the block.</p>

<p><strong>If Statements</strong> are binary, the expression evaluates either to <code>true</code> or <code>false</code> and there are only two paths of execution.</p>

<p>To allow for more paths of execution we could chain <strong>If Else Statements</strong> and create something like this:</p>

<pre><code>    if ( age &lt; 18) {
        System.out.println(" underage ");
    } else {

        if (age &lt; 70) {
            System.out.println(" adult ");
        } else {
            System.out.println(" elder ");
        }

    }
</code></pre>

<p>This is completely valid, and commonly done.</p>

<h4 id="not">Not</h4>

<p>Also, there is a wait to invert a boolean. Lets look at the following code :</p>

<pre><code>if ( age &lt; 18) {
    System.out.println(" underage ");
} 
</code></pre>

<p>This is equivalent to  :</p>

<pre><code>if ( ! age &gt;= 18) {
    System.out.println(" underage ");
} 
</code></pre>

<p>Notice the <code>!</code> operator, that inverts the result of the <code>age &gt;= 18</code> expression. </p>

<p>So, if we have age defined like <code>int age = 5 ;</code> , this is how the evaluation would be evaluated :</p>

<ol>
<li>Replacing we get :  <code>if ( ! 5 &gt;= 18 )</code></li>
<li><code>5 &gt;= 18</code> is evaluated first , resulting in <code>false</code> , because <code>5</code> is not Getter nor Equal to 18.</li>
<li>we would then have :  <code>if ( ! false )</code> </li>
<li><code>!false</code> is <code>true</code> , because the <code>!</code> changes the boolean value ( this is what it does )</li>
<li>we have : <code>if ( true )</code></li>
</ol>

<p>Is this making sense? </p>

<p>In fact, to demonstrate this better, look at the following code :</p>

<pre><code>boolean value = true;
System.out.println("Value is : " + value);
</code></pre>

<p>Executing this would produce :</p>

<pre><code>Value is : true
</code></pre>

<p>Now, modifying the code like this :</p>

<pre><code>boolean value = !true;
System.out.println("Value is : " + value);
</code></pre>

<p>Would produce :</p>

<pre><code>Value is : false
</code></pre>

<p>So, as you can see, the  <code>!</code> operator just inverts the boolean.</p>

<p>There are many many other ways to control the flow of execution of a program, <strong>If Statements</strong> are one , another is the <strong>Switch Statement</strong> , which is not used as much as the <em>If Statement</em> but is also important to know.</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="switchstatement">Switch Statement</h3>

<p>The <strong>Switch statement</strong> works a bit differently from the <em>If Statement</em>. The switch statement also takes an expression, but this expression must evaluate to <em>byte</em>, <em>short</em>, <em>char</em>,  <em>int</em>, <em>String</em>.</p>

<p>Lets look at the following example:</p>

<pre><code>int value = 1 ;

switch ( value ) {

    case 1:
        System.out.println("Detected");
        System.out.println("Value is 1");
        break;

}
</code></pre>

<p>If we were to execute this code, the result would be : </p>

<pre><code>Detected
Value is 1
</code></pre>

<p>So what this does is:</p>

<ol>
<li><p><code>switch ( value)</code> : the switch take the value the expression evaluates to. In this case the expression is just a value that evaluates to <code>int</code>.</p></li>
<li><p>The value of the expression gets compared with all the <code>case</code> options available. </p></li>
<li><p>Because the evaluation of the expression is  <code>1</code> and there is a <em>case</em> that matches that <code>case 1:</code> , everything after that is executed <strong>until a <code>break;</code> is found</strong>.</p></li>
</ol>

<p>Very simple! </p>

<p>Look at this modified version of the previous code:</p>

<pre><code>int value = 2 ;

switch (value) {
    case 1:
        System.out.println("Detected");
        System.out.println("Value is 1");
        break;
    case 2:
        System.out.println("Detected");
        System.out.println("Value is 2");
        break;
    case 3:
        System.out.println("Detected");
        System.out.println("Value is 3");
        break;
}
</code></pre>

<p>In this example we modified the value the expression evaluates to, and we added a few other cases.</p>

<p>Compiling and executing this will produce :</p>

<pre><code>Detected
Value is 2
</code></pre>

<p>There is also a special catch, which is the <code>default</code> case, which can be used to execute in case the expression does not evaluate to any of the other cases :</p>

<pre><code>int value = 5 ;

switch (value) {
    case 1:
        System.out.println("Detected");
        System.out.println("Value is 1");
        break;
    case 2:
        System.out.println("Detected");
        System.out.println("Value is 2");
        break;
    case 3 :
        System.out.println("Detected");
        System.out.println("Value is 3");
        break;
    default:
        System.out.println("Nothing Detected");
        break;
}
</code></pre>

<p>Compiling and executing this will produce :</p>

<pre><code>Nothing Detected
</code></pre>

<p>Very easy, yes ? But now , just out of curiosity, lets remove all the <code>breaks;</code> from the code. Give a look at this:</p>

<pre><code>int value = 2 ;

switch (value) {

    case 1:
        System.out.println("Detected");
        System.out.println("Value is 1");
        //break;
    case 2:
        System.out.println("Detected");
        System.out.println("Value is 2");
        //break;
    case 3 :
        System.out.println("Detected");
        System.out.println("Value is 3");
        //break;
    default:
        System.out.println("Nothing Detected");
        //break;
}
</code></pre>

<p>Executing would produce :</p>

<pre><code>Detected
Value is 2
Detected
Value is 3
Nothing Detected
</code></pre>

<p>Because value is now <code>2</code>, it does not match the first case, but it matches <code>case 2</code>, so it starts executing until it finds the <code>break;</code> statement, which does not exist, so it executes until the end of the <strong>Switch statement</strong>. </p>

<blockquote>
  <p>It is very important to remember that, if a case matches, execution will be until a <code>break;</code> is reached, or the Switch body ends.</p>
</blockquote>

<h3 id="wrappingup">Wrapping up</h3>

<p>So, with this basic knowledge of Flow Control, you are ready to try out a few exercises, just to get some practice in solving some small problems, and getting used to writing code. Check <a href="http://blog.jbaysolutions.com/learning-java-2-beginner-level/ ">the first exercises section</a> before going for the next Tutorial!</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h4 id="references">References</h4>

<ul>
<li><a href="https://en.wikipedia.org/wiki/Truth_table">Wikipedia - Truth Tables</a>  </li>
<li><a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html">Oracle Java Documentation - the switch statement</a></li>
</ul>

<script>  
function gotonow(anch) {  
    var curtop = 0;
    var obj = document.getElementById(anch);
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        window.scroll(0, [curtop]);
    }
    return false;
}
</script>]]></content:encoded></item><item><title><![CDATA[Java Tutorial 6 - Arrays]]></title><description><![CDATA[In Java, an array is: a structure that stores values. These have a few properties that are very important to understand, for setting and reading values.]]></description><link>http://blog.jbaysolutions.com/2016/03/29/tutorial-6-arrays/</link><guid isPermaLink="false">4c7641bf-09ff-4398-a0b5-04ee7ece3e27</guid><category><![CDATA[java]]></category><category><![CDATA[Learning Java from scratch]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Tue, 29 Mar 2016 14:56:28 GMT</pubDate><content:encoded><![CDATA[<ol>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-6-arrays/" onclick="gotonow('introduction');return false;">Introduction</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-6-arrays/" onclick="gotonow('arrays');return false;">Arrays</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-6-arrays/" onclick="gotonow('letstalkarrays');return false;">Lets talk Arrays</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-6-arrays/" onclick="gotonow('accessingvaluesofanarray');return false;">Accessing values of an Array</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-6-arrays/" onclick="gotonow('settingvaluesofelements');return false;">Setting values of elements</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-6-arrays/" onclick="gotonow('introduction');return false;">Initing with values</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-6-arrays/" onclick="gotonow('whatisthesizeofthisarray');return false;">What is the size of this array?</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-6-arrays/" onclick="gotonow('accessingusinginvalidindex');return false;">Accessing using invalid index</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-6-arrays/" onclick="gotonow('references');return false;">References</a></li>
</ol>

<h3 id="introduction">Introduction</h3>

<p>At this point we have all the knowledge we need to create Classes, methods, variables, instances of Objects, call methods, etc. These are the basic building blocks of any program made in Java.</p>

<p>In the last tutorial we finished with the following phrase: </p>

<blockquote>
  <p>Wouldn't it be nice to be able to have a list of Person objects stored in someway, instead of having to programmatically define a variable for each of the objects we create?</p>
</blockquote>

<p>Well, lets look at Arrays then!</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="arrays">Arrays</h3>

<p>For this Tutorial we will create another project with IntelliJ called <strong>"BeginnerJava6"</strong> , or just another empty folder named <strong>"BeginnerJava6"</strong> where we'll store our code. Create a package called <strong>"tutorial6"</strong>, and we'll write all our code inside this package. </p>

<p>Lets create a class caller <strong>Starter</strong> with a <code>main</code> method:</p>

<pre><code>package tutorial6;

public class Starter {
    public static void main(String[] args) {

    }
}
</code></pre>

<p>All very simple until now. </p>

<h4 id="letstalkarrays">Lets talk Arrays</h4>

<p>We'll kick it off with an example of an Array:</p>

<pre><code>int[] listOfInts = new int[10];
</code></pre>

<p><strong>What is an Array?</strong> In Java, the simplest way of describing an array is: a structure that stores values. These structure have a few properties that are very important to understand :</p>

<ul>
<li>They are of fixed size</li>
</ul>

<p>So, an array has a fixed size that is defined when the array is created. In our example of <code>listOfInts</code>, it is a structure that can take 10 elements : <code>new int[10]</code> </p>

<ul>
<li>It is typed </li>
</ul>

<p>Which means that they store elements of a specific type. This specific type is defined also when the array is created. In our example it stores <code>int</code> values. </p>

<ul>
<li>It is ordered </li>
</ul>

<p>This means that the elements have a specific position on the array, and that adding or removing elements, does not change the position or the remaining elements in the array. </p>

<p>These are a few examples of other types of arrays:</p>

<ul>
<li><code>float[] listOfFloats = new float[10];</code> - An array of floats of size 10</li>
<li><code>double[] listOfDoubles = new double[50];</code> - An array of doubles of size 50</li>
<li><code>String[] listOfStrings = new String[9000];</code> - An array of Strings of size 9000</li>
</ul>

<p>As you can see, the notation is quite simple! First the programmer defines the type of array it wants to work with, and a name for that array:</p>

<ul>
<li><code>int[] listOfInts</code> : This is the declaration part of the statement on our first example</li>
</ul>

<p>Then the programmer instantiates the array, using the <code>new</code> keyword, like it was an object, but instead of using the <code>( )</code> to pass arguments to a constructor, the programmer uses <code>[ ]</code> with the size of the array he need to create :</p>

<ul>
<li><code>new int[10]</code> : This is the instantiation part of the statement, where the size of the array is specified</li>
</ul>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<p>Lets create an array of <code>int</code>s inside the <code>main</code> method of the <em>Starter</em> class:</p>

<pre><code>package tutorial6;

public class Starter {

    public static void main(String[] args) {

        int[] listOfInts = new int[10];

    }

}
</code></pre>

<p>A few things to take notice, and recapping from the last tutorials :</p>

<ul>
<li>the <code>listOfInts</code> variable is of <strong>Method Level Scope</strong> </li>
<li>because it is of <strong>Method Level Scope</strong> , it only exist inside that method</li>
<li>and because it is of <strong>Method Level Scope</strong>  it does not have an <strong>Access Modifier</strong> </li>
<li>inside the <code>main</code> method we create the array variable and instantiate it with a size of 10</li>
<li>it does nothing else</li>
</ul>

<p>Everything is making sense, yes?</p>

<p>Very easy, give it a compile and run it. If it does absolutely nothing, that means that it is good.</p>

<h3 id="accessingvaluesofanarray">Accessing values of an Array</h3>

<p>To access the values inside the array we do :  <code>arrayName[ POSITION ]</code> where <em>POSITION</em> is the index of the array we want to access. </p>

<p>The index of an array is an <code>int</code> always starts at <strong>0</strong> and ends at <strong>size-1</strong> of the size defined at its instantiation.</p>

<p>Lets modify the <code>main</code> method of the <em>Starter</em> class to print all the elements of the array we are creating:</p>

<pre><code>public static void main(String[] args) {

    int[] listOfInts = new int[10];

    System.out.println("Value at index 0 : " + listOfInts[0] );
    System.out.println("Value at index 1 : " + listOfInts[1] );
    System.out.println("Value at index 2 : " + listOfInts[2] );
    System.out.println("Value at index 3 : " + listOfInts[3] );
    System.out.println("Value at index 4 : " + listOfInts[4] );
    System.out.println("Value at index 5 : " + listOfInts[5] );
    System.out.println("Value at index 6 : " + listOfInts[6] );
    System.out.println("Value at index 7 : " + listOfInts[7] );
    System.out.println("Value at index 8 : " + listOfInts[8] );
    System.out.println("Value at index 9 : " + listOfInts[9] );

}
</code></pre>

<p>Compile and run it. The result should be something like this:</p>

<pre><code>Value at index 0 : 0
Value at index 1 : 0
Value at index 2 : 0
Value at index 3 : 0
Value at index 4 : 0
Value at index 5 : 0
Value at index 6 : 0
Value at index 7 : 0
Value at index 8 : 0
Value at index 9 : 0
</code></pre>

<p>Notice that all <em>elements</em> of the array are filled with <code>0</code>s, this is an important detail to know about arrays, they are initialized with with default values of the type of array they are, hence:</p>

<ul>
<li><code>int[] ints = new int[10]</code> : all elements will be 0</li>
<li><code>double[] doubles = new doubles[10]</code> : all elements will be 0.0</li>
</ul>

<p>If the array was an array of objects, then the default value of each element would be <code>null</code>, which is to mean that the position is empty and has no object. We'll see more about what <code>null</code> means when looking at Reference Variables. Some examples :</p>

<ul>
<li><code>User[] users = new Users[10]</code>  : all elements will be  <code>null</code></li>
<li><code>String[] strings = new String[10]</code>  : all elements will be  <code>null</code></li>
</ul>

<p>Give it a try and see the results yourself.</p>

<p>Now we can read the elements in the array positions, but what about setting those values?</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="settingvaluesofelements">Setting values of elements</h3>

<p>To set the value of a particular element of an array we use the same notation as before:  <code>arrayName[ POSITION ]</code> where <em>POSITION</em> is the index of the array we want to access, and then we assign the value using the <code>=</code> operator, like so:</p>

<pre><code>listOfInts[5] = 1000;
</code></pre>

<p>This last statement will assign the value of <code>1000</code> to the element on the 6st position! Yes, 6st position, remember that the index starts at <code>0</code>, and <code>0</code> is the first position of the array.</p>

<p>As an exercise, modify the <code>main</code> method to first assign values to all elements of the array and then print them out.</p>

<p>The end result should be something like this:</p>

<pre><code>public static void main(String[] args) {

    int[] listOfInts = new int[10];

    listOfInts[0] = 199;
    listOfInts[1] = 9349;
    listOfInts[2] = 9229;
    listOfInts[3] = 11243;
    listOfInts[4] = 952;
    listOfInts[5] = 13;
    listOfInts[6] = 422;
    listOfInts[7] = 4239;
    listOfInts[8] = 527;
    listOfInts[9] = 874;


    System.out.println("Value at index 0 : " + listOfInts[0] );
    System.out.println("Value at index 1 : " + listOfInts[1] );
    System.out.println("Value at index 2 : " + listOfInts[2] );
    System.out.println("Value at index 3 : " + listOfInts[3] );
    System.out.println("Value at index 4 : " + listOfInts[4] );
    System.out.println("Value at index 5 : " + listOfInts[5] );
    System.out.println("Value at index 6 : " + listOfInts[6] );
    System.out.println("Value at index 7 : " + listOfInts[7] );
    System.out.println("Value at index 8 : " + listOfInts[8] );
    System.out.println("Value at index 9 : " + listOfInts[9] );

}
</code></pre>

<p>And running this last example will produce:</p>

<pre><code>Value at index 0 : 199
Value at index 1 : 9349
Value at index 2 : 9229
Value at index 3 : 11243
Value at index 4 : 952
Value at index 5 : 13
Value at index 6 : 422
Value at index 7 : 4239
Value at index 8 : 527
Value at index 9 : 874
</code></pre>

<p>There is another way to set the values of an array, which is to assign the values when initializing the array.</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="initingwithvalues">Initing with values</h3>

<p>In some cases, when we create an array we already know what values we want to place in it, and in those cases it makes a lot more sense to just set those values during instantiation, instead of instantiating an array with a specific size and then writing some more code to insert the values in their correct positions.</p>

<p>This is done in the following way:</p>

<pre><code>int[] listOfInts = new int[]{ 111,222,333,444,555,666,777,888,999,1000 };
</code></pre>

<p>This small example will create an array of <code>int</code>s called <code>listOfInts</code>, with a size of <code>10</code>although it is not specified directly, and with the following ints <code>111,222,333,444,555,666,777,888,999,1000</code> in their ordered position.</p>

<p>Notice that by using this notation :</p>

<ul>
<li>The size of the array is specified indirectly , it is the size of parameters provided.</li>
<li>The order of the values will be the corresponding index, starting with <code>0</code></li>
</ul>

<p>As an exercise, modify the <code>main</code> method to assign values during instantiation of the array, and print those values out.</p>

<p>The end <code>main</code> method should look something like this:</p>

<pre><code>public static void main(String[] args) {

    int[] listOfInts = new int[]{ 111,222,333,444,555,666,777,888,999,1000 };

    System.out.println("Value at index 0 : " + listOfInts[0] );
    System.out.println("Value at index 1 : " + listOfInts[1] );
    System.out.println("Value at index 2 : " + listOfInts[2] );
    System.out.println("Value at index 3 : " + listOfInts[3] );
    System.out.println("Value at index 4 : " + listOfInts[4] );
    System.out.println("Value at index 5 : " + listOfInts[5] );
    System.out.println("Value at index 6 : " + listOfInts[6] );
    System.out.println("Value at index 7 : " + listOfInts[7] );
    System.out.println("Value at index 8 : " + listOfInts[8] );
    System.out.println("Value at index 9 : " + listOfInts[9] );

}
</code></pre>

<p>Executing this last <code>main</code> method will produce:</p>

<pre><code>Value at index 0 : 111
Value at index 1 : 222
Value at index 2 : 333
Value at index 3 : 444
Value at index 4 : 555
Value at index 5 : 666
Value at index 6 : 777
Value at index 7 : 888
Value at index 8 : 999
Value at index 9 : 1000
</code></pre>

<h3 id="whatisthesizeofthisarray">What is the size of this array?</h3>

<p>Another really important detail of working with arrays, is getting the size of an array. In our examples thus far we created the arrays, we know the sizes, we know what they contain, but this might not always be the case.</p>

<p>To get the size of an array we access the <code>length</code> public int variable that exists on all arrays, because arrays are objects (remember, if a variable is not of a primitive type, it is an object) :</p>

<pre><code>listOfInts.length;
</code></pre>

<p>As an exercise, modify the <code>main</code> method we have been working with, and after printing all the values print also the size of the array.</p>

<p>The end result could look like this:</p>

<pre><code>public static void main(String[] args) {

    int[] listOfInts = new int[]{ 111,222,333,444,555,666,777,888,999,1000 };

    System.out.println("Value at index 0 : " + listOfInts[0] );
    System.out.println("Value at index 1 : " + listOfInts[1] );
    System.out.println("Value at index 2 : " + listOfInts[2] );
    System.out.println("Value at index 3 : " + listOfInts[3] );
    System.out.println("Value at index 4 : " + listOfInts[4] );
    System.out.println("Value at index 5 : " + listOfInts[5] );
    System.out.println("Value at index 6 : " + listOfInts[6] );
    System.out.println("Value at index 7 : " + listOfInts[7] );
    System.out.println("Value at index 8 : " + listOfInts[8] );
    System.out.println("Value at index 9 : " + listOfInts[9] );

    int size = listOfInts.length;
    System.out.println("Size of array is : " + size);

}
</code></pre>

<p>Notice that in this bit of code, this particular section :</p>

<pre><code>int size = listOfInts.length;
System.out.println("Size of array is : " + size);
</code></pre>

<p>Could be rewritten as:</p>

<pre><code>System.out.println("Size of array is : " + listOfInts.length);
</code></pre>

<p>Which would avoid creating another variable and assigning a value to that variable. </p>

<p>If you have been trying these exercises, and writing code as you are learning it, you probably already tried to access an element of an array using an index that is larger than the size of the array itself. If you did, then you got an error. Lets look at that now. </p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="accessingusinginvalidindex">Accessing using invalid index</h3>

<p>Like it was said in the beginning of this tutorial, an array has a fixed size, and it's index goes from <code>0</code> to <code>size-1</code>, so what happens when we use an index that is smaller than <code>0</code> or bigger than <code>size-1</code>?</p>

<p>Lets modify the <code>main</code> method to try it out:</p>

<pre><code>public static void main(String[] args) {

    int[] listOfInts = new int[10];
    System.out.println("Value at index 0 : " + listOfInts[-1] );

}
</code></pre>

<p>Compiling this code will produce no errors. </p>

<p>Running the compiled code will generate an exception:</p>

<pre><code>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at tutorial6.Starter.main(Starter.java:7)
</code></pre>

<p>The same is true for trying to set a value with an invalid index:</p>

<pre><code>int[] listOfInts = new int[10];
listOfInts[20] = 1000;
</code></pre>

<p>This will also produce an exception:</p>

<pre><code>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
at tutorial6.Starter.main(Starter.java:7)
</code></pre>

<p>One way to avoid these exceptions, of type <code>ArrayIndexOutOfBoundsException</code>, if to verify before if the index we are about to use is smaller or equal to the size of the array, and also larger than <code>0</code>. We'll see how to do that on the next tutorial.</p>

<p>If you feel ready, the next Tutorial : Tutorial 6 - Flow Control</p>

<h3 id="references">References</h3>

<ul>
<li><a href="https://docs.oracle.com/javase/8/docs/api/">Java 8 API Specification</a></li>
</ul>

<script>  
function gotonow(anch) {  
    var curtop = 0;
    var obj = document.getElementById(anch);
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        window.scroll(0, [curtop]);
    }
    return false;
}
</script>]]></content:encoded></item><item><title><![CDATA[Java Tutorial 5 - Packages and Access Modifiers]]></title><description><![CDATA[In this tutorial we'll finally look at Packages to organize our code, and also at Access Modifiers that allow us to restrict access to parts of our Classes.]]></description><link>http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/</link><guid isPermaLink="false">32cef8f6-d3d9-4e63-9cbb-9a26cddbf918</guid><category><![CDATA[java]]></category><category><![CDATA[Learning Java from scratch]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Tue, 29 Mar 2016 14:55:18 GMT</pubDate><content:encoded><![CDATA[<ol>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/" onclick="gotonow('introduction');return false;">Introduction</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/" onclick="gotonow('packages');return false;">Packages</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/" onclick="gotonow('overloading');return false;">Overloading</a> <br>
<ol><li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/" onclick="gotonow('thiskeyword');return false;"><code>this</code> Keyword</a></li></ol></li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/" onclick="gotonow('continuing');return false;">Continuing the code</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/" onclick="gotonow('callingmethodsfromanywhere');return false;">Calling methods from Anywhere</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/" onclick="gotonow('accessmodifiers');return false;">Access Modifiers</a> <br>
<ol><li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/" onclick="gotonow('public');return false;">Public</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/" onclick="gotonow('private');return false;">Private</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/" onclick="gotonow('packageprotected');return false;">Package-Protected</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/" onclick="gotonow('protected');return false;">Protected</a></li></ol></li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/" onclick="gotonow('usingaccessmodifiers');return false;">Using Access Modifiers</a> <br>
<ol><li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/" onclick="gotonow('whataboutconstructors');return false;">What about Constructors?</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/" onclick="gotonow('whataboutmethodlevelscopevariables');return false;">What about Methods Level Scope Variables?</a></li></ol></li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/" onclick="gotonow('manyobjects');return false;">Many objects</a></li>
</ol>

<h3 id="introduction">Introduction</h3>

<p>In this tutorial we'll finally look at Packages to organize our code, and also at Access Modifiers that will allow us to restrict access to parts of our Classes.</p>

<p>By this point you show have an understanding of how to create a new Class, create new objects of a class type, create variables and know that there are primitive types. If you don't, the please check the <a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-3-variables-first-look-at-primitive-variables-and-operators/">Tutorial 3 - Variables</a> and <a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-4-classes-constructors-and-methods/">Tutorial 4 - Classes, Constructors and Methods</a> .</p>

<p>So, if you have <a href="https://www.jetbrains.com/idea/">IntelliJ Community Edition</a> installed and would like to use it, just open it up and <em>Create a New Project</em>, of Java type, and select no other libraries nor Frameworks. Call it <strong>"BeginnerJava5"</strong>. If you are using a text editor, just create a new Folder somewhere on your disc and call it <strong>"BeginnerJava5"</strong>. </p>

<p>We'll develop a very rudimentary system that creates and stores data on Persons, much like we did on the previous tutorial. We'll do it from scratch, and now learn about Packages in Java. </p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<p>Lets start with creating a class called <strong>Starter</strong>, so using IntelliJ on the left tree find the <strong>"src"</strong> folder, right click in it and select <em>"new"</em> -> <em>"Java Class"</em> .  If you are using a the text editor, create a file called "Starter.java" on the root of the folder you previously created.</p>

<pre><code>public class Starter {
}
</code></pre>

<p>This is our <em>Starter</em> class. Lets create a <em>main</em> method and make it print out something:</p>

<pre><code>public class Starter {

    public static void main(String[] args) {
        System.out.println("Starting program");
    }

}
</code></pre>

<p>Compile it and run it. If you are using IntelliJ simply press <em>Ctrl+Shift-F10</em>. </p>

<p>Everything should be fine to this point. </p>

<p>Now we'll go and implement the User class, but before we do, lets think a little about how we want to organize our Classes. For a project so small as this one it wouldn't be a problem to have all Classes in the same place, but imagine for a project that will have tens or hundreds or thousands of Classes? Having a large project with all its classes in the same place would be a nightmare to manage, and work with. </p>

<blockquote>
  <p>There is the concept of Packages in Java, which allows the programmers to organize their classes in a tree like fashion.</p>
</blockquote>

<h3 id="packages">Packages</h3>

<p>Every project in Java should have its package, the exception being that the project will never ever be used again in any sort of productive way. Lets call this a rule. </p>

<p>Because we are programming a <strong>Person</strong> management system, and because we want to do it right, well create a package for this project. We'll call it <code>tutorials.personmanagement</code> .</p>

<p>There is a naming convention as to what the package name of a software or library should be and what rules should be follow:</p>

<ul>
<li>Package names are in all lowercase</li>
<li>If the project is developed by a company, organization, or person that has an internet domain, the reverse of the domain is used to start the name of the package. </li>
</ul>

<p>For example, if this was a project developed by <em>JBay Solutions</em>  and this project is a <em>Printing Money Software</em>, then because JBay Solutions has the domain <em>jbaysolutions.com</em> the package could be called for example:</p>

<ul>
<li><code>com.jbaysolutions.printingmoney</code></li>
<li><code>com.jbaysolutions.printmoneysoftware</code></li>
<li><code>com.jbaysolutions.lib.printingmoney</code></li>
</ul>

<p>There is a bit of freedom to choose the name of the package, but its goal is to avoid conflicts! By following these rules, it is very unlikely that you'll find conflicts of Classes with the same name, inside packages with the same name, in different libraries.</p>

<p>So, our package is going to be called <code>tutorials.personmanagement</code>. </p>

<p>If you are using IntelliJ just right-click on the <em>"src"</em> folder on the Project tree on the right, and select <em>"new"</em> -> <em>"Package"</em> . Just type in : <strong>tutorials.personmanagement</strong> .</p>

<p>If you are using the text editor, then just go to the folder of the project, and create a folder named "<em>tutorials</em>" and then inside that folder create another folder called "<em>personmanagement</em>" . </p>

<p>So now we have the Package for the project, we'll start with the creation of the <strong>Person</strong> class, inside the <em>tutorials.personmanagement</em> package . Just go ahead and create the <strong>Person</strong> class, with no methods and no variables.</p>

<p>If you use IntelliJ it should look like this:</p>

<pre><code>package tutorials.personmanagement;

public class Person {
}
</code></pre>

<p>If you created the Class in a normal Text Editor, then you are probably missing the first line:</p>

<pre><code>package tutorials.personmanagement;
</code></pre>

<p>Because this <strong>Person</strong> class "belongs" to a package, not only must the file be created inside that specific folder, <em>the first statement of that Class must be the definition of the package it belongs to</em>. </p>

<p>This would also be correct, because the Comments and Blank lines obviously don't count as statements:</p>

<pre><code>// This is a comment

/*
 This is also a comment 
*/

package tutorials.personmanagement;

public class Person {
}
</code></pre>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<p>For our software, a Person will have the following attributes:</p>

<ul>
<li>A Name - <em>String</em></li>
<li>An Age - <em>int</em></li>
<li>A Salary - <em>double</em></li>
</ul>

<p>Lets implement this class then, with the Getter and Setter methods for all the properties, and also create 2 constructors, one that takes all 3 parameters and one that takes just the Name and Age, because under aged people will not have a salary. </p>

<p>We should end up with a class somewhat like this :</p>

<pre><code>package tutorials.personmanagement;

public class Person {

    String name;
    int age;
    double salary;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}
</code></pre>

<p>Notice that in this class we have two constructors. <em>This is valid, because the constructors have different signatures</em>. </p>

<blockquote>
  <p>Likewise we could have several methods with the exact same name, as long as input paramenters part of the signature is different. This is called method <strong>overloading</strong> , or in our particular case here, <strong>constructor overloading</strong>. </p>
</blockquote>

<h3 id="overloading">Overloading</h3>

<p>Lets think about this "Overloading" thing for a second.</p>

<p>We have two Constructors like this:</p>

<ul>
<li><code>public Person(String name, int age, double salary)</code></li>
<li><code>public Person(String name, int age)</code></li>
</ul>

<blockquote>
  <p>Why is this allowed? The simple reason is : you call them in different ways!</p>
</blockquote>

<p>Because you call them in different ways, the JVM, when it is executing, will know exactly which constructor to use based on the input you provide.</p>

<p>As an example, imagine you will be creating a Person object with the following code:</p>

<pre><code>Person person = new Person( "Rui", 35 );
</code></pre>

<p>The JVM knows that you are trying to call a constructor that takes as input a <strong>String</strong> and an <strong>int</strong> in this particular order. It will then look at the class Person and see if there is a Constructor that matches this. It finds it and uses it:</p>

<ul>
<li><code>public Person(String name, int age)</code></li>
</ul>

<p>It will not be able to use the other Constructor : </p>

<ul>
<li><code>public Person(String name, int age, double salary)</code></li>
</ul>

<p>Likewise, if we try to create a Person object with the following code:</p>

<pre><code>Person person = new Person( "Rui", 35 , 1000.0 );
</code></pre>

<p>It will only be able to use the second constructor.</p>

<blockquote>
  <p>Overloading works exactly in the same way for methods.</p>
</blockquote>

<p>Also, if we look at one of the constructor, we will notice that the names of the parameters provided are exactly the same as the names of the Class level variables:</p>

<pre><code>String name;
int age;
double salary;

public Person(String name, int age) {
    this.name = name;
    this.age = age;
}
</code></pre>

<p>These are effectively two different variables, one that has a <strong>Class Level Scope</strong>, and one that has a <strong>Method Level Scope</strong> (check the previous Tutorial to understand more about variables scope <a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-4-classes-constructors-and-methods/">Here</a>) .  </p>

<blockquote>
  <p>This is legal, because they are defined in different scopes. </p>
</blockquote>

<p>But now, because we can access two variables with the same name from inside the method (or constructor in our case), there has to be a way to unequivocally specify which variable we are referring to, hence the use of the keyword <strong>this</strong> . </p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="thiskeyword">this Keyword</h3>

<p>From inside a method, the keyword <strong>this</strong> is used to reference the Object the method belong to. In this particular case, inside the constructor, the <code>this.name</code> specifies unequivocally that we are referring to the <code>String name</code> variable defined outside the method. </p>

<p>If we have this Constructor instead:</p>

<pre><code>String name;
int age;
double salary;

public Person(String name, int age) {
    name = name;
    age = age;
}
</code></pre>

<p>Because we are not using the <strong>this</strong> keyword, then we will be referring to the <code>String name</code> variable that is passed as argument, and therefore we would not be affecting any of the Class Level variables that exist on the class. </p>

<p>Notice also that on the Setter methods of the class, we also use the same name for the input argument as we use for the Class variables, and therefore we need to use the <strong>this</strong> keyword:</p>

<pre><code>public void setName(String name) {
    this.name = name;
}
</code></pre>

<p>Also, keep in mind that the following method would be valid and would accomplish the same result as the previous method:</p>

<pre><code>public void setName(String newName) {
    this.name = newName;
}
</code></pre>

<p><strong>In this particular case the use of the <code>this</code> keyword is redundant</strong>, because there is no ambiguity as to which variables we are referring to, but it is legal and correct non the less. </p>

<p>Lets continue with the code.</p>

<h3 id="continuing">Continuing</h3>

<p>On our <strong>Starter</strong> class, which does not have a package, we only have the <em>main</em> method, which is at this point printing a String. Lets modify the <em>main</em> method to now create an object o type <strong>Person</strong>:</p>

<pre><code>public class Starter {

    public static void main(String[] args) {
        System.out.println("Starting program");        
        Person person = new Person("Rui", 35);
    }

}
</code></pre>

<p>If you are using IntelliJ or any other IDE, the source code should be showing some errors. This is because the <strong>Starter</strong> doesn't know what <strong>Person</strong> is, nor where it is. We must <strong>import</strong> the Class to let <strong>Starter</strong> know that when we refer to <strong>Person</strong> we are talking about a specific class:</p>

<pre><code>import tutorials.personmanagement.Person;

public class Starter {

    public static void main(String[] args) {
        System.out.println("Starting program");

        Person person = new Person("Rui", 35);
    }

}
</code></pre>

<p>As you can see, in the first line of this class, we added an import statement:</p>

<pre><code>import tutorials.personmanagement.Person;
</code></pre>

<blockquote>
  <p>This is how it works: If a programmer is writing some code in a Class that uses other Classes, then, if the other Classes are not in the same exact Package, the programmer needs to import either the specific class, or everything inside the Package of the other classes:</p>
</blockquote>

<ul>
<li><code>import tutorials.personmanagement.Person;</code>  : Importing specific class</li>
<li><code>import tutorials.personmanagement.* ;</code>   : Importing every class inside this package</li>
</ul>

<p>Usually a programmer will import only the Class that is needed, unless there are several Classes inside a package that are going to all be needed, and in that case, the programmer imports all the Classes inside a Package using the <code>*</code> notation. </p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<p><strong>Why is this important?</strong></p>

<p>Imagine for a second that you are developing a big project that has a visual component that draws Squares on the screen, and a computational side that calculates areas of Squares. You will possibily have two classes called <strong>Square</strong> on two different packages : </p>

<ul>
<li><code>com.project.render.Square</code></li>
<li><code>com.project.area.Square</code></li>
</ul>

<p>When writting the code, depending of which part the programmer is now coding, he will need to import a different <code>Square</code> class. This gets even more tricky when a project uses libraries that were developed by a 3rd party, and you don't know all the names of all the classes that exist inside that 3rd party library. </p>

<blockquote>
  <p>The import statements are always placed between the Package statement and the beginning of the class </p>
</blockquote>

<p>Like this:</p>

<pre><code>package com.project;

import com.project.render.Square;

public class Example {
    [ETC ETC ETC]
}
</code></pre>

<p>If the specific class you will need to import stuff into does not belong to a Package, then the import statements should be the first statements of the file. (Obviously not counting the comments)</p>

<p>Compile and run what you have until now, and see if the import works ( <em>Ctrl+Shift+F10</em> or <em>Shift+F10</em> on IntelliJ) .</p>

<h3 id="callingmethodsfromanywhere">Calling methods from anywhere</h3>

<p>In the previous part of this tutorial we created a <strong>Person</strong> class, and a <strong>Starter</strong> class where we create an instance of Person with some values. Lets now modify the Person object that was created and change the value of the <code>name</code> variable for that object, and lets also modify the <strong>Person</strong> class to add a method for printing the values of the variables. We'll start with the method of the <strong>Person</strong> class:</p>

<pre><code>public void printData() {
    System.out.println("Value for name is : " + name);
    System.out.println("Value for age is : " + age);
    System.out.println("Value for salary is : " + salary);
}
</code></pre>

<p>Very simple, like we did on the previous tutorials. </p>

<p>Now, lets modify the <code>main</code> method on the <strong>Starter</strong> class, to modify the <code>name</code> property of the object and also print out the values of the object afterwards:</p>

<pre><code>public static void main(String[] args) {
    System.out.println("Starting program");

    Person person = new Person("Rui", 35);
    person.setName("Super Rui");
    person.printData();
}
</code></pre>

<p>Compiling and running it we get :</p>

<pre><code>Starting program
Value for name is : Super Rui
Value for age is : 35
Value for salary is : 0.0
</code></pre>

<p>The first thing to notice here is that the Constructor used for creating the <strong>Person</strong> object was the Constructor that only takes in <code>String name</code> and <code>int age</code> , and therefore <code>salary</code> was never ever set! But when we print, the value of <code>salary</code> is <code>0.0</code>. </p>

<blockquote>
  <p>This is because, for <strong>Class Level Scope</strong> <em>primitive</em> typed variables (yes... all these names we have just learned), when not assigned, they take their default value, which for a <code>double</code> is <code>0.0</code>.  </p>
</blockquote>

<p>The second thing to notice is that the change of the <code>name</code> was done through a Setter method, which is correct, but is not enforced here, which is bad. We'll see how to enforce that in a minute with <strong>Access Modifiers</strong>. </p>

<p>For our example of a Person Management System, we want that every time that a <strong>Person</strong> is created or properties are modified on a <strong>Person</strong> object, the Software shows some Logs. To do this, we will implement a method on the <strong>Person</strong> class that prints a provided message. We'll call that method <code>logToConsole</code> and we define it like this :</p>

<pre><code>public void logToConsole(String message) {
    System.out.println("PERSON LOG - " + message);
}
</code></pre>

<p>So, every time this method is called with a <code>message</code>, it will writen to the console with a <code>PERSON LOG -</code> prefix. </p>

<p>Now, we'll modify every Setter method on the <strong>Person</strong> class to call this method before changing the value of a variable. We'll also modify the Constructors to call this method when they are called. </p>

<p>The final <em>*Person</em> class should look something like this now:</p>

<pre><code>package tutorials.personmanagement;

public class Person {

    String name;
    int age;
    double salary;

    public Person(String name, int age) {
        logToConsole("Creating Person with name: " + name + " age: " + age);

        this.name = name;
        this.age = age;
    }

    public Person(String name, int age, double salary) {
        logToConsole("Creating Person with name: " + name + " age: " + age + " salary: " +salary);

        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public void logToConsole(String message) {
        System.out.println("PERSON LOG - " + message);
    }

    public void printData() {
        System.out.println("Value for name is : " + name);
        System.out.println("Value for age is : " + age);
        System.out.println("Value for salary is : " + salary);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        logToConsole("name modified to: " + name );

        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        logToConsole("age modified to: " + age);

        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        logToConsole("salary modified to: " + salary );

        this.salary = salary;
    }
}
</code></pre>

<p>Looking, for example, at the <code>setName</code> method we have:</p>

<pre><code>public void setName(String name) {
    logToConsole("name modified to: " + name );

    this.name = name;
}
</code></pre>

<p>Which mean that before assigning the provided <code>name</code> value to the class variable <code>name</code> , we call the method <code>logToConsole</code> and  print the value out.</p>

<p>Compiling the project now and running it will return something like this:</p>

<pre><code>Starting program
PERSON LOG - Creating Person with name: Rui age: 35
PERSON LOG - name modified to: Super Rui
Value for name is : Super Rui
Value for age is : 35
Value for salary is : 0.0
</code></pre>

<p>Notice that we have 2 LOGs on the output. The first which corresponds to the Constructor , which should the values used on the creation of the <strong>Person</strong> object, and the second one which if for the call of the <code>setName</code> method. </p>

<p>Lets say now that we are very sneaky and lets try to call the <code>logToConsole</code> method from the <code>main</code> method in this way :</p>

<pre><code>public static void main(String[] args) {
    System.out.println("Starting program");

    Person person = new Person("Rui", 35);
    person.setName("Super Rui");

    person.logToConsole("name modified to: MEGA MEGA RUI");

    person.printData();
}
</code></pre>

<p>When we compile and run it we get:</p>

<pre><code>Starting program
PERSON LOG - Creating Person with name: Rui age: 35
PERSON LOG - name modified to: Super Rui
PERSON LOG - name modified to: MEGA MEGA RUI
Value for name is : Super Rui
Value for age is : 35
Value for salary is : 0.0
</code></pre>

<p>We now have 3 LOGs on the output, we have the third LOG saying that the name was modified to <code>"MEGA MEGA RUI"</code> but when we call the <code>printData</code> method, we see that the value for name is still <code>"Super Rui"</code>. We understand why, because we called the <code>logToConsole</code> function, which simply prints things to the console, and not the <code>setName</code> Setter Method which also prints things (through the use of <code>logToConsole</code>) but also modifies the value of the <code>name</code> variable. We know this, but other users, that might be looking at the LOGs will not get this, and will wonder why the name was not modified. </p>

<p>The reason why this can happen is because everyone can call <code>logToConsole</code>. </p>

<p><strong>Problems can even be worst</strong>, for example, with the <code>salary</code> variable. Imagine that the Setter method for Salary has some other code that calculates Taxes, and other things that are related to money. It would be a very big security issue if a programmer would modify the value of the <code>salary</code> of a person directly without using the Setter method, or print LOGs saying that the salary was modified, but nothing was actually changed on the <strong>Person</strong> object in question. </p>

<p>Enter the <strong>Access Modifiers</strong>. </p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="accessmodifiers">Access Modifiers</h3>

<p>Since the first tutorial of this series, every method and class we created started with the <code>public</code> keyword. This is the Access Modifier of the Class or Method, which in all our examples was <code>public</code>, which is the least restrictive Access Modifier that there is. </p>

<p>There are in total 4 Access Modifiers:</p>

<ul>
<li><code>public</code></li>
<li><code>protected</code></li>
<li>no modifier (package-protected)</li>
<li><code>private</code></li>
</ul>

<h4 id="public">Public</h4>

<p>A method that is public is a method that can be called from anywhere in the code. You can call it from inside the same class, from a different class in the same package, from a different class on a different package, etc. The same goes for Class Level Scope variables, you can access these variables from anywhere.</p>

<h4 id="private">Private</h4>

<p>A method that is private is a method can can only be called from the same Class where it is declared. The same goes for Class Level Scope variables, these can only be accessed from inside the same Class where they are declared.</p>

<h4 id="packageprotected">Package-Protected</h4>

<p>The package-protected is a modifier which does not have a specific name, but is usually referred to as the <strong>Package-Protected</strong> access modifier, or <strong>Package Level</strong> access modifier, which is when a method or a variable have no Access Modifier defined. An example is :</p>

<pre><code>public class Person {

    String name;  // &lt;-- Package-Protected Access Modifier
    int age;  // &lt;-- Package-Protected Access Modifier
    double salary;  // &lt;-- Package-Protected Access Modifier

}
</code></pre>

<p>These three <strong>Class Level Scope variables</strong> have the <strong>Package-protected</strong> access modifier , because they don't have an Access Modifier defined. </p>

<p>What this means is that these variables can be accessed directly only from the Class they are declared in, or from other Class that belong to the same package. </p>

<h4 id="protected">Protected</h4>

<p>The protected Access Modifier is almost the same as the Package Access Modifier ( or "no modifier" ) , which means that the method or variable can be accessed from Classes that belong to the same package, but also from Subclasses even if they are in other packages. What is a Subclass? Well get back to this in a few tutorials, but it is nothing to worry about.</p>

<blockquote>
  <p>All these Access Modifiers can be applied Methods and Class Level Scope Variables.</p>
  
  <p>As for Classes, they can only be "public" or "Package level" . Private and protected  make no sense to Classes, and therefore cannot be used. </p>
</blockquote>

<h3 id="usingaccessmodifiers">Using Access Modifiers</h3>

<p>Looking at our <strong>Person</strong> Class, we see that we have 3 variables that are package-protected:</p>

<pre><code>String name;
int age;
double salary;
</code></pre>

<p>It makes no sense to have them as <strong>Package-Protected</strong> because they are only meaningful to the Object they belong to. Also, because they have Getter and Setter methods, it makes no sense to allow them to be accessed and modified from outside of this Class. We should make them <code>private</code>, like so:</p>

<pre><code>public class Person {

    private String name;
    private int age;
    private double salary;
</code></pre>

<p>What about the methods? The Getter and Setter methods, because we want to be able to access them from other classes, even outside of the package this class belongs to, we leave them as <code>public</code>. </p>

<p>What about the <code>logToConsole</code> method? Because we only want this method to be called from inside the <strong>Person</strong> class, and avoid other developers ruining the LOGs we produce, we'll make the method <code>private</code> :</p>

<pre><code>private void logToConsole(String message) {
    System.out.println("PERSON LOG - " + message);
}
</code></pre>

<p>Making this change to the <code>logToConsole</code> method will make calling it from the <code>main</code> method at <strong>Starter</strong> illegal and will generate an error if we try to Compile. Try it and see for yourself (really, try it) . </p>

<p>Lets now remove the call to <code>logToConsole</code> method from the <code>main</code> method (or comment it out), and give it a compile and run.</p>

<pre><code>public static void main(String[] args) {
    System.out.println("Starting program");

    Person person = new Person("Rui", 35);
    person.setName("Super Rui");

    //person.logToConsole("name modified to: MEGA MEGA RUI");  

    person.printData();
}
</code></pre>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h4 id="whataboutconstructors">What about Constructors?</h4>

<p>Constructors are like methods and therefore can have any Access Modifier, even the "private" modifier. You'll see examples of it later on.</p>

<h4 id="whataboutmethodlevelscopevariables">What about Method Level Scope Variables?</h4>

<p>Method Level Scope Variables don't have an Access Modifier, because they are only accessible from inside the specific method they are created in. Also, it wouldn't make any sense to have them have an Access Modifier because they only exist during the execution of the method they belong to, and after the method execution they stop existing. </p>

<h3 id="manyobjects">Many objects</h3>

<p>As an exercise, lets now modify the <code>main</code> method to make it create 2 objects of type <strong>Person</strong> , using the two different Constructors we have, and then print the data on both the objects using the <code>printData</code> method.</p>

<p>If should look something like this :</p>

<pre><code>public static void main(String[] args) {
    System.out.println("Starting program");

    Person person = new Person("Rui", 35);
    person.setName("Super Rui");

    Person person2 = new Person("Miguel", 90, 500.0);

    person.printData();
    person2.printData();
}
</code></pre>

<p>Compile and run it. The result should look like:</p>

<pre><code>Starting program
PERSON LOG - Creating Person with name: Rui age: 35
PERSON LOG - name modified to: Super Rui
PERSON LOG - Creating Person with name: Miguel age: 90 salary: 500.0
Value for name is : Super Rui
Value for age is : 35
Value for salary is : 0.0
Value for name is : Miguel
Value for age is : 90
Value for salary is : 500.0
</code></pre>

<p>Wouldn't it be nice to be able to have a list of <strong>Person</strong> objects stored in someway, instead of having to programmatically define a variable for each of the objects we create? Yes , and we'll look into of doing it in the next tutorial.</p>

<p>Further Reading :</p>

<ul>
<li>Primitive Types in details</li>
</ul>

<p>Lets jump to the next Tutorial : <a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-6-arrays/">Tutorial 6 - Arrays</a></p>

<script>  
function gotonow(anch) {  
    var curtop = 0;
    var obj = document.getElementById(anch);
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        window.scroll(0, [curtop]);
    }
    return false;
}
</script>]]></content:encoded></item><item><title><![CDATA[Java Tutorial 4 - Classes, Constructors and Methods]]></title><description><![CDATA[In this tutorial  we'll now look at Objects and Reference Variables, and we'll start  understanding the Scope of variables.]]></description><link>http://blog.jbaysolutions.com/2016/03/29/tutorial-4-classes-constructors-and-methods/</link><guid isPermaLink="false">00589eda-0863-47eb-ac0f-ae6ec3e33804</guid><category><![CDATA[java]]></category><category><![CDATA[Learning Java from scratch]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Tue, 29 Mar 2016 14:54:38 GMT</pubDate><content:encoded><![CDATA[<ol>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-4-classes-constructors-and-methods/" onclick="gotonow('introduction');return false;">Introduction</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-4-classes-constructors-and-methods/" onclick="gotonow('variablesscope');return false;">Variables Scope</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-4-classes-constructors-and-methods/" onclick="gotonow('classesandobjects');return false;">Classes and Objects</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-4-classes-constructors-and-methods/" onclick="gotonow('creatingmethods');return false;">Creating methods</a> <br>
<ol><li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-4-classes-constructors-and-methods/" onclick="gotonow('settermethods');return false;">Setter Methods</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-4-classes-constructors-and-methods/" onclick="gotonow('gettermethods');return false;">Getter Methods</a></li></ol></li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-4-classes-constructors-and-methods/" onclick="gotonow('constructor');return false;">Constructors</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-4-classes-constructors-and-methods/" onclick="gotonow('exercise');return false;">Exercise</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-4-classes-constructors-and-methods/" onclick="gotonow('whatelseaboutmethods');return false;">What else about methods?</a></li>
</ol>

<h3 id="introduction">Introduction</h3>

<p>In the previous tutorials we dabbed into Primitive variables, did a few operations with them, nothing special or exciting. </p>

<p>In this tutorial however, we'll now look at Objects and Reference Variables, and we'll start with understanding the Scope of variables.</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="variablesscope">Variables Scope</h3>

<p>In our previous examples, the ones shown in the previous tutorial, all our variables were defined and used inside a method. What this means is that those variables are only available inside that method, they are created and erased and recreated with each time that method is executed. </p>

<p>Look at the next Class:</p>

<pre><code>public class Scope {

    int classVariable = 1;

    public void methodNumber1() {

        int methodVariable1 = 2 ;

    }

    public void methodNumber2() {

        int methodVariable2 = 3 ;

    }
}
</code></pre>

<p>There are a total of 3 variables defined in this Class. </p>

<ul>
<li><p><code>classVariable</code>: This variable can be accessed from anywhere inside the Class and it can be accessed from inside any of the methods inside that Class. Just as a side note, this is called a variable with <strong>Class Level Scope</strong>.</p></li>
<li><p><code>methodVariable1</code> and <code>methodVariable2</code> : These variables can be accessed only from inside the methods they are defined in. In fact, they don't exist outside of the execution of their method, and therefore, <em>methodNumber2</em> cannot access (read, write... print) <em>methodVariable1</em>, because that variable is only defined inside <em>methodNumber1</em>. This is called having <strong>Method Level Scope</strong>.</p></li>
</ul>

<p>The names <strong>Class Level Scope</strong> and <strong>Method Level Scope</strong> are not really important to know, but what they imply is. <code>methodVariable1</code>  and <code>methodVariable2</code> exist only inside their respective methods. They could even have the exact same name, it wouldn't matter, they don't exist outside of the methods. </p>

<p>Code indentation (writing code in an organized way, like we have been doing so far) really helps a lot to understand the scope of variables.</p>

<h2 id="classesandobjects">Classes and Objects</h2>

<p>To explain the concept of Objects and Classes, we'll implement a very rudimentary system that creates and stores Users and some attributes of each of the Users, and then prints out a listing of this information, formatted in some particular way. </p>

<p>Because we know we will be storing Users, and those users have attributes, we know that the best way to organize this information would be to have a "template" for what a user should have. We'll start with the creation of a <strong>User class</strong>. </p>

<p>Create a new file called  <strong><em>User.java</em></strong>  inside an empty folder that will be used for this tutorial, and write the code for the class:</p>

<pre><code>public class User {

}
</code></pre>

<p>This Class, as it is, will store absolutely nothing, and it has no methods defined, so in practice it will do nothing. </p>

<p>Lets say that our Users will all have a name and an age:</p>

<pre><code>public class User {

    String name;
    int age;

}
</code></pre>

<p>So this class can now be used to store two pieces of data : </p>

<ul>
<li>a name, of <strong>type String</strong></li>
<li>an age, of <strong>type int</strong></li>
</ul>

<p>But let us discuss it a bit further. </p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<p>As we saw in the previous tutorial, and <em>int</em> is a primitive type that uses 32bits. It can be a number that goes as high as 2^31-1, so it is very unlikely (if not biologically impossible) that someone will ever be that age. We could actually use a byte to store the age of the User, it would save memory (if that is a concern) . </p>

<p>We'll choose to continue using an <em>int</em>, for no particular reason. </p>

<p>We also have a variable named <em>name</em> of type <em>String</em>. <strong>String</strong> is a very particular type, it is not a primitive (it is in a way a collection of chars) but can be declared like a primitive, and also some operators work on it ( like the + operator, when we concatenate Strings). We'll talk about String in a second.</p>

<p>Another difference from what we have been doing so far, is that there is no <code>main</code> method on this class. <em>This means that you cannot execute this class, and therefore the <code>main</code> method must exist in another class, if the project is to be executed.</em> </p>

<p>Without closing the <strong>User.java</strong> file, create another file, right next to the <strong>User.java</strong> file, and call it "LessonExecution3.java" . This will be the Class that starts the program, and will make use of the <strong>User</strong> class. Create the <strong>LessonExecution3</strong> class and create a <code>main</code> method in it. It should look like this:</p>

<pre><code>public class LessonExecution3 {

    public static void main(String[] args) {

    }

}
</code></pre>

<p>Now, lets create a User and store it, we'll specify the name and the age of the user, and then, we will print that data:</p>

<pre><code>public static void main(String[] args) {
    User user = new User();
    user.name = "Rui";
    user.age = 35;

    System.out.println( "User Name: " + user.name );
    System.out.println( "User Age: " + user.age );
}
</code></pre>

<p>Compile and run both files like this:</p>

<pre><code>javac User.java LessonExecution3.java
java  LessonExecution3
</code></pre>

<p>The output should be something like:</p>

<pre><code>User Name: Rui
User Age: 35
</code></pre>

<p>Lets look at the inside of the <code>main</code> method we have just created inside the <strong>LessonExecution3</strong> class. </p>

<p>We start with the statement: </p>

<pre><code>User user = new User();
</code></pre>

<p>We know that User is a class, and therefore what we are doing here is creating a variable of that Type, and assigning a newly created Object of that type to the variable:</p>

<ul>
<li><code>User user</code> :  creating a variable of type User</li>
<li><code>new User()</code> :  creating an Object of type User</li>
<li><code>User user = new User()</code> : Assigning the object to the variable.</li>
</ul>

<p>When creating an object, the notation is always <code>new Object</code> , with emphasis on the word <strong><code>new</code></strong> . </p>

<p>So. after we create and assign an Object of type User to the variable named <strong><code>user</code></strong>, we access the variables inside that object using the <strong><code>.</code></strong> (dot) notation:</p>

<pre><code>user.name = "Rui";
user.age = 35;
</code></pre>

<p>Notice that when we access the variables inside the newly created object, we use name of the variable of the object, and the name of the variable inside that object. Looking at  <code>user.name</code> we can break it down like this:</p>

<ul>
<li><code>user</code> :  the name of the variable , not the name of the Class!</li>
<li><code>name</code> :  the name of the variable inside that particular object!</li>
</ul>

<p>Remember, we don't do something like <code>User.name</code> because <strong>User</strong> is the name of the Class, and the Class, like we said before is just a template for objects to be created.</p>

<p>After we access the variables to assign them values, we perform the <code>System.out.println()</code> statements, where we access the variables inside the particular Object and print those values out. </p>

<p>This works, but lets make it better! </p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="creatingmethods">Creating Methods</h3>

<p>Now, the printing of data of the User object is being done on the <code>main</code> method, which is not very wise if one wants to print the contents of several User objects, because it would mean that there would have to be as many <code>System.out.println</code> as twice the number of User objects created.</p>

<p>A method that prints this same data could be easily created. Lets do it.</p>

<p>Go to the <strong>User</strong> class source code file, and modify it to look like this :</p>

<pre><code>public class User {

    String name;
    int age;

    public void printData() {
        System.out.println( "User Name: " + name );
        System.out.println( "User Age: " + age );
    }

}
</code></pre>

<p>In this updated version of the User class, we have now a method called <code>printData</code> that :</p>

<ul>
<li>returns nothing : <code>void</code></li>
<li>receives nothing : <code>()</code></li>
<li>performs some <code>System.out.println()</code> statements inside.</li>
</ul>

<p>Notice that when we do the printing inside this method, we access the variables directly, without using the <strong>dot</strong> notation. This is because : </p>

<ul>
<li>the scope of those variables makes them accessible from that method</li>
<li>Also, the variable <strong><code>User user</code></strong> does not exist on this class, it is only accessible from the <em>LessonExecution3</em> class, inside the <code>main</code> method. </li>
</ul>

<p>Now the <code>main</code> method of <em>LessonExecution3</em> must be modified to call the method <code>printData</code> instead of having the two <code>System.out.println</code> statements. We do it like this:</p>

<pre><code>public class LessonExecution3 {

    public static void main(String[] args) {
        User user = new User();
        user.name = "Rui";
        user.age = 35;

        user.printData();  // &lt;------------
    }

}
</code></pre>

<p>On this new version, the <code>System.out.println</code> statements were removed, and replaced by the <code>user.printData()</code> statement, which has inside some other <code>System.out.println</code> statements. We call the method by using the variable of the object we want to access, and using the <strong>dot</strong> notation specify the method we want to execute. In this particular case, because <code>printData</code> receives no arguments, we place the <code>( )</code> with nothing inside the brackets.</p>

<h3 id="settermethods">Setter Methods</h3>

<p>But we can improve this code a lot still. When we declare the <code>user</code> variable and instantiate it, we then access the variables inside that object to assign values to them. <strong>This is actually a bad practice.</strong></p>

<blockquote>
  <p>Instead of accessing the variables directly, we should be using methods to both set values of these variables and to get the values of these variables. </p>
</blockquote>

<p>We'll now implement a method to set the variable <strong>name</strong>. We call methods that specifically set values for variables <strong>Setter Methods</strong>, and a modified version of the User class with a setter method for the <strong>name</strong> variable can be seen next:</p>

<pre><code>public class User {

    String name;
    int age;

    public void printData() {
        System.out.println( "User Name: " + name );
        System.out.println( "User Age: " + age );
    }

    /*
    Setter method for the name variable
    */
    public void setName(String newname) {
        name = newname ;
    }

}
</code></pre>

<p>There is now a method with the signature like <code>public void setName(String newname)</code>, which means:</p>

<ul>
<li>the method receives only one argument, which we call <code>newname</code></li>
<li>the method return nothing : <code>void</code></li>
</ul>

<p>Then, inside the method, we set the Class Variable <code>name</code> with the value of the received variable <code>newname</code> , like this :  <code>name = newname ;</code>  . Simple yes?</p>

<p>But having this Setter method does not stop programmers from accessing the variable <em>name</em> directly and modifying it! It is just another way to modify the Class variable. </p>

<p>There is a way to make it impossible for a user to access the variable directly, which the use of <strong>Access Modifiers</strong>, and we'll see about it on the next <a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/">Tutorial</a>.</p>

<p>Now lets modify the <code>main</code> method inside <em>LessonExecution3</em> to use the setter method for <code>name</code> instead of accessing it directly:</p>

<pre><code>public static void main(String[] args) {
    User user = new User();
    user.setName( "Rui" );   //   &lt;-------- Using setter method for name
    user.age = 35;    //  &lt;-------- Accessing age variable directly

    user.printData();
}
</code></pre>

<p>Because the <code>setName</code> method requires a String parameter as input, the method is called with the value to be assigned to that parameter inside the <strong><code>()</code></strong> brackets, like this:  <code>(  "value" )</code> .   </p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<p>If, for example, the required parameter was a number, of type <strong>int</strong> , then calling the method and providing a String as argument would make the program not compile. </p>

<p>Now, do exactly the same thing to the variable <code>age</code> . Create a setter method and modify the <code>main</code> method to call the setter method for <em>age</em> instead of accessing it directly.</p>

<p>The resulting <strong>User</strong> class should look something like this :</p>

<pre><code>public class User {

    String name;
    int age;

    public void printData() {
        System.out.println( "User Name: " + name );
        System.out.println( "User Age: " + age );
    }

    /*
      Setter method for the name variable
    */
    public void setName(String newname) {
        name = newname ;
    }

    /*
      Setter method for the age variable
    */
    public void setAge(int newage) {
        age = newage ;
    }

}
</code></pre>

<p>Notice that we have started putting comments before the methods, explaining what they will be doing. </p>

<p>And then the <code>main</code> method should look like this:</p>

<pre><code>public static void main(String[] args) {
    User user = new User();
    user.setName( "Rui" );
    user.setAge( 35 );

    user.printData();
}
</code></pre>

<p>Now that we already made 3 methods, including two that are setter methods, it makes sense to create also the getter methods for those variables!</p>

<h3 id="gettermethods">Getter Methods</h3>

<p>Getter methods are just what their name say, they are methods to get values of specific variables. </p>

<p>For example, from looking to our class <em>User</em> to get the values of both <em>name</em> and <em>age</em> variable a programmer would need to access them directly. This is not desired, <strong>accessing variables from other classes directly is a bad practice</strong>, and therefore we need a way to access the values of those variables.</p>

<blockquote>
  <p>Accessing variables from other classes directly is a bad practice</p>
</blockquote>

<p>To create a getter method for the variable <code>name</code>, we need to write a method whose signature should look like this: <code>public String getName()</code> , which means:</p>

<ul>
<li>the method returns one String :  <code>String</code></li>
<li>the method does not require any parameters ; <code>( )</code></li>
</ul>

<p>Now the question is, how does one make a method return a value? Simple, we use the <strong>return keyword</strong> :</p>

<pre><code>/*
  Getter method for the Name variable
*/
public String getName() {
    return name;
}
</code></pre>

<p>So, if somewhere on our code, from outside of the <strong>User</strong> class, we would like to get the value of <code>name</code> of a particular object, we can now instead use this getter method. Lets exemplify using our <code>main</code> method inside of <em>LessonExecution3</em> :</p>

<pre><code>public static void main(String[] args) {
    User user = new User();
    user.setName( "Rui" );
    user.setAge( 35 );

    user.printData();

    // ---- Testing the getter method ----
    String valueFromObject = user.getName();
    System.out.println("Testing getter method : "  + valueFromObject );
}
</code></pre>

<p>Modify your classes accordingly, compile and give it a run. The output should look something like :</p>

<pre><code>User Name: Rui
User Age: 35
Testing getter method : Rui
</code></pre>

<p>Now, as an exercise implement a getter method for the <code>age</code> variable, that returns an <em>int</em> and test the getter method on the <code>main</code> method, like we did before. </p>

<p>The resulting <strong>User</strong> class should look like this:</p>

<pre><code>public class User {

    String name;
    int age;

    public void printData() {
        System.out.println( "User Name: " + name );
        System.out.println( "User Age: " + age );
    }

    /*
      Setter method for the name variable
    */
    public void setName(String newname) {
        name = newname ;
    }

    /*
     Getter method for the name variable
    */
    public String getName() {
        return name;
    }

    /*
      Setter method for the age variable
    */
    public void setAge(int newage) {
        age = newage ;
    }

    /*
    Getter method for the age variable
    */
    public int getAge() {
        return age;
    }

}
</code></pre>

<p>And the resulting <strong>LessonExecution3</strong> class should look like this:</p>

<pre><code>public class LessonExecution3 {

    public static void main(String[] args) {
        User user = new User();
        user.setName( "Rui" );
        user.setAge( 35 );

        user.printData();

        String valueFromObject = user.getName();
        System.out.println("Testing getter name method : "  + valueFromObject );

        int ageFromObject = user.getAge();
        System.out.println("Testing getter age method : "  + ageFromObject );

    }

}
</code></pre>

<p>But we can still make it better! </p>

<p>If we look at the previous code, to create a <strong>User</strong> object with complete information (with name and age) we must do it in 3 different statements! </p>

<p>If we accept that a <em>User</em> must always have a <code>name</code> and <code>age</code> , then this code will not do it, because we are not forcing these to be defined at creation, which means that if someone creates a <em>User</em> object and then forgets to call the setters for <code>name</code> and <code>age</code>, the <em>User</em> object would not have these variables defined.</p>

<p>For this, there is a special kind of method, which is called a <strong>Constructor</strong> that can only be called at the creation of the object.</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="constructor">Constructor</h3>

<p>A Constructor is a method that does not return anything, and has the exact same name as the Class and is called during instantiation of the new Object.</p>

<blockquote>
  <p>Each class must have at least one Constructor, but if none is provided, one is created automatically, called the default constructor, which takes 0 parameters and does absolutely nothing. </p>
</blockquote>

<p>In the previous version of the code, the <strong>User</strong> class has no constructor, which mean that one is created automatically (behind the scenes), which is equivalent to this :</p>

<pre><code>public class User {

    /*
     The Default Constructor
    */
    public User() {

    }

    String name;
    int age;

    [ ETC ETC ETC ] 
}
</code></pre>

<p>And when in the <em>main</em> method we were doing:</p>

<pre><code>User user = new User();
</code></pre>

<p>the <code>new User()</code> is actually saying : <em>create a new object of type User, using the "no arguments" Constructor.</em></p>

<p>As you can see, the constructor : </p>

<pre><code>public User() {

}
</code></pre>

<ul>
<li>Has no return type defined, because it is a constructor</li>
<li>Has the same name as the Class</li>
</ul>

<p>A class can have multiple Constructors, as long as they have different signatures, which in this particular case means that each different Constructor must have  different types of parameters that they take as input (or the number of parameters vary). For example, having these constructors all on the same class would be acceptable:</p>

<ul>
<li><code>public User()</code></li>
<li><code>public User(String newname)</code> </li>
<li><code>public User(String newname, int age)</code> </li>
<li><code>public User(int age, String newname)</code> </li>
</ul>

<p>Having a class with all these constructors would be illegal:</p>

<ul>
<li><code>public User()</code></li>
<li><code>public User(String firstname)</code></li>
<li><code>public User(String surname)</code></li>
</ul>

<p>Because the last two Constructors are identical.</p>

<blockquote>
  <p>So, recapping, if no Constructor is defined, then one is automatically created, that takes no arguments, and does absolutely nothing.  And if one Constructor is specified, then the automatic "no arguments" constructor is not created. </p>
</blockquote>

<p>Getting back to our code, because we decided that there would make no sense to have <strong>User</strong> objects without <code>name</code> and <code>age</code>, we'll create a Constructor that must receive both these parameters, and we delete the "no arguments" Constructor if there is one:</p>

<pre><code>public class User {

    String name;
    int age;

    public User(String newname, int newage) {
        name = newname;
        age = newage;
    }

    [ETC ETC ETC]

}
</code></pre>

<p>At this point we have a <strong>User</strong> class that has only one constructor, and that constructor must take 2 arguments, the <code>newname</code> String and the <code>newage</code> int.</p>

<p>If you tried to compile now you would get an error like this :</p>

<pre><code>LessonExecution3.java:4: error: constructor User in class User cannot be applied to given types;
        User user = new User();
                    ^
  required: String,int
  found: no arguments
  reason: actual and formal argument lists differ in length
  1 error
</code></pre>

<p>This happens because we are creating the <strong>user</strong> object using a constructor that does not exist! <strong>Remember, before we had no Constructor defined, and because of that one automatic one was created. Now there is one, and because there is only one, we must use that constructor!</strong></p>

<p>We must now modify the <code>main</code> method to make use of that constructor:</p>

<pre><code>public static void main(String[] args) {
    User user = new User("Rui" , 35);
    user.setName( "Rui" );
    user.setAge( 35 );

    user.printData();

    String valueFromObject = user.getName();
    System.out.println("Testing getter name method : "  + valueFromObject );

    int ageFromObject = user.getAge();
    System.out.println("Testing getter age method : "  + ageFromObject );

}
</code></pre>

<p>Notice that now we are creating the object using <code>new User("Rui" , 35);</code> , which tells us that we are using the Constructor that takes one String and one int, in that particular order.</p>

<p>Afterwards we have :</p>

<pre><code>user.setName( "Rui" );
user.setAge( 35 );
</code></pre>

<p>This is unnecessary, because the values are already being set in the Constructor. Lets remove that, and we end up with :</p>

<pre><code>public static void main(String[] args) {
    User user = new User("Rui" , 35);

    user.printData();

    String valueFromObject = user.getName();
    System.out.println("Testing getter name method : "  + valueFromObject );

    int ageFromObject = user.getAge();
    System.out.println("Testing getter age method : "  + ageFromObject );

}
</code></pre>

<p>Compile everything now and run it, to verify that the values are being set correctly:</p>

<pre><code>User Name: Rui
User Age: 35
Testing getter name method : Rui
Testing getter age method : 35
</code></pre>

<h4 id="exercise">Exercise</h4>

<p>As an exercise, create another constructor on the <strong>User</strong> class, that takes an <code>int</code> and a <code>String</code>, is this new order and create another object of type <em>User</em> in a variable called <code>user2</code> , using the new Constructor, and call the <code>printData</code> method on that object!</p>

<p>The code for the <strong>User</strong> class should end up looking like this:</p>

<pre><code>public class User {

    String name;
    int age;

    public User(String newname, int newage) {
        name = newname;
        age = newage;
    }

    public User(int newage, String newname) {
        name = newname;
        age = newage;
    }

    public void printData() {
        System.out.println( "User Name: " + name );
        System.out.println( "User Age: " + age );
    }

    [ETC ETC ETC]

}
</code></pre>

<p>And the code for the <strong>LessonExecution3</strong> should look something like this:</p>

<pre><code>public class LessonExecution3 {

    public static void main(String[] args) {
        User user = new User("Rui" , 35);

        user.printData();

        User user2 = new User(99, "Old Man");

        user2.printData();

        String valueFromObject = user.getName();
        System.out.println("Testing getter name method : "  + valueFromObject );

        int ageFromObject = user.getAge();
        System.out.println("Testing getter age method : "  + ageFromObject );

    }

}
</code></pre>

<p>At this point you should know how to implement methods and constructors , create new classes , and create instances of those classes (creating new Objects of the class type). All of this speaks to the absolute basic mechanics of Object-Oriented programming.  </p>

<p>There are a few more considerations to know about methods, that you might have figured out already, but we'll put it in writing.</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="whatelseaboutmethods">What else about Methods?</h3>

<p>A method can have both input and output at the same time. Look at this valid method, which is totally unrelated to the code we have been producing:</p>

<pre><code>public int sumTwoNumbers(int number1 , int number2) {
    return number1 + number2 ;
}
</code></pre>

<p>This method is completely acceptable, and valid. It receives two <strong>ints</strong> and returns the sum of those <strong>ints</strong> .</p>

<p>Variables that are declared inside the method cannot be accessed outside of that method:</p>

<pre><code>public void  testFunction ( ) {
    int specialNumber;   // &lt;--- Declared
    specialNumber = 20 ;  // &lt;--- Assigned

    specialNumber = specialNumber + 10 ; 

    System.out.println("Value now is : "  + specialNumber); // &lt;-- will print 30

    // HERE 
}
</code></pre>

<p>In the previous example, each time the method <code>testFunction</code> is executed, a variable is created called <code>specialNumber</code>, and just before the method finishes, this variable stops existing.  <strong>Remember, those variables only exist inside the method!</strong></p>

<p>Now, if the declaration is outside of the method, in the Class: </p>

<pre><code>int specialNumber;   // &lt;--- Declared

public void  testFunction ( ) {

    specialNumber = 20 ; 
    specialNumber = specialNumber + 10 ; 

    System.out.println("Value now is : "  + specialNumber); // &lt;-- will print 30

}
</code></pre>

<p>in this case, the variable <code>specialNumber</code> will exist for each object , and can be accessed from any method on that Class. </p>

<p>And that is it for this tutorial! In the next tutorial we will look into Packages and Access Modifiers, like the keyword <code>public</code> that we have been using. </p>

<p><strong>Lets go, next Tutorial:</strong> <a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/">Tutorial 5 - Packages and Access Modifiers</a></p>

<script>  
function gotonow(anch) {  
    var curtop = 0;
    var obj = document.getElementById(anch);
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        window.scroll(0, [curtop]);
    }
    return false;
}
</script>]]></content:encoded></item><item><title><![CDATA[Java Tutorial 3 - Variables - First Look]]></title><description><![CDATA[In this tutorial we will look into storing data and doing something with that data. We'll talk about variables, primitives and Objects.]]></description><link>http://blog.jbaysolutions.com/2016/03/29/tutorial-3-variables-first-look-at-primitive-variables-and-operators/</link><guid isPermaLink="false">daa63fb6-fbbf-4bce-920c-dcbb79b79baa</guid><category><![CDATA[java]]></category><category><![CDATA[Learning Java from scratch]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Tue, 29 Mar 2016 14:52:49 GMT</pubDate><content:encoded><![CDATA[<ol>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-3-variables-first-look-at-primitive-variables-and-operators/" onclick="gotonow('introduction');return false;">Introduction</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-3-variables-first-look-at-primitive-variables-and-operators/" onclick="gotonow('myfirstvariable');return false;">My First Variable</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-3-variables-first-look-at-primitive-variables-and-operators/" onclick="gotonow('primitivevariables');return false;">Primitive Variables</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-3-variables-first-look-at-primitive-variables-and-operators/" onclick="gotonow('someoperatoractionandstrings');return false;">Some operator action and Strings</a></li>
</ol>

<h3 id="introduction">Introduction</h3>

<p>On the previous tutorial we made a really simple program, with just one <em>Class</em> and one <em>Method</em>. There was no data stored, no calculations done, etc. </p>

<p>In this tutorial we will look into storing data and doing something with that data. We'll talk about variables, primitives and Objects, and we'll make a really simple calculator to add 2 numbers! Yes, exciting! </p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="myfirstvariable">My first Variable</h3>

<p>First, we open our favorite text editor and create a new class called <em>Lesson2</em> with an empty <code>main</code> method. If you have been following the tutorials, try and do it by yourself, or just simply copy the following code onto the editor and save the file as <em>Lesson2.java</em> (<em>remember, java is Case Sensitive</em>).</p>

<pre><code>public class Lesson2 {
    public static void main(String[] args) {

    }
}
</code></pre>

<p>You can now compile it and run it. It should give you no errors and print absolutely nothing. </p>

<p>Make the main method now print the "Hello World" phrase, like it was done on the <a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-2-hello-world/">previous tutorial</a>, and we should end up with something like this:</p>

<pre><code>public class Lesson2 {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}
</code></pre>

<p>Compile and run it again. It should be printing "Hello World"! Remember, every time you modify the Source Code you must compile the code again, and only then will you be able to run it with the new changes.</p>

<p>Lets modify this code now to have a variable and have that code print the value of the variable:</p>

<pre><code>public class Lesson2 {

    public static void main(String[] args) {
        int firstVariable = 5;
        System.out.println("Value is: " + firstVariable);
    }

}
</code></pre>

<p>The first change you notice is the <code>int firstVariable = 5;</code> . This is a variable named <em>firstVariable</em> , it is of type <strong>int</strong> (integer) and has a value of <strong>5</strong>. </p>

<blockquote>
  <p>This is how you declare a variable in Java: You explicitly define the Type of the variable and give it a name. Optionally you can also define a value, like we did there, but this is not mandatory.</p>
</blockquote>

<p>The second change is the print that we are now doing: <code>System.out.println("Value is: " + firstVariable);</code> . The program will now print "<em>Value is:</em> " and concatenate the value of the <em>firstValue</em> using the operator <strong>+</strong>. </p>

<p>Compile and run it. It should have printed : <em>Value is: 5</em></p>

<p>So, the first variable, which is named <code>firstVariable</code> is of type <strong>int</strong> (which stands for integer), but what is an <strong>int</strong> and what other types are there?</p>

<h3 id="primitivevariables">Primitive Variables</h3>

<p><strong>int</strong> is what is called a Primitive type and there are 7 other primitive types. Here is a complete list, with a very simple description of what they are:</p>

<ul>
<li><strong>short</strong> : a type of whole number, that can go from -32768 to 32767.  (<em>it is 16bit signed</em>)</li>
<li><strong>int</strong> : a type of whole number, that can go from -2^31 to (2^31)-1.  (<em>it is 32bit signed</em>)</li>
<li><strong>long</strong> : a type of whole number, that can go from -2^63 to (2^63)-1.  (<em>it is 64bit signed</em>)</li>
<li><strong>float</strong> : a type of floating point number, therefore can have decimals (<em>it is 32bit single precision</em>)</li>
<li><strong>double</strong> : a type of floating point number, therefore can have decimals (<em>it is 64bit double precision</em>)</li>
<li><strong>boolean</strong> : a type that only allows 2 values : <em>true</em> or <em>false</em>.</li>
<li><strong>char</strong> : a single character (<em>16 bit</em>)</li>
<li><strong>byte</strong> : a type of whole number, that can go from -128 to 127.  (<em>it is 8bit signed</em>)</li>
</ul>

<p>Before you get too nervous about all this jibber jabber, lets start by saying that only about 3 or 4 of these are used really regularly and these are :  <strong>int</strong>, <strong>long</strong>, <strong>double</strong> and <strong>boolean</strong> . That is not to mean that you don't need to know about the other ones, you do, and you will use some of them, but for learning purposes we'll focus on these 4 for now. </p>

<p><em>What is a Primitive Variable?</em>  There are two types of Variables, those that are of a Primitive type (therefore of one of these 8 types) or those that are Reference Variable. We'll see Reference Variables later, lets write some code first!</p>

<p>Lets modify the <em>Lesson2</em> class and create variables for these types:</p>

<pre><code>public static void main(String[] args) {
    short shortVariable = 1;
    System.out.println("shortVariable is: " + shortVariable);

    int intVariable = 2;
    System.out.println("intVariable is: " + intVariable);

    long longVariable = 3;
    System.out.println("longVariable is: " + longVariable);

    float floatVariable = 4.1f;
    System.out.println("floatVariable is: " + floatVariable);

    double doubleVariable = 5.1;
    System.out.println("doubleVariable is: " + doubleVariable);

    boolean booleanVariable = true;
    System.out.println("booleanVariable is: " + booleanVariable);

    char charVariable = 'x';
    System.out.println("charVariable is: " + charVariable);    

    byte byteVariable = 8;    
    System.out.println("byteVariable is: " + byteVariable);    
}
</code></pre>

<p>Now compile and run it. You should be getting an output like:</p>

<pre><code>shortVariable is: 1
intVariable is: 2
longVariable is: 3
floatVariable is: 4.1
doubleVariable is: 5.1
booleanVariable is: true
charVariable is: x
byteVariable is: 8
</code></pre>

<p>Notice the notation used to define these variables: </p>

<ul>
<li><code>float floatVariable = 4.1f ;</code></li>
</ul>

<p>We placed an "<strong>f</strong>" after the number. When you define a value of a <strong>float</strong> typed variable, you must write the letter <strong>"f"</strong> after the number, to let the compiler know (when you decide to compile the code) that you understand that you are using a small floating-point type, and therefore know that you will not have a lot of precision on that number. </p>

<ul>
<li><code>boolean booleanVariable = true ;</code></li>
</ul>

<p>When defining a value for a <strong>boolean</strong> typed variable, there are only 2 choices: <em>true</em> or <em>false</em> . </p>

<ul>
<li><code>char charVariable = 'x' ;</code></li>
</ul>

<p>When defining a value for a <strong>char</strong> typed variable, the character must be enclosed inside <strong>'</strong> and only one character.  Char is a bit special, it is 16 bits, exactly the same as the <strong>short</strong> type... and are interchangeable. We'll get a chance to see it later.</p>

<p>Now that we have a basic knowledge of the primitive variable types, lets do some operations on those. </p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="someoperatoractionandstrings">Some Operator Action and Strings!</h3>

<p>Now that we know how to define and assign values to primitive variables, lets modify the code again, and have only two variables of type <em>int</em> defined inside the <code>main</code> method. We'll call them <code>number1</code> and <code>number2</code> and will assign them the values <strong>50</strong> and <strong>2</strong>.  Try doing it yourself!</p>

<p>It should end up looking like this:</p>

<pre><code>public static void main(String[] args) {

    // Variable of type int called number1 and number2
    int number1 = 50;
    int number2 = 2;

}
</code></pre>

<p>If you compile and run it now, it should produce no output. Also, notice that now we have a comment on the source code, before the definition of the variables. This is one of the two ways of writing comments, by placing <strong><code>//</code></strong> everything thing written to the right of this will be considered a comment and ignored by the compiler. </p>

<p>Lets now create another variable, named <code>sumOfNumbers</code>, which will contain the sum of <code>number1</code> and <code>number2</code>, and lets print the result to the console:</p>

<pre><code>public static void main(String[] args) {

    // Variables of type int called number1 and number2
    int number1 = 50;
    int number2 = 2;

    int sumOfNumbers = number1 + number2;

    System.out.println( sumOfNumbers );

}
</code></pre>

<p>Compile it and give it a run. It should have printed the result : <em>52</em></p>

<p>There are many other <strong>operators</strong>, like <strong><code>-</code></strong> for subtraction, <strong><code>/</code></strong> for division, <strong><code>*</code></strong> for multiplication, <strong><code>%</code></strong> for modulus. There are also <strong>Compound Operators</strong> and <strong>Equality Operator</strong>, which we'll see very soon.</p>

<p>Experiment with those operators to see what happens, create a few more variables with the result of these operators applied to variables <code>number1</code> and <code>number2</code>  and print those values out. Check the following code:</p>

<pre><code>public static void main(String[] args) {

    // Variables of type int called number1 and number2
    int number1 = 50;
    int number2 = 2;

    int sumOfNumbers = number1 + number2;
    System.out.println( "Sum: " + sumOfNumbers );

    int subtractionOfNumbers = number1 - number2;
    System.out.println( "Subtraction: " + subtractionOfNumbers );

    int divisionOfNumbers = number1 / number2;
    System.out.println( "Division: " +divisionOfNumbers );

    /*
        For the Multiplication, we'll do something different
    */

    int multiplicationOfNumbers;
    multiplicationOfNumbers = number1 * number2;
    System.out.println( "Multiplication: " + multiplicationOfNumbers );

}
</code></pre>

<p>Compile and run!</p>

<p>In this piece of code we can see a few new things:</p>

<ul>
<li><p>We have a new type of comment : <strong><code>/* comment */</code></strong> . This type of comment can span several lines, it begins with <strong><code>/*</code></strong> and ends with <strong><code>*/</code></strong> . Everything in between those is ignored by the compiler</p></li>
<li><p>We create an <em>int</em> typed variable called <code>multiplicationOfNumbers</code> but we do not assign any value to it. Then, on the next statement, we assign the value with the result of the multiplication of <code>number1</code> and <code>number2</code>. </p></li>
<li><p>We modified every "print" statement, to now print a String (like <code>"Multiplication: "</code>) with the value of specific variables.  </p></li>
</ul>

<p>Notice that we have been using the <strong><code>+</code></strong> operator since the beginning of the tutorials to concatenate a String ( something inside <strong><code>"</code></strong> ) and values of primitive variables. Keep in mind that the <strong>Add</strong> operator, when applied to primitives calculates the addition of the values of the two variables. When applied to one or more Strings, it performs concatenation. </p>

<p>On the next Tutorial we'll talk about Constructors and Methods.</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<p><strong>When you feel ready:</strong> <a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-4-classes-constructors-and-methods/">Tutorial 4 - Classes, Constructors and Methods</a></p>

<script>  
function gotonow(anch) {  
    var curtop = 0;
    var obj = document.getElementById(anch);
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        window.scroll(0, [curtop]);
    }
    return false;
}
</script>]]></content:encoded></item><item><title><![CDATA[Java Tutorial 2 - Hello World]]></title><description><![CDATA[To start this great journey, we'll use the tipical "Hello World" program. Before we start running we must learn how to walk.]]></description><link>http://blog.jbaysolutions.com/2016/03/29/tutorial-2-hello-world/</link><guid isPermaLink="false">c65cb175-34b5-4ac0-9dce-fab9f732cbe2</guid><category><![CDATA[java]]></category><category><![CDATA[Learning Java from scratch]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Tue, 29 Mar 2016 14:51:55 GMT</pubDate><content:encoded><![CDATA[<ol>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-2-hello-world/" onclick="gotonow('introduction');return false;">Introduction</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-2-hello-world/" onclick="gotonow('helloworld');return false;">Hello World</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-2-hello-world/" onclick="gotonow('javaandjavac');return false;">Java and Javac</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-2-hello-world/" onclick="gotonow('lookingatthecode');return false;">Looking at the Code</a> <br>
<ol><li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-2-hello-world/" onclick="gotonow('aclass');return false;">A Class</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-2-hello-world/" onclick="gotonow('amethod');return false;">A Method</a></li></ol></li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-2-hello-world/" onclick="gotonow('exercises');return false;">Exercises</a></li>
</ol>

<h3 id="introduction">Introduction</h3>

<p>To start this great journey, we'll use the typical "Hello World" program. Yes, it is not very exciting, not very motivational, but before we start running we must learn how to walk. </p>

<p>At this point you should have the JDK installed, and a text editor available. If you have no idea what a JDK is, then you should go and check the previous tutorial: <a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-1-introduction-the-absolute-basics/">Tutorial 1 - Introduction  (The Absolute Basics) </a></p>

<p>Open your favorite (or available) text editor and lets start!</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h3 id="helloworld">Hello World</h3>

<p>Just for this example, we'll use a normal text editor instead of IntelliJ. This is just to show you how you compile java code. In the next tutorials we'll start making use of <a href="http://www.jetbrains.com/idea/">IntelliJ Community Edition</a>, which makes it a lot simpler to compile and run your projects. <strong>But don't skip this bit, you should really know how to compile and run your code by hand!</strong></p>

<p>Grab the text editor, start a new file and copy this bit of code into it:</p>

<pre><code>public class Lesson1{
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}
</code></pre>

<p>After you copied this, create an empty folder, which we will be using for this particular tutorial, and save the file with the name <strong>Lesson1.java</strong>.  Java is a case sensitive language, so copy the code exactly the wait it was presented before and save the file with that precise name. We'll get more into that, don't worry.</p>

<p>There should now be a Folder on your system, with just one file named <strong>Lesson1.java</strong> .</p>

<blockquote>
  <p>Remember: Java is a case sensitive language</p>
</blockquote>

<p>Open a command prompt if you are in windows (type cmd.exe in the "Run" option on the Windows Start Button) , or a Shell if you are in a Unix based system and go to that Folder. </p>

<h3 id="javaandjavac">JAVA and JAVAC</h3>

<p>To compile the Lesson1 program we are making, which simply prints "Hello World", we must first compile it! <em>To compile we use the Java Compiler (JAVAC)</em>.</p>

<p>On the command prompt or shell, inside the folder where the <em>Lesson1.java</em> file exists, type in:</p>

<pre><code>javac
</code></pre>

<p>If a sea of text just flashed by, then the JDK is correctly installed and you can proceed to the next step. If on the other hand there was an error message like : <strong><em>javac: command not found</em></strong> , then the JDK is not correctly installed and you should check the previous tutorial before proceeding. </p>

<p>On the command prompt or shell, type in:</p>

<pre><code>javac Lesson1.java
</code></pre>

<p>If everything went right, you should now have exactly 2 files inside that folder:</p>

<ul>
<li><strong>Lesson1.java</strong>  -  The source code</li>
<li><strong>Lesson1.class</strong>  -  The Compiled Java Bytecode</li>
</ul>

<p>Now in that same command prompt or shell, type in:</p>

<pre><code>java Lesson1
</code></pre>

<p>It should print out "Hello World"! Congratulations, this is your first program in Java! It doesn't do much, but it is a start! Lets look at the source code and understand what it all means.</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr></p>

<h2 id="lookingatthecode">Looking at the Code</h2>

<p>As it was said in the previous tutorial, Java is a Object Oriented (OO) language, and that means that our program is structured in Objects that may or may not have data inside, and may or may not have code inside. </p>

<h4 id="aclass">A Class</h4>

<p>When a programmer writes a file like this:</p>

<pre><code>public class Lesson1{

} 
</code></pre>

<p>The programmer is in fact creating a <strong>Class</strong> , which you can think of as a Template for Objects, with the name <strong>Lesson1</strong>. </p>

<p>Because our "Hello World" program is really small, it only has one Class, but if it was more complex it could have many many many more Classes. </p>

<p>From that code <code>public class Lesson1</code> , we know that we are creating a <strong>Class</strong> named <strong>Lesson1</strong>, and that <strong>Class</strong> is <strong>Public</strong>. We'll forget about the <em>Public</em> bit for now, but we'll get back to it once we look at Access Modifiers in the <a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-5-packages-and-access-modifyiers/">Tutorial 5 - Packages and Access Modifiers</a>  . </p>

<h4 id="amethod">A Method</h4>

<p>Then, inside the <em>Lesson1</em> class (which is the bit between <code>{</code> and <code>}</code>, we have:</p>

<pre><code>public static void main(String[] args) {

}
</code></pre>

<p>This is a Method, and it is called <em>"main"</em>. We'll break it down:</p>

<ul>
<li><code>public</code> : like in the class, it will be talked about in the next tutorial</li>
<li><code>static</code> : we'll also forget about this for the moment, we'll get back to it in a few tutorials</li>
<li><code>void</code> : this means that the method does not return anything. </li>
<li><code>main</code> : the name of the method we are creating</li>
<li><code>(String[] args)</code> : the arguments the method receives, in this case it is an <em>Array of Strings</em>, called <em>args</em>. </li>
</ul>

<p>This part of the method <code>public static void main(String[] args)</code> is called the Signature of the method. Obviously all methods will have a signature, where: </p>

<ul>
<li>the name of the method is specified, </li>
<li>the arguments it receives are specified, </li>
<li>what it returns is specified</li>
</ul>

<p>This method, named <em>"main"</em>, with a signature as described before, is a very important method! It is the method that the JVM (Java Virtual Machine) will grab and execute, and therefore this is where a program starts its execution.</p>

<p>Notice that the class named <strong>Lesson1</strong> starts with a capital letter. Now notice that the <code>main</code> method start with a lowercase letter.  This was not something random that just happened to be this way, it was on purpose. Although there is no technical reason why this is so, it is a convention, and every Java programmer knows this and will do it this way. <strong>We will adhere to it :</strong></p>

<blockquote>
  <p>Names of classes start with Capital letters</p>
  
  <p>Names of methods start with Lower case letters</p>
  
  <p>Names of variables start with Lower case letters (except for some exceptions well see later)</p>
</blockquote>

<p>Inside the method we find:</p>

<pre><code>System.out.println("Hello World");
</code></pre>

<p>In simple terms it is a <strong>Statement</strong> that prints a line with "Hello World" to the console (or command prompt, or shell) . </p>

<p>In sightly more complex term (which you don't need to completely understand now, and will be explained later on) we are calling a method called <code>println</code> that exists inside a variable called <code>out</code> , that exists inside a <code>System</code> object. We know this because of the <strong>naming conventions</strong>, and it will all make a lot more sense really soon.</p>

<p>So, what do we know up to this point?</p>

<ul>
<li>A Class is a template for Objects</li>
<li>A <strong>Class name</strong> always <strong>starts with a Capital Level</strong></li>
<li>A Method has a signature that defines the input and output</li>
<li>A <strong>Method</strong> is named with a <strong>starting lowercase letter</strong></li>
<li>A Class is compiled using the Java Compiler <strong>javac</strong></li>
<li>A Compiled program is run using the Java Virtual Machine: <strong>java</strong></li>
</ul>

<p>Next we'll talk about variables and just a little bit more OO theory. We are about to start the good stuff!</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr>  </p>

<h2 id="exercises">Exercises</h2>

<p>To get a bit more practice, consider doing the following exercise:</p>

<ol>
<li>Create a class named <em>Exercise1</em> that prints "My First Exercise" when it is executed. </li>
</ol>

<p><strong>Next tutorial:</strong> <a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-3-variables-first-look-at-primitive-variables-and-operators/">Tutorial 3 - Variables</a></p>

<script>  
function gotonow(anch) {  
    var curtop = 0;
    var obj = document.getElementById(anch);
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        window.scroll(0, [curtop]);
    }
    return false;
}
</script>]]></content:encoded></item><item><title><![CDATA[Java Tutorial 1 - Introduction - The absolute basics]]></title><description><![CDATA[Java is not a difficult language to learn, even if you are a beginner. There are a few concept that we must get out of the way in order to get started.]]></description><link>http://blog.jbaysolutions.com/2016/03/29/tutorial-1-introduction-the-absolute-basics/</link><guid isPermaLink="false">838b9491-fdf4-4a30-b81a-909a361d9b5b</guid><category><![CDATA[java]]></category><category><![CDATA[Learning Java from scratch]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Tue, 29 Mar 2016 14:50:52 GMT</pubDate><content:encoded><![CDATA[<ol>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-1-introduction-the-absolute-basics/" onclick="gotonow('introduction');return false;">Introduction</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-1-introduction-the-absolute-basics/" onclick="gotonow('objectorientedprogrammingoolanguage');return false;">Object-Oriented Programming (OO) Language</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-1-introduction-the-absolute-basics/" onclick="gotonow('platform');return false;">Platform</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-1-introduction-the-absolute-basics/" onclick="gotonow('developmentkit');return false;">Development Kit</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-1-introduction-the-absolute-basics/" onclick="gotonow('ide');return false;">IDEs</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-1-introduction-the-absolute-basics/" onclick="gotonow('nextsteps');return false;">Next Steps</a></li>
</ol>

<h2 id="introduction">Introduction</h2>

<p>Java is not a difficult language to learn, even if you are a complete beginner. There are a few concept however that we must get out of the way in order to get started. </p>

<p>In this tutorial we will cover the absolute basics of Java and programming in general, so if you already know what Java is, what a development kit is, you have a JDK installed and ready to run, then go ahead and Skip to the next tutorial. </p>

<p><strong>What is Java?</strong></p>

<p>Java is two things: it is both an <em>Object-Oriented Programming language</em> and a <em>Platform</em>. </p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr>  </p>

<h2 id="objectorientedprogrammingoolanguage">Object-Oriented Programming (OO) Language .</h2>

<p>When writing code, or programming, a programmer writes that code using a specific syntax and grammar that he and other programmers understand called the Programming Language. In the particular case of Java, it is an Object-Oriented programming language, which means that it is based around the notion of Objects that may have data inside and also may contain code instructions (like methods). </p>

<p>Object-Oriented programming is one of several programming paradigms, but there are others, like Functional Programming (like Lisp and Haskell) , Logic Programming (like Prolog), etc.  It is simply a set of concepts and rules on how to structure an idea or problem.</p>

<p>So, when we say that Java is an Object Oriented Programming Language, we are just expressing the way that code is structured, and what is the expected behavior of that code. This will be covered more indepth in the next tutorials of this series, while writing some code and getting some hands-on experience. </p>

<p>But Java is also a Platform,</p>

<h2 id="platform">Platform</h2>

<p>When someone makes a program in Java, for it to be executable it needs to be compiled. Compiling code is basically translating  the human readable source code, which is the writing the programmer does, into a "format" that the computer can make sense of. This is called compiling to Native code, and it has the following particularities:</p>

<ul>
<li>Code compiled natively is usually faster, at least at startup</li>
<li>Code compiled natively is architecture and OS specific (must be compiled independently for each OS : windows, Linux, etc)</li>
<li>Code compiled natively do require an interpreter.</li>
</ul>

<p><img src="http://blog.jbaysolutions.com/content/images/2016/03/Compilation_native.png" alt=""></p>

<p>Java in particular (and some other languages as well) is an interpreted programming language, which means that the Java Source code is compiled into intermediate "format", and then for it is run, the computer must have an interpreter. In Java this is called Compiling to Java bytecode, and has the following particularities:</p>

<ul>
<li>Java Bytecode requires an interpreter to be installed ( Java must be installed on the running machine)</li>
<li>Java Bytecode is not architecture or OS specific. It can run in any arch. or Os that has an interpreter</li>
</ul>

<p><img src="http://blog.jbaysolutions.com/content/images/2016/03/Compilation_java.png" alt=""></p>

<p>So, when we talk about Java there is this distinction, it is a programming language, but also a Platform (or runtime environment).</p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr>  </p>

<h2 id="developmentkit">Development Kit</h2>

<p>To start programming in Java, the first thing that a programmer needs is the Java Development Kit (also known as JDK) and to run a program made in Java, a user needs the Java Runtime Environment (also known as JRE). </p>

<p>The JDK has the compiler, and all utilities needed to transform Java Source Code into Java Bytecode, and also brings a JRE inside so the developer can run the application he is coding. As a developer you'll only need to install the JDK on your computer.</p>

<p>The JRE has the interpreter, that is called the Java Virtual Machine (or JVM for short). We'll talk more about the particularities of the JVM as we move along.</p>

<p>So, to get the JDK you can go to the <a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html">Oracle JDK 8 Download Page</a> . We are looking for the Java SE Development Kit 8u73 . Download the version for your platform and follow all the steps to install it. </p>

<p>Once the JDK is installer, you'll need an editor to write the Source Code for the projects you'll be programming.</p>

<h2 id="ide">IDE</h2>

<p>Any text editor will do, you can code Java using the Windows Notepad, or linux Vi if you want. But sometimes it is helpful to have an editor that can verify straight away the syntax you are using to program, and warn you of any errors you might have made. It is also useful to have a text editor that writes some boilerplate code that you don't want to be writing all the time, and that allows for the code to be compiled automatically from inside the editor, to save time and for convenience. These are called Integrated Development Environments, or IDEs for short. </p>

<p>There are many many IDEs for Java, like NetBeans, Eclipse, etc etc etc. </p>

<p>For the first tutorials there is no need for a fancy IDE.  We could use a simple text editor and everything would be fine.  </p>

<p>Some recommended text editors are :</p>

<ul>
<li><a href="https://www.textpad.com/">Textpad for Windows</a></li>
<li><a href="https://www.sublimetext.com">Sublime Text for Win, Linux and Mac</a></li>
<li><a href="http://www.geany.org/">Geany for Linux</a></li>
</ul>

<p>But don't get lost in the choice of text editor. It really makes no difference, you can do it with Notepad.</p>

<p>After the first beginner tutorials, the IDE that will be used is <a href="https://www.jetbrains.com/idea/">IntelliJ Community Edition</a> . Any other can be used, but the examples will be made using IntelliJ. There is a Community Edition of IntelliJ that is free, and that is the one that will be used on the tutorials. </p>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>  
<!-- Horizontal For Posts - Text Only -->  
<ins class="adsbygoogle" style="display:inline-block;width:728px;height:90px" data-ad-client="ca-pub-1311169549359552" data-ad-slot="3316155422"></ins>
<script>  
(adsbygoogle = window.adsbygoogle || []).push({});
</script>  

<p><br><hr>  </p>

<h3 id="nextsteps">Next Steps</h3>

<p>Before the next tutorial you should:</p>

<ul>
<li>install the specified JDK.</li>
<li>install a text editor , an IDE (or decide to use notepad or something for now)</li>
</ul>

<p><strong>Once you are ready, next tutorial:</strong>  <a href="http://blog.jbaysolutions.com/2016/03/29/tutorial-2-hello-world/">Tutorial 2 - Hello World</a></p>

<script>  
function gotonow(anch) {  
    var curtop = 0;
    var obj = document.getElementById(anch);
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        window.scroll(0, [curtop]);
    }
    return false;
}
</script>]]></content:encoded></item></channel></rss>