<?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[java - 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:03 GMT</lastBuildDate><atom:link href="http://blog.jbaysolutions.com/tag/java/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[How to Implement a Mechanism like QR code scanning of WhatsApp Web]]></title><description><![CDATA[<p>This tutorial came to be due to a question I found on Stackoverflow titled <a href="http://stackoverflow.com/questions/37350286/mechanism-behind-qr-code-scanning-of-whatsapp-webapp/39275035">Mechanism behind QR code scanning of whatsapp webapp</a> and the <a href="http://stackoverflow.com/questions/37350286/mechanism-behind-qr-code-scanning-of-whatsapp-webapp/39275035#39275035">investigation and answer that I gave</a> .</p>

<p>Because the answer was given in real broad strokes, I decided to create a tutorial on how to implement something</p>]]></description><link>http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/</link><guid isPermaLink="false">107afd9c-5490-47b6-8fb7-8c01d1f0d69c</guid><category><![CDATA[play2]]></category><category><![CDATA[android]]></category><category><![CDATA[java]]></category><category><![CDATA[javascript]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Tue, 20 Sep 2016 09:10:42 GMT</pubDate><content:encoded><![CDATA[<p>This tutorial came to be due to a question I found on Stackoverflow titled <a href="http://stackoverflow.com/questions/37350286/mechanism-behind-qr-code-scanning-of-whatsapp-webapp/39275035">Mechanism behind QR code scanning of whatsapp webapp</a> and the <a href="http://stackoverflow.com/questions/37350286/mechanism-behind-qr-code-scanning-of-whatsapp-webapp/39275035#39275035">investigation and answer that I gave</a> .</p>

<p>Because the answer was given in real broad strokes, I decided to create a tutorial on how to implement something like what is being used by WhatsApp. This tutorial will cover the theory behind it, the implementation of an Android App to read QR codes and send and receive data to a Server, and also an implementation of the Server side using Play2 Framework. Another implementation using Glassfish 4 and Tyrus will follow at some point if there is interest. </p>

<p>It is assumed some degree of knowledge on Android development for the Android sections, some knowledge of Play2 Framework  for the Play2 Framework server side implementation, and obviously Java. I'll try to cover all the basics and specifics, but it will be quite hard to explain everything is 100% detail. </p>

<ol>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('tostart');return false;">To Start</a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('whatistheplan');return false;"><strong>What is the plan?</strong></a>  </li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('serverandwebimplementation');return false;"><strong>Server and Web Implementation</strong></a> <br>
<ul><li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('generatingqrcodes');return false;">Generating QR Codes</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('websocketstheserverside');return false;">WebSockets - The Server Side</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('websocketsandinterfacestuffthewebside');return false;">WebSockets and Interface stuff - The Web Side</a>
<ul><li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('interfacestuff');return false;">Interface Stuff</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('websocketsjavascriptstuff');return false;">WebSockets Javascript Stuff</a></li></ul></li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('sendandreceivingmessagesserverside');return false;">Send and Receiving Messages - Server Side</a></li></ul></li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('androidclientimplementation');return false;"><strong>Android Client Implementation</strong></a> <br>
<ul><li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('interfacebit');return false;">Interface Bit</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('firebasecloudmessagingintroanddependencies');return false;">Firebase Cloud Messaging Intro and Dependencies</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('firebaseandroidimplementation');return false;">Firebase Android implementation</a>
<ul><li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('updatingfirebasetoken');return false;">Updating Firebase Token</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('handlingarrivingmessages');return false;">Handling arriving messages</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('broadcastreceivertoreceivemessages');return false;">BroadcastReceiver to Receive Messages</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('chatmessagelistandadapter');return false;">Chat Message List and Adapter</a></li></ul></li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('qrcodescanning');return false;">QR Code Scanning</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('communicationwithserver');return false;">Communication with Server</a></li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('configurationsthatyouneedtochange');return false;">Configurations that you need to Change</a></li></ul></li>
<li><a href="http://blog.jbaysolutions.com/2016/09/20/how-to-implement-a-mechanism-like-qr-code-scanning-of-whatsapp-web/" onclick="gotonow('references');return false;"><strong>REFERENCES</strong></a></li>
</ol>

<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="tostart">To Start</h2>

<p>So, first of all, all source code is available at these two locations:</p>

<ul>
<li><a href="https://github.com/jbaysolutions/whatsapp-clone-play-server">WhatsApp Auth Clone using Play2 - Server</a></li>
<li><a href="https://github.com/jbaysolutions/whatsapp-clone-android-client">WhatsApp Auth Clone Android App </a></li>
</ul>

<p>One is the Web server side bit, which will display a QR Code and allow the auth and also do some chatting, and the other is the Android app that will read QR Codes and also work as a chat client. </p>

<p>These are not particularly pretty, they are a proof of concept and just work. Contributions, forks, etc, are welcome.</p>

<h2 id="whatistheplan">What is the plan?</h2>

<p>For our small proof of concept, just like with WhatsApp, the chat bit of the Web App will work using WebSockets.  When a user opens the URL for the Web App thing ( using <a href="http://localhost:9000/">http://localhost:9000/</a> ) the Web page gets a few Javascripts (we are also using JQuery here, just to simplify some of the work we need to be done, and bootstrap so that everything doesn't just look too horrible), some CSSs and then it opens a WebSocket, where it receives immediatly a UUID for it to use to download the QR Code image.  </p>

<p>The WebSocket on the browser is listenning for several things, one of which is that UUID for the QR Code retrieval.  When the UUID code for the QR Code arrives, the javascript updates the Web Page with that image URL and displays it. </p>

<p><strong>The browser at this point:</strong></p>

<ul>
<li>has a WebSocket open </li>
<li>has a  QR Code displayed on the screen</li>
</ul>

<p><strong>The server at this point:</strong></p>

<ul>
<li>Has a WebSocket open with that browser</li>
<li>It knows that the WebSocket is associated with a particular QR Code.</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>On the Android side of things, the Android App will do most of the communications (<em>like authentication ... which is basically lacking, for simplicity sake, and sending messages to the server</em>) using normal GET requests to the Play2 Application . To receive messages, we will be using <a href="https://firebase.google.com/">Firebase Cloud Messaging</a>, because it saves us time in implementation, because we won't need to keep sockets and whatnot open with the server, and monitor them for disconnects and other problems, and because it is just the best way for this Proof of Concept.  </p>

<p>So, unlike the WhatsApp Android App , we require the user to set his username  (<em>we make no checks to see if one already exist, or anything like that... feel free to implement this if you like</em>) and sign in. This just stores the Username on the App so that everytime we send a message using the App, it sends the username of the person who wrote that message.  This is not at all secure, because it would be easy to impersonate another person, but then again, this is just a Proof of Concept. </p>

<p>Once the User selected a Username on the Android App, the can start chatting away, or can at any moment do the QR Code scanning.  Doing the QR Code scanning, the Android App gets the UUID that is embedded on the QR Code and sends a message to the server saying : OK , this UUID that I just scanned, belongs to this Username.  The server receives the message, checks the list of QR Code UUIDs that it has, and then uses the WebSocket associated with it to notify the browser of the username it should use, and refresh the interface with the chat windoe and hide the QR Code bit. </p>

<p>At this point both the Android and Web App use GET requests to send messages to the server, and receive new messages either through the WebSocket (in the case of the Web Client)   or through Firebase Cloud Messaging (in case of the Android Client). </p>

<p>In both, when a message is received, the interface is updated to show that message and who wrote it. </p>

<p>This is it. </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="serverandwebimplementation">Server and Web Implementation</h2>

<p>For the Web/Server implementation we use Play Framework 2.5.6 "Steamy", you can get it at <a href="https://www.playframework.com/download">the official Play Framework site</a> , or just get the complete source code of the WhatsApp Clone Play Project <a href="https://github.com/jbaysolutions/whatsapp-clone-play-server">Here</a> .</p>

<p>Lets break it down in smaller bits</p>

<h3 id="generatingqrcodes">Generating QR Codes</h3>

<p>To generate QR codes we'll use ZXing lib from google version 3.2.1 , which you can get here <a href="https://mvnrepository.com/artifact/com.google.zxing/core/3.2.1">https://mvnrepository.com/artifact/com.google.zxing/core/3.2.1</a> .  All code made here was base on this <a href="https://www.numetriclabz.com/android-qr-code-scanner-using-zxingscanner-library-tutorial/">Tutorial</a> with some modifications to serve our purpose.</p>

<p>First we add the ZXing dependency to the Play project, by editing the build.sbt file and adding the following line, to the end of it:</p>

<pre><code>libraryDependencies += "com.google.zxing" % "core" % "3.2.1"
</code></pre>

<p>We created a class called <code>QRCodeUtil</code> in the package <code>com.jbaysolutions.whatsappclone.util</code> with a single method called <code>generateQRCode</code> that generates a QR Code BufferedImage for a given UUID:</p>

<pre><code>public static BufferedImage generateQRCode(UUID uuid) {

    int size = 250;
    try {

        Map&lt;EncodeHintType, Object&gt; hintMap = new EnumMap&lt;EncodeHintType, Object&gt;(EncodeHintType.class);
        hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        BitMatrix byteMatrix = qrCodeWriter.encode(
                uuid.toString(),
                BarcodeFormat.QR_CODE,
                size,
                size,
                hintMap
        );

        int CrunchifyWidth = byteMatrix.getWidth();
        BufferedImage image = new BufferedImage(CrunchifyWidth, CrunchifyWidth,
                BufferedImage.TYPE_INT_RGB);
        image.createGraphics();

        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth);
        graphics.setColor(Color.BLACK);

        for (int i = 0; i &lt; CrunchifyWidth; i++) {
            for (int j = 0; j &lt; CrunchifyWidth; j++) {
                if (byteMatrix.get(i, j)) {
                    graphics.fillRect(i, j, 1, 1);
                }
            }
        }

        logger.debug("You have successfully created QR Code.");

        return image;

    } catch (WriterException e) {
        logger.error("Problem generating QR Code" , e);
        return null;
    }
}
</code></pre>

<p>On the <code>HomeController</code> we have a method for returning that QR Code to the browser, for a given UUID String:</p>

<pre><code>public Result getQRCode(String inputUUID) throws IOException {

    UUID uuid = UUID.fromString(inputUUID);

    BufferedImage image = QRCodeUtil.generateQRCode(uuid);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "png", baos);
    byte[] bytes = baos.toByteArray();

    ByteArrayInputStream stream = new ByteArrayInputStream(bytes);

    return ok(stream)
            .as("image/png");

}
</code></pre>

<p>On the Routes file the Play Project we have the following route for this particular method on the Controller:</p>

<pre><code>GET        /uuid/:uuid                   controllers.HomeController.getQRCode(uuid: String)
</code></pre>

<p>That is it. To test it out, just go to a browser on the same machine where you ahve the Play application running and go, for example, to the following URL:  <a href="http://localhost:9000/uuid/0e2161d7-25e7-4846-84c8-faaa87a81313">http://localhost:9000/uuid/0e2161d7-25e7-4846-84c8-faaa87a81313</a> .  A QR Code should be displayed on the browser.  Try it out with any other valid UUID aswell. </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="wherewillthisbeused">Where will this be used?</h4>

<p>This QR Code generation code will be used when we implement the WebSocket bit, and on the Browser side, the listenner receives a UUID.  When the WebSocket listener receives a specific command with a UUID, it will update the interface with the UUID QR Code image. We'll see more about that in a minute. </p>

<h3 id="websocketstheserverside">WebSockets - The Server Side</h3>

<p>A good place to start if the <a href="https://www.playframework.com/documentation/2.5.x/JavaWebSockets">Play Framework documentation on WebSockets</a> , which... is confusing, but still, it give you examples of stuff working.  On the next version of Play, a new sort of implementation for WebSockets oin Java is available, and that is why you'll see a lot of uses of the class <code>LegacyWebSocket</code>, which is the old implementation, that will still be made available in the next releases of Play. We'll use that.</p>

<p>On the <code>HomeController</code> we have the following method:</p>

<pre><code>public LegacyWebSocket&lt;String&gt; socket() {

    return new LegacyWebSocket&lt;String&gt;() {
        @Override
        public void onReady(WebSocket.In&lt;String&gt; in, WebSocket.Out&lt;String&gt; out) {

            in.onMessage(new Consumer&lt;String&gt;() {
                @Override
                public void accept(String s) {
                    // Never Used
                }
            });

            in.onClose(new Runnable() {
                @Override
                public void run() {
                    logger.info("WebSocket Disconnected");
                }
            });

            // Now we do some of or logic 
            // 1- We generate a UUID that we'll associate with this WebSocket 
            String uuid = UUID.randomUUID().toString();

            // 2- Now we store the UUID that we just created, in some fashion
            // to associate it with the IN and OUT streams of the Web Socket
            WebSessionsHandler.getInstance().createNewQRSession(
                    uuid,
                    in,out
            );

            // 3- We send the UUID to the browser, through the WebSocket 
            // we just opened with the browser 
            out.write("wsready###" + uuid);

        }
    };

}
</code></pre>

<p>Real simple, instead of returning a Result, like we always (<em>almost always</em>) do in the Controllers, we now return a WebSocket ( ok ok , <code>LegacyWebSocket</code> ) to the Browser.  In our implementation of the WebSocket we simply create the Socket and make it so that when it is closed, we log that :</p>

<pre><code>in.onClose(new Runnable() {
    @Override
    public void run() {
        logger.info("WebSocket Disconnected");
    }
});
</code></pre>

<p>When we receive a message on the Server, through the WebSocket, we do nothing. The reason is : we will not be send messages from the browser to the Server through the WebSocket. For no particular reason, just because we'll use the same method we use for the Android App :</p>

<pre><code>in.onMessage(new Consumer&lt;String&gt;() {
    @Override
    public void accept(String s) {
        // Never Used
    }
});
</code></pre>

<p>Then we do some logic that is associated with our WhatsApp Clone thing. First we generate an UUID to associate with the WebSocket on the server side, and later to generate the QR Code on the Browser:</p>

<pre><code>String uuid = UUID.randomUUID().toString();
</code></pre>

<p>We then store the IN and OUT "streams" of the WebSocket in association with the UUID :</p>

<pre><code>WebSessionsHandler.getInstance().createNewQRSession(
        uuid,
        in,out
);
</code></pre>

<p>Our implementation of <code>WebSessionsHandler</code> isn't particularly nice, but it does the job. We store the In and OUT associated with an UUID, which is just what wew need at this stage.</p>

<p>Then, we use the OUT stream to send the UUID to the browser. We are sending a String that starts with "<strong>wsready###</strong>" followed by the UUID. This just makes it easier to identify the type of message, and to split the string on the Client side and extract the UUID later:</p>

<pre><code>out.write("wsready###" + uuid);
</code></pre>

<p>That is it for the WebSocket code on the Server side. We just need to add a route to the Routes file and give it a test run. The route should look like this:</p>

<pre><code>GET        /ws                           controllers.HomeController.socket()
</code></pre>

<p>To test it out, use the following link : <a href="http://www.websocket.org/echo.html">http://www.websocket.org/echo.html</a>  and use <code>ws://localhost:9000/ws</code>  as the test URL.  Connect and see the test benchmark receive an UUID!</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="websocketsandinterfacestuffthewebside">WebSockets and Interface stuff - The Web Side</h3>

<h4 id="interfacestuff">Interface Stuff</h4>

<p>First things first, on the <code>main.scala.html</code> template, on the <code>Head</code> of the HTML we import JQuery and Bootstrap:</p>

<pre><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"&gt;&lt;/script&gt;

&lt;!-- Latest compiled and minified CSS --&gt;
&lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"&gt;

&lt;!-- Optional theme --&gt;
&lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"&gt;
</code></pre>

<p>And inside the body, but right at the end:</p>

<pre><code>&lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"&gt;&lt;/script&gt;
</code></pre>

<p>But that is not all, we also import a Javascript that we will write called whatsappclone.js` :</p>

<pre><code>&lt;script src="@routes.Assets.versioned("javascripts/whatsappclone.js")" type="text/javascript"&gt;&lt;/script&gt;
</code></pre>

<p>On this script we will write all of the logic we will describe next. </p>

<p>Also, on the <code>index.scala.html</code> template file we write it like this:</p>

<pre><code>@(title: String)

@main(title) {

    &lt;div class="page-header"&gt;
      &lt;h1&gt;WhatsApp Web App Clone Tutorial&lt;/h1&gt;
    &lt;/div&gt;


    &lt;div class="container" id="chatarea" style="display: none"&gt;
        &lt;div class="row"&gt;
            &lt;div class="col-md-12"&gt;
                &lt;div class="list-group" id="product-filter-data"&gt;
                    &lt;div id="chatlist" style="height: 300px; max-height: 300px; overflow-y: scroll"&gt;

                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class="row"&gt;
            &lt;div class="col-md-12"&gt;
                &lt;div class="input-group"&gt;
                    &lt;input id="messageInput" type="text" class="form-control" placeholder="Say something..."&gt;
                    &lt;span class="input-group-btn"&gt;
                        &lt;button class="btn btn-default" type="button" onclick="sendMessage();"&gt;Send&lt;/button&gt;
                    &lt;/span&gt;
                &lt;/div&gt;&lt;!-- /input-group --&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;


    &lt;div id="qrcodearea"&gt;
        &lt;img id="qrcode" src=""&gt;
    &lt;/div&gt;

}
</code></pre>

<p><strong>The important bits to pay attention are :</strong></p>

<ul>
<li><p>There is a DIV with id <code>qrcodearea</code> with an <code>img</code> inside. This is where the QR Code will be displayed</p></li>
<li><p>There is a DIV with if <code>chatarea</code> . This is the Chat bit.  It has a List , where the messages will be displayed, and also an input with id <code>messageInput</code> which is where the user will write messages he wants to send. </p>

<p>Notice that the <code>chatarea</code> div is not being displayed. This is the default startup mode we want: not showing chat area until the user is authenticated with the QR Code. </p></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>

<h4 id="websocketsjavascriptstuff">WebSockets Javascript Stuff</h4>

<p>On the <code>main.scala.html</code> file we are importing a javascript called <code>whatsappclone.js</code>, just like we said on the previous section. This is the javascript that contains all the logic. When the javascript is loaded and the document is ready we do a couple of things:</p>

<ul>
<li>We find the divs that we want to hide and show and assign them to some variables, just for confort.</li>
<li>We initialize the WebSocket</li>
<li>We also add a Listener on the <code>messageInput</code> field, for the <code>return</code> key, and call send message when the return key is pressed while on the input field.</li>
</ul>

<p>This is the code for that:</p>

<pre><code>$(document).ready(function(){
    console.log("Starting WhatsApp Clone");
    qrcodeareaDiv = $("#qrcodearea");
    chatareaDiv = $("#chatarea");
    chatareaDiv.css('display','none')
    chatList = $("#chatlist");
    initWebSocket();

    $("#messageInput").on('keypress', function (e) {
        if (e.which === 13) {
            sendMessage();
        }
    });

})
</code></pre>

<p>The <code>initWebSocket</code> method, that is called on the <code>document</code> ready methods does the following:</p>

<pre><code>function initWebSocket() {

    websocket = new WebSocket("ws://localhost:9000/ws");

    websocket.onopen = function(evt) {
        console.log("WebSocket Opened");
    };

    websocket.onclose = function(evt) {
        console.log("WebSocket Closed");
        websocket = null;
        username = null;
    };

    websocket.onmessage = function(evt) {

        var rawdata = evt.data;

        if (rawdata.startsWith("wsready###")) {

            var qrUuid = rawdata.split("###")[1];
            console.log("UUID for qr received: " + qrUuid);
            $("#qrcode").attr("src", "http://localhost:9000/uuid/" + qrUuid);

        } else if (rawdata.startsWith("authed###")) {

            username = rawdata.split("###")[1];
            console.log("Auth done using mobile for user: " + username);
            qrcodeareaDiv.hide();
            chatareaDiv.css('display','block');

        } else if (rawdata.startsWith("msg###")) {

            var user = rawdata.split("###")[1];
            var msg = rawdata.split("###")[2];
            console.log("message from : " + user + " with data: " + msg + " \n");

            if ( username === user ) {
                // FROM ME
                chatList.append("&lt;div class=\"list-group-item list-group-item-success\"&gt;I said:"+msg+"&lt;/div&gt;");
            } else {
                // FROM OTHER PEOPLE
                chatList.append("&lt;div class=\"list-group-item list-group-item-warning\" style=\"text-align: right\"&gt;"+user+" said:"+msg+"&lt;/div&gt;");
            }

        } else {
            console.error("Unknown Stuff: " + rawdata) ;
        }

    };


    websocket.onerror = function(evt) { 
        console.error("Error: " + evt) ;
    };

}
</code></pre>

<p>So, we open a WebSocket to the url <code>ws://localhost:9000/ws</code> , which is where we are making the socket available:</p>

<pre><code>websocket = new WebSocket("ws://localhost:9000/ws");
</code></pre>

<p>Then we say that when the WebSocket is opened, we log some stuff to the javascript console, just for debugging purposes:</p>

<pre><code>websocket.onopen = function(evt) {
    console.log("WebSocket Opened");
};
</code></pre>

<p>When the WebSocket is closed, we also print some debugging to the javascript console and we set the WebSocket to null and also a variable called <code>username</code>:</p>

<pre><code>websocket.onclose = function(evt) {
    console.log("WebSocket Closed");
    websocket = null;
    username = null;
};
</code></pre>

<p>If there is an error with the WebSocket we also print some debugging to the javascript console:</p>

<pre><code>websocket.onerror = function(evt) { 
    console.error("Error: " + evt) ;
};
</code></pre>

<p>Now for the interesting bit, when a message is received on the WebSocket we do a few things:</p>

<p>First we get the message that was sent from the server into a variable:</p>

<pre><code>var rawdata = evt.data;    
</code></pre>

<p>Then, we try to understand what type of message was sent, and we do that by checking how to message starts. Remember that in the previous section, when a WebSocket was open, the server would send straight away a message with the UUID of the QR code to be displayed. That message starts with <code>wsready</code> followed by <code>###</code> and the the UUID. So : </p>

<pre><code>if (rawdata.startsWith("wsready###")) {

    var qrUuid = rawdata.split("###")[1];
    console.log("UUID for qr received: " + qrUuid);
    $("#qrcode").attr("src", "http://localhost:9000/uuid/" + qrUuid);

} 
</code></pre>

<p>What this code does is : when the WebSocket on the browser side receives a message that starts with <code>wsready###</code> , it first splits the message at the <code>###</code> marker and stores the UUID that comes after the <code>###</code>:</p>

<pre><code>var qrUuid = rawdata.split("###")[1];
</code></pre>

<p>We then log that UUID to the javascript console, just so we can see what is going on, and then, we update an <code>&lt;img&gt;</code> element with id <code>qrcode</code> that exists on the <code>index.scala.html</code> with an url for the QR Code image:</p>

<pre><code>$("#qrcode").attr("src", "http://localhost:9000/uuid/" + qrUuid);
</code></pre>

<p>Remember, the url <code>http://localhost:9000/uuid/</code> was explained in the previous sections, where we show how we generate a QR Code image and how we make it return on a specific route.</p>

<p>The browser and server, if a message starting with <code>wsready###</code> arrives, have a WebSocket open between each other, that specific WebSocket can be identified by an UUID, and the browser is now displaying a QR Code of that UUID. </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>But that is not all that happens when a message is received on the WebSocket. We are also expecting two other types of messages, which we haven't talked about yeat, but I'll introduce now:</p>

<ul>
<li><p><code>authed###</code> : A message starting with <code>authed###</code> is sent to the WebSocket by the server, once a Mobile user authenticates using the QR Code. This message has the <code>username</code>of the user that just authenticated with the Mobile Device, and is used to signal the browser to get ready with the Chat window. so :</p>

<p><strong>1-</strong> Store Username:</p>

<pre><code>username = rawdata.split("###")[1];
</code></pre>

<p><strong>2-</strong> Hide QR Code bit of the interface, which is not needed anymore, because a user already authenticated with that QR Code:</p>

<pre><code>qrcodeareaDiv.hide();
</code></pre>

<p><strong>3-</strong> Display the Chat section of the interface : </p>

<pre><code>chatareaDiv.css('display','block');
</code></pre></li>
<li><p><code>msg###</code>: A message starting with <code>msg###</code> is sent to the WebSocket by the server when some user sends a chat message to the server, be it from a Web Client or a Mobile Client. This message is a two part message with this format :    <code>msg###USERNAME###MESSAGE</code> . The first thing we do is split the rawmessage on the <code>###</code> marks, and extract the username of the person sending the message, and the message itself:</p>

<pre><code>var user = rawdata.split("###")[1];
var msg = rawdata.split("###")[2];
</code></pre></li>
</ul>

<p>We then update the Chat interface in one of two ways, depending if the user that sent the message was the same user that is authenticated on the Web Client, or if it was another user:</p>

<pre><code>if ( username === user ) {
    // FROM ME
    chatList.append("&lt;div class=\"list-group-item list-group-item-success\"&gt;I said:"+msg+"&lt;/div&gt;");
} else {
    // FROM OTHER PEOPLE
    chatList.append("&lt;div class=\"list-group-item list-group-item-warning\" style=\"text-align: right\"&gt;"+user+" said:"+msg+"&lt;/div&gt;");
}
</code></pre>

<p>That is it for the WebSocket. </p>

<p>There is also another method, that we have introduced before, when talking about the  <code>ready</code> method of the document, with regards to the return key of the  <code>messageInput</code>text field. That is the <code>sendMessage</code> function, which looks like this:</p>

<pre><code>function sendMessage() {
    var message = $("#messageInput").val();

    $.ajax({
        'url': '/session/msg',
        'type': 'GET',
        'data': {
            'user': username,
            'message': message
        },
        'success': function (data) {
            //clear input field value
            $("#messageInput").val("");
        },
        'error' : function (data) {
            alert(data);
        }
    });
}
</code></pre>

<p>So, when the Web Client user wants to send a message, he writes it down on the <code>messageInput</code> field, and when he is done, he presses the return key. This method is called, which uses JQuery to send an ajax request to the server, where it send the username of the user sending the message, and the message the user wrote.  </p>

<p>Notice that we do no update the Chat sections of the interface. We leave that to the WebSocket. We just send the message to the server, if the server receives it and everything is fine, the server will send the message to every Web Client, through the WebSockets that are open, and the interfaces get refreshed when that message arrives. </p>

<p>This is it for the Web Client side of things. </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="sendandreceivingmessagesserverside">Send and Receiving Messages - Server Side</h3>

<p>The way we went about this is, everytime a client wants to send a message to the Chat, the client must make a GET request to the server with the its Username and Message. The Client shouldn't make any updates to the Chat interface on sending the message. The server receives the message and then goes to all Web Session that are authenticated and to all Mobile Sessions and sends that same message to the clients, using the WebSockets, or the Firebase cloud Messaging, depending on the type of Client. Only then, when the Client receives the message from the server, will it update the Chat interface. </p>

<p>On the Server side, we have the following method on the <code>HomeController</code> :</p>

<pre><code>public Result broadcastMessage(String user, String message) {

    // Send for all WebSessions
    for ( WebSession session : WebSessionsHandler.getInstance().getAllAuthSessions()) {
        try {
            session.getOut().write(
                    "msg###"+user+"###"+message
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Send for all Mobile Sessions
    for (MobileSession session : MobileSessionsHandler.getInstance().getAllSessions()) {
        FirebaseUtil.sendPushMessage(session.getFirebaseToken(), user + " : " +message);
    }

    return ok();

}
</code></pre>

<p>What it does is, first iterate all the WebSessions it has, that are authenticated, and send a message through their WebSocket in the format previously describe while writing the Javascript bit of the WebSocket. </p>

<p>Then it iterates all the MobileSessions and using Firebase Cloud Messaging, send a message to each of the Mobile Devices. For doing this we are using the <a href="https://github.com/Raudius/Pushraven">Pushraven lib</a> , in the following way (<code>FirebaseUtil</code> class) : </p>

<pre><code> public synchronized static void sendPushMessage(String client_key, String message) {
    raven
            .text(message)
            .to(client_key);
    raven.push();

    raven.clear();
    raven.clearAttributes();
    raven.clearTargets();
}
</code></pre>

<p>Please check the <a href="https://github.com/Raudius/Pushraven">official web page for Pushraven</a> for more information on what is going on here. </p>

<p>And this is basically it. Now on to the Android 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="androidclientimplementation">Android Client Implementation</h2>

<p>For the Android implementation we have a really simple ìnterface for login in, make the QR Code Scan and do some chatting. It uses <a href="https://developer.android.com/training/volley/index.html">Volley</a> for communications with the Chat Server, which we just explained in the previous section, and also uses <a href="https://firebase.google.com/docs/cloud-messaging/">Firebase Cloud Messaging</a> for receiving new messages from the Server. </p>

<p>It also works a bit different than the WhatsApp app, in that we don't use the phonenumber as the ID for the user, but instead we prompt the user for a Username. We do no validation, nor authentication, because that is not the point of this tutorial. </p>

<p>Lets start!</p>

<h3 id="interfacebit">Interface Bit</h3>

<p>For our Android client we just use an Activity with just one interface. That interface is divided in two main sections, one for the Login in, and another for the Chat. The section for the chat also has the QR Code bit. Our <code>activity_main.xml</code> layout looks like this:</p>

<pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:orientation="vertical"
    android:id="@+id/mainLayout"&gt;

    &lt;LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:id="@+id/signinLayout"&gt;

        &lt;EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/usernameET"
            android:hint="@string/username_et_hint" /&gt;

        &lt;Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/signin_button"
            android:id="@+id/signinButton"
            android:onClick="signIn" /&gt;

    &lt;/LinearLayout&gt;

    &lt;LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/qrScannerLayout"
        android:visibility="gone"&gt;&lt;/LinearLayout&gt;

    &lt;LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/chatLayout"
        android:visibility="gone"&gt;

        &lt;RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"&gt;

            &lt;Button android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:text="@string/qr_code_button"
            android:onClick="performQrScanner"
                android:id="@+id/scanQrButton"
                android:layout_alignParentTop="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true" /&gt;

            &lt;ListView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/chatLListView"
                android:layout_gravity="center_horizontal"
                android:layout_below="@+id/scanQrButton"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_above="@+id/linearLayout" /&gt;

            &lt;RelativeLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:id="@+id/linearLayout"&gt;

                &lt;EditText
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/messageET"
                    android:layout_toLeftOf="@+id/sendButton"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentStart="true" /&gt;

                &lt;Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/send_button"
                    android:id="@+id/sendButton"
                    android:onClick="sendMessage"
                    android:layout_alignParentTop="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignParentEnd="true" /&gt;
            &lt;/RelativeLayout&gt;
        &lt;/RelativeLayout&gt;

    &lt;/LinearLayout&gt;

&lt;/LinearLayout&gt;
</code></pre>

<p>We have the <code>signinLayout</code> LinearLayout, which is the section where the user specifies the Username he wants to use:</p>

<pre><code>&lt;LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:id="@+id/signinLayout"&gt;

    &lt;EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/usernameET"
        android:hint="@string/username_et_hint" /&gt;

    &lt;Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/signin_button"
        android:id="@+id/signinButton"
        android:onClick="signIn" /&gt;

&lt;/LinearLayout&gt;
</code></pre>

<p>We have and empty LinearLayout called <code>qrScannerLayout</code> which is where we'll display the Camera bit , when we perform QR Code Scanning. It is empty by default but will be filled when the user selects the QR Code Scanning button:</p>

<pre><code>&lt;LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/qrScannerLayout"
    android:visibility="gone"&gt;&lt;/LinearLayout&gt;
</code></pre>

<p>And then, we have the Chat section bit, which is again another LinearLayout called <code>chatLayout</code> that contains: </p>

<ul>
<li>Button for QR Code Scanning </li>
<li>ListView for the Chat Messages</li>
<li>EditText for writting Messages to send</li>
</ul>

<p>One thing to take notice is that the <code>chatLayout</code> has the <code>visibility</code> property as <code>gone</code>, which is the default, because we don't want to show this interface until the user defines its Username. This section looks like this:</p>

<pre><code>&lt;LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/chatLayout"
    android:visibility="gone"&gt;

    &lt;RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"&gt;

        &lt;Button android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="@string/qr_code_button"
        android:onClick="performQrScanner"
            android:id="@+id/scanQrButton"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" /&gt;

        &lt;ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/chatLListView"
            android:layout_gravity="center_horizontal"
            android:layout_below="@+id/scanQrButton"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_above="@+id/linearLayout" /&gt;

        &lt;RelativeLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:id="@+id/linearLayout"&gt;

            &lt;EditText
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/messageET"
                android:layout_toLeftOf="@+id/sendButton"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true" /&gt;

            &lt;Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/send_button"
                android:id="@+id/sendButton"
                android:onClick="sendMessage"
                android:layout_alignParentTop="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true" /&gt;
        &lt;/RelativeLayout&gt;
    &lt;/RelativeLayout&gt;
&lt;/LinearLayout&gt;
</code></pre>

<p>On the Activity side it is very simple. For the login bit, the user writes down the Username on the <code>EditText</code>field and presses the  Login Button, which does nothing except locking the Username <code>EditText</code> field and Login Button, and show the Chat session of the interface, like so:</p>

<pre><code>public void signIn(View view) {
    if (usernameET.getText().toString().isEmpty()) {
        Toast.makeText(this, "Must have username defined", Toast.LENGTH_SHORT).show();
        return ;
    }

    // If a username is defined, then lock interface and update
    usernameET.setEnabled(false);
    signInButton.setEnabled(false);
    chatLayout.setVisibility(View.VISIBLE);
}
</code></pre>

<p>But lets now talk about Firebase Cloud Messaging.</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="firebasecloudmessagingintroanddependencies">Firebase Cloud Messaging Intro and Dependencies</h3>

<p>For sending the messages of the Chat from the Server to the Android Clients, we use Firebase Cloud Messaging. Give a read at the <a href="https://firebase.google.com">Official Site</a> for more information regarding Firebase, but for the purpose of this tutorial you just need to know that it allows sending push messages to Android devices (to and from, and other devices, and browsers and stuff), and that is what we will use it for.  We'll use Firebase to send push messages from the Chat server to the Android devices. </p>

<p>So, to start using Firebase, you need to go to the <a href="https://console.firebase.google.com">Firebase console</a> at  <a href="https://console.firebase.google.com">https://console.firebase.google.com</a> and register the app you are creating. For this tutorial, the package to use during registration is : <code>com.jbaysolutions.tutorial.whatsappclone</code> . </p>

<p>Once the app is registered on the Firebase Console, you must download the <code>google-services.json</code> file that is provided and replace it on the App. This is very important, or else it just won't work. </p>

<p>If you are making an app from scratch, then you need to :</p>

<ul>
<li><p>Add dependency of <code>com.google.gms:google-services</code> on the <code>build.gradle</code> file on the root of the project ( the one that has the <code>gradle</code> build tools dependency) :</p>

<pre><code>dependencies {
    classpath 'com.android.tools.build:gradle:1.3.0'


   // NOTE: Do not place your application dependencies here; they belong
   // in the individual module build.gradle files


   classpath 'com.google.gms:google-services:3.0.0'


}
</code></pre></li>
<li><p>Add dependencies of <code>firebase</code> to the <code>build.gradle</code> file that exists at the base of the module: </p>

<pre><code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
     compile 'com.android.support:appcompat-v7:24.0.0'
     compile 'me.dm7.barcodescanner:zxing:1.8.4'
     compile 'com.google.firebase:firebase-core:9.4.0'
     compile 'com.google.firebase:firebase-messaging:9.4.0'
     compile 'com.android.volley:volley:1.0.0'
}
</code></pre></li>
<li><p>Add the <code>apply plugin</code>  to the end of the of the <code>build.gradle</code> file at the base of the module:</p>

<pre><code>apply plugin: 'com.google.gms.google-services'
</code></pre></li>
<li><p>Save the <code>google-services.json</code> you just downloaded from the Firebase Console for this app right next to the <code>build.gradle</code> file at the base of the module. </p></li>
</ul>

<p>This is it. You are now ready to use the Firebase Cloud Messaging. </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="firebaseandroidimplementation">Firebase Android implementation</h3>

<p>Most of the code used on the WhatsApp Clone Android App is base on this <a href="https://www.simplifiedcoding.net/firebase-cloud-messaging-tutorial-android/">Tutorial</a>  so give it a quick read if you want. </p>

<p>So, when we start the WhatsApp Clone App and the first thing we need to do is send a registration of the Device to the server, with the Firebase token of the device, so that the Server can now contact the Device back at any time. We also need to notify the Server everytime the Firebase token changes. </p>

<p>Remember, the Firebase Token is the one thing that allows the Server to reach the Client Device at any time using push messaging.</p>

<h4 id="updatingfirebasetoken">Updating Firebase Token</h4>

<p>For that we use a service which we define on the Manifest like this :</p>

<pre><code>&lt;service
    android:name=".firebase.MyFirebaseInstanceIDService"&gt;
    &lt;intent-filter&gt;
        &lt;action android:name="com.google.firebase.INSTANCE_ID_EVENT"/&gt;
    &lt;/intent-filter&gt;
&lt;/service&gt;
</code></pre>

<p>The code for that Service looks like this :</p>

<pre><code>public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    @Override
    public void onTokenRefresh() {

        //Getting registration token
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();

        //Displaying token on logcat
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        try {
            ServerFacade.sendRegistrationToServer(this, refreshedToken);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Log.e(TAG, e.getMessage(), e);
        }
    }
}
</code></pre>

<p>What this does is, everytime the Firebase token for the device changes, the <code>onTokenRefresh</code> method is called, in which we get the token, and then we use the <code>sendRegistrationToServer</code> method of the <code>ServerFacade</code> class to send it to the Server. </p>

<p>The other thing we need to do is do something when a message arives through Firebase. </p>

<h4 id="handlingarrivingmessages">Handling arriving messages</h4>

<p>To handle arriving messages from Firebase we use another service which we have defined on the Manifest like so:</p>

<pre><code>&lt;service
    android:name=".firebase.MyFirebaseMessagingService"&gt;
    &lt;intent-filter&gt;
        &lt;action android:name="com.google.firebase.MESSAGING_EVENT"/&gt;
    &lt;/intent-filter&gt;
&lt;/service&gt;
</code></pre>

<p>The code for that Service looks like this:</p>

<pre><code>public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        //Displaying data in log
        //It is optional
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());

        //Calling method to generate notification
        //sendNotification(remoteMessage.getNotification().getBody());

        Intent i = new Intent();
        i.setAction("RECEIVEMESSAGE");
        i.putExtra("rawdata", remoteMessage.getNotification().getBody());
        sendBroadcast(i);
    }
}
</code></pre>

<p>What this does is, everytime a message is sent to this device, the <code>onMessageReceived</code> method is called.  This method retrieves the name of the user who sent the message and the message itself and sends it to the <code>MainActivity</code> through broadcasting.  On the Activity we have a <code>BroadcastReceiver</code> implemented and registered to receive these notifications. Lets see 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>

<h4 id="broadcastreceivertoreceivemessages">BroadcastReceiver to Receive Messages</h4>

<p>On the <code>MainActivity</code> we have a inner class that extends <code>BroadcastReceiver</code> to receive the messages from the <code>MyFirebaseMessagingService</code> . The BroadcastReceiver is implemented like this :</p>

<pre><code>class MessageBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String rawData = intent.getStringExtra("rawdata");
        String user = rawData.split(":")[0].trim();
        String message = rawData.split(":")[1].trim();
        adapter.addMessage(
                user, message,
                (user.trim().equals(usernameET.getText().toString()))
        );
        Log.d("RAWDATA", "Received RawData : " + rawData);
    }
}
</code></pre>

<p>What it does is receive messages being sent from the <code>MyFirebaseMessagingService</code> service, extracts the User and Message from the raw message , and updates an Adapter that is set for the ListView of the interface. We'll see more about that in a minute.</p>

<p>For this BroadcastReceiver to actually receive stuff, it needs to be registered on the Activity, which is done like this:</p>

<pre><code>@Override
protected void onResume() {
    super.onResume();
    registerReceiver(mReceiver, new IntentFilter("RECEIVEMESSAGE"));
}
</code></pre>

<p>We also unregister is when we have the Activity go on Pause:</p>

<pre><code>@Override
public void onPause() {
    super.onPause();
    if (mScannerView != null) {
        mScannerView.stopCamera(); 
    }
    unregisterReceiver(mReceiver);
}
</code></pre>

<p>Now that we have the BroadcastReceiver out of the way, lets look at the ListView and the Adapter.</p>

<h4 id="chatmessagelistandadapter">Chat Message List and Adapter</h4>

<p>On the interface layout, we have a ListView called <code>chatLListView</code> which we assign to a variable on the <code>onCreate</code> method, and set an Adapter to it:</p>

<pre><code>chatList = (ListView) findViewById(R.id.chatLListView);
chatList.setAdapter(adapter);
</code></pre>

<p>That adapter is an instance of <code>ChatListAdapter</code> which is a <code>BaseAdapter</code> that draws one of two layouts depending on whether the message is from the same user as the user registered on the Android App, or not. The relevant method to take notice is the <code>getView</code> method, that looks like this:</p>

<pre><code>@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View v;
    LayoutInflater vi = LayoutInflater.from(context);

    ChatMessage p = getItem(position);

    if (p.isMe) {
        v = vi.inflate(R.layout.chatlayout_me, null);
    } else {
        v = vi.inflate(R.layout.chatlayout_others, null);
        ((TextView)v.findViewById(R.id.whoTV)).setText(p.user);
    }

    ((TextView)v.findViewById(R.id.messageTV)).setText(p.message);

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

<p>The two layouts that exist to render a message are <code>chatlayout_me</code> and <code>chatlayout_others</code>, and they look like this :</p>

<p><code>chatlayout_me</code> : </p>

<pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#d9fcd1"&gt;

    &lt;TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="me:"
        android:id="@+id/whoTV"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textColor="@android:color/black" /&gt;

    &lt;TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/messageTV"
        android:layout_below="@+id/whoTV"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" /&gt;
&lt;/RelativeLayout&gt;
</code></pre>

<p><code>chatlayout_others</code> :</p>

<pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#fcecbf"&gt;

    &lt;TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="me:"
        android:id="@+id/whoTV"
        android:textColor="@android:color/black"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" /&gt;

    &lt;TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/messageTV"
        android:layout_below="@+id/whoTV"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:gravity="right" /&gt;
&lt;/RelativeLayout&gt;
</code></pre>

<p>They are basically the same, with just a different background color and gravity.</p>

<p>Now for the QR Code Scanning!</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="qrcodescanning">QR Code Scanning</h3>

<p>The QR Code Scanning was based on this <a href="https://www.numetriclabz.com/android-qr-code-scanner-using-zxingscanner-library-tutorial/">Tutorial</a> , so, again, give it a read if you want to. We are using the ZXing library from google to do the scanning. </p>

<p>The overall idea is : When you press the QR Code Scan  button, that is on the <code>activity_main.xml</code> layout file ,  we initialize a scanning view from the ZXing library and we add it to the <code>qrScannerLayout</code>, which is a LinearLayout we have defined also on the <code>activity_main.xml</code> layout file. This was explained previously. We set the result listener of the scanner to the activity itself (because the <code>MainActivity</code> implements <code>ZXingScannerView.ResultHandler</code> ) and we start the Camera.  Like this:</p>

<pre><code>public void performQrScanner(View view) {

    qrScanneLayout.setVisibility(View.VISIBLE);
    mScannerView = new ZXingScannerView(this);   // Programmatically initialize the scanner view

    qrScanneLayout.addView(
            mScannerView
    );

    mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
    mScannerView.startCamera();         // Start camera
}
</code></pre>

<p>Because our <code>MainActivity</code> implements <code>ZXingScannerView.ResultHandler</code> we have to implement the <code>handleResult</code> method, which we do, just like this:</p>

<pre><code> public void handleResult(Result rawResult) {
    // Do something with the result here
    Log.e("handler", rawResult.getText()); // Prints scan results
    Log.e("handler", rawResult.getBarcodeFormat().toString()); // Prints the scan format (qrcode)
    // show the scanner result into dialog box.

    mScannerView.stopCamera();

    try {
        ServerFacade.sendRegisterUserToQRCode(
                this,
                usernameET.getText().toString(),
                rawResult.getText()
        );

        qrScanneLayout.removeView(
                mScannerView
        );
        qrScanneLayout.setVisibility(View.GONE);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        Log.e("Main Activity", e.getMessage(), e);
        qrScanneLayout.removeView(
                mScannerView
        );
        qrScanneLayout.setVisibility(View.GONE);
    }

}
</code></pre>

<p>On this method we extract the QR Code, which is the UUID provided by the server to the browser through the WebSocket, and we use the <code>ServerFacade</code> class to register the User that is using this device with that UUID.  This will trigger the Server to send a command to the Browser that belongs to that UUID notifying that it now belongs to the specific User, and the browser gets it interface updated with the Chat bit. </p>

<p>Now all that we are missing is the <code>ServerFacade</code> class that is used for communication with the Server.</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="communicationwithserver">Communication with Server</h3>

<p>All communications with the Server are made through the use of a class called <code>ServerFacade</code>. It uses Volley to do all HTTP communications. Check this <a href="https://developer.android.com/training/volley/index.html">Tutorial</a> for more information on Volley and how to use it.</p>

<p>There are three methods here:</p>

<ul>
<li><p><code>sendRegistrationToServer</code> : Used to send the deviceId of the android along with the Firebase Token. These are stored on the server for a way for the Server to know how to send message notifications back to the Device.</p></li>
<li><p><code>sendRegisterUserToQRCode</code> : Used to associate a User with the UUID of a QR Code. This is the method that lets the Server know that a WebSocket belongs to a user.</p></li>
<li><p><code>sendMessage</code> : Used to send messages all the registered users . </p>

<p>Give a look at them. There is nothing much to it really. </p>

<p>We have a RequestQueue wrapped in a Singleton, like described on this section of the Tutorial <a href="https://developer.android.com/training/volley/requestqueue.html">here</a> , which we call <code>RequestQueueSingleton</code>, so all http requests are placed on that queue. </p>

<p>On the ServerFacade, we build the requests using another Singleton called <code>Configuration</code> , which is where we have defined the Chat Server IP and Chat Server Port.</p>

<p>We place the Requests on the queue and that is it.</p></li>
</ul>

<h3 id="configurationsthatyouneedtochange">Configurations that you need to Change</h3>

<p>Before you can you this application, you need to go to the <code>Configuration</code> class and modify the IP and Port of the server you are running, so that the App knows where to reach it. And that is it. Compile and deploy it to your mobile phone!</p>

<h2 id="references">REFERENCES</h2>

<p><a href="https://mvnrepository.com/artifact/com.google.zxing/core/3.2.1">https://mvnrepository.com/artifact/com.google.zxing/core/3.2.1 </a></p>

<p><a href="http://www.websocket.org/echo.html">http://www.websocket.org/echo.html</a></p>

<p><a href="https://www.numetriclabz.com/android-qr-code-scanner-using-zxingscanner-library-tutorial/">https://www.numetriclabz.com/android-qr-code-scanner-using-zxingscanner-library-tutorial/</a></p>

<p><a href="https://www.simplifiedcoding.net/firebase-cloud-messaging-tutorial-android/">https://www.simplifiedcoding.net/firebase-cloud-messaging-tutorial-android/</a></p>

<p><a href="https://www.playframework.com/documentation/2.5.x/JavaWebSockets#handling-websockets">https://www.playframework.com/documentation/2.5.x/JavaWebSockets#handling-websockets</a></p>

<p><a href="https://blog.openshift.com/how-to-build-java-websocket-applications-using-the-jsr-356-api/">https://blog.openshift.com/how-to-build-java-websocket-applications-using-the-jsr-356-api/</a></p>

<p><a href="http://crunchify.com/java-simple-qr-code-generator-example/">http://crunchify.com/java-simple-qr-code-generator-example/</a></p>

<p><a href="https://developer.android.com/training/volley/index.html">https://developer.android.com/training/volley/index.html</a></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>

<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[Understanding Static in Java]]></title><description><![CDATA["What does Static means" or  "What is Static in Java" . A quick and easy overview of what Static is and how it works followed by examples]]></description><link>http://blog.jbaysolutions.com/2016/08/16/understanding-static-in-java/</link><guid isPermaLink="false">239624e1-5618-49b0-9154-5572e8a099dc</guid><category><![CDATA[java]]></category><category><![CDATA[Getting Started]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Tue, 16 Aug 2016 14:35:17 GMT</pubDate><content:encoded><![CDATA[<p>A very common question from beginners in Java is "<strong>What does Static means</strong>" or "<strong>What is Static in Java</strong>". It is actually very simple. </p>

<p>Something that is Static in Java is something that belongs to the Class and not the objects of that Class type, hence it is shared across the instances of that Class type.</p>

<p>To better understand what is meant by that, let us rewind a bit!</p>

<p>When writing a Java program, a programmer writes Classes and creates objects of those Class types, or other Class types that belong to some libs.  So, look at this Class:</p>

<pre><code>public class NumberHolder {

    public int number = 5;

}
</code></pre>

<p>This Class simply holds a number in a public variable called <code>number</code>.  If we wanted to use this class we would need to instantiate this class to create an object, and then use that object to store the value on the variable, just like so :</p>

<pre><code>NumberHolder holder1 = new NumberHolder();
holder1.number = 10;
</code></pre>

<p>If we would print the value of the "number" variable inside the holder1 object like so:</p>

<pre><code>System.out.println("Value of holder1 number : " + holder1.number);
</code></pre>

<p>we would get:</p>

<pre><code>Value of holder1 number : 10
</code></pre>

<p>Now, if we wanted to hold two numbers, we would need to create two objects of type <code>NumberHolder</code> and assign the values to them, like this:</p>

<pre><code>NumberHolder holder1 = new NumberHolder();
holder1.number = 10;

NumberHolder holder2 = new NumberHolder();
holder2.number = 99;
</code></pre>

<p>Printing the values of the number variables inside of each of the <code>NumberHolder</code> objects :</p>

<pre><code>System.out.println("Value of holder1 number : " + holder1.number);
System.out.println("Value of holder2 number : " + holder2.number);
</code></pre>

<p>Would produce :</p>

<pre><code>Value of holder1 number : 10
Value of holder2 number : 99
</code></pre>

<p>So, each of the objects has a variable that belongs to that specific object of class type <code>NumberHolder</code>. </p>

<p>Now in some cases there is a need to have a value that is shared across every instance of a particular class, and to do this, we use Static.  Now, bear in mind that making something Static has several implications, that we'll see a bit further down.</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="somethingthatisstatic">Something that is static</h2>

<p>So, now we'll create another class that we'll call <code>TotalHolder</code> , which looks somewhat like this:</p>

<pre><code>public class TotalHolder {

    public static int total = 0;

}
</code></pre>

<p>Very simple. Now, we'll create two instances of <code>TotalHolder</code> and do some assigning to the total int variable and see what happens:</p>

<pre><code>TotalHolder totalHolder1 = new TotalHolder();
TotalHolder totalHolder2 = new TotalHolder();

totalHolder1.total = 10;
System.out.println("Print total through totalHolder1 : " + totalHolder1.total);

totalHolder2.total = 500;
System.out.println("Print total through totalHolder2 : " + totalHolder2.total);

System.out.println("Print total again through totalHolder1 : " + totalHolder1.total);
</code></pre>

<p>If we run this code we get an output like this:</p>

<pre><code>Print total through totalHolder1 : 10
Print total through totalHolder2 : 500
Print total again through totalHolder1 : 500
</code></pre>

<p>So, as you can see, the value of the variable <code>total</code>, when being accessed through either of the <code>TotalHolder</code> instances will have the same value..... that is because <strong>it is exactly the same variable that is being accessed, not two different variables that share the same value, but the same exact variable!</strong>  In fact, the static variables (or methods) don't even belong to the Instances of objects, but to the Class itself... and to illustrate that I've made two pictures :</p>

<p><img src="http://blog.jbaysolutions.com/content/images/2016/08/teste.png" alt="Non-static image"></p>

<p>This last image show the example using the NumberHolder objects. As you can see, each instance of the NumberHolder has its own independent "number" variable.</p>

<p>As for the Static example, look at this image:</p>

<p><img src="http://blog.jbaysolutions.com/content/images/2016/08/teste--1-.png" alt="Static image"></p>

<p>Because the variable <code>total</code> is static, it does not belong to the Instances of the <code>TotalHolder</code>, but to the class itself. Which means that when accessed, through whatever instance of the object, it will be in fact the Class variable that is being accessed. </p>

<p>But that is not all..... because the static variables (and methods) belong to the Class, we don't really need to have Instances of the objects to access those variables, which means that the previous example code, code be re-written like this:</p>

<pre><code>TotalHolder.total = 10;
System.out.println("Print total through TotalHolder Class : " + TotalHolder.total);

TotalHolder.total = 500;
System.out.println("Print total through     TotalHolder Class : " + TotalHolder.total);

System.out.println("Print total again through TotalHolder Class : " + TotalHolder.total);
</code></pre>

<p>Notice that in this example we are not using any Instances, but instead accessing the <code>total</code> variable through the Class... which is completely legal, because the variable belongs to the class.... because it is static.... is it making sense? </p>

<p>But wait !!!!!!! This is not all !!!!! What about methods ?</p>

<p><strong>Methods can also be static, and the same story applies to those methods! Methods that are static belong to the Class, and methods that are not static belong to the instance</strong>.... Things might be starting to sound strange, but don't give up on this! It is actually quite simple and I'll try to explain it with examples 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>

<h2 id="staticmethodswhy">Static Methods? Why ?</h2>

<p>OK, lets recap a bit, cause this really needs to be second nature:</p>

<ul>
<li>Static variables belong to the Class</li>
<li>Static methods belong to the Class</li>
<li>Static methods and variables can be accessed directly through the Class, instead of Instances.</li>
<li>Non-static methods and variables belong to their Instances, and can only be accessed through those instances</li>
</ul>

<p>So, to have have a variable that is shared with all Instances of a Class type, we can use a static Variable. </p>

<p>But what about methods? What are the benefits of having Static methods? Are those really needed?</p>

<p>We'll focus on the benefits first!</p>

<p>Because a Static method can be accessed through the Class, there is no need to create an Instance of the class to get access to the methods, which can be very useful with memory management... less instances, less memory used, less GC , less everything! But this is not all. In terms of code style and code reading.... it just makes everything much more readable and easy to understand, if used properly. </p>

<p>One good, and very common use of Static methods, is to create Util classes. Util classes is not an official designation I think, but what I mean by that is a Class that has useful methods (that are usually isolated) to perform certain common tasks, such as for example a Math util class, which could look like this:</p>

<pre><code>public class MathUtil {

    public static double multiply( double par1, double par2) {
        return par1*par2 ;
    }

    public static double divide( double par1, double par2) {
        return par1/par2 ;
    }

    public static double add( double par1, double par2) {
        return par1-par2 ;
    }

    public static double subtract( double par1, double par2) {
        return par1-par2 ;
    }
}
</code></pre>

<p>This is obviously a very simple class, but you get the idea! To use this class to make some operations, we would do something like this:</p>

<pre><code>MathUtil.multiply( 20 , 2);
MathUtil.divide( 20 , 2);
MathUtil.add( 10 , 10);
MathUtil.subtract( 2 , 1);
</code></pre>

<p>Really easy to read, isn't it? And notice, because we didn't create an Instance of the <code>MathUtil</code> Class, we are actually saving memory! Now imagine that in the ultra massive bank accounting system that you are developing using Java, if these methods were not static, and these operations needed to be done in several places, all the time, you would be creating <code>MathUtil</code> Instances all over the place, you would eventually use a considerable amount of memory, which would also at some point would need to be Garbage Collected..... and not to speak of the object Instantiation times....  you see? Static methods are a solution to these issues.  Obviously that in a concurrent environment you would also need to have in mind concurrency considerations, but that is beyond the scope of this tutorial ( <a href="http://blog.jbaysolutions.com/2011/10/06/java-threading-and-concurrency-introduction/">Check this Concurrency Tutorial if you are interested</a> ) .</p>

<p><strong>The big rule with Static methods is that, if you are accessing anything outside this method, that something also needs to be Static</strong>. </p>

<p>And this makes sence.... lets think about this for a second:  If you are calling a Static method, and you know that a static method belongs to a Class and it can be accessed directly through the Class, if that method were to access a non-static variable, which would belong to a specific Instance, the VM wouldn't know which of the instance variables it was refering to, or even worst, if there were no Instances at all created, what would happen?  </p>

<p>So, as you can see, having a static method accessing variables or methods outside of the scope of the method is illegal and your code won't compile... because it makes no sense. </p>

<p>And yes... there is more! Lets talk about static blocks!</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="staticblocks">Static Blocks</h2>

<p>You know what a block is, and static block is not very different and looks like this:</p>

<pre><code>public class TotalHolder {

    static {
        total = 0;
    }

    public static int total;

}
</code></pre>

<p>Think of static blocks that a Class can have as a Constructor for the Class. What happens is this: When you start you program on the JVM, classes get loaded into memory, this is where the Classes will live, and will be available to create instances, and access static variables and methods. </p>

<p><strong>When a Class is loaded into memory, the JVM will initialize the static variables that exist on the Class, and will execute all the static blocks of the Class, in the order they are presented, always in that order.</strong> </p>

<p>Obviously, static block behave like static methods in the sense that they can only access static variables and methods that exist outside of the scope of the block, because.... specially at this time, when the static blocks are being executed, there will be no instances of those classes. </p>

<p>And this is it! We hope this was useful, and leave us any comment you would like to share or any doubts you may still have.</p>]]></content:encoded></item><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><item><title><![CDATA[Adding Image to PDF file using Java and IText]]></title><description><![CDATA[<p>To add an image to an already existing PDF file is a relatively simple task, using <a href="http://itextpdf.com/" title="iText">iText</a>.</p>

<p>On this example, we will add a smile image to the bottom of the PDF first page.</p>

<p>We start by loading the PDF we want to modify, and getting the reference for the</p>]]></description><link>http://blog.jbaysolutions.com/2015/10/27/adding-image-to-pdf-java-itext/</link><guid isPermaLink="false">b440d4a5-a073-4323-9f91-3dee253fe90e</guid><category><![CDATA[java]]></category><category><![CDATA[itext]]></category><category><![CDATA[pdf]]></category><dc:creator><![CDATA[Gustavo Santos]]></dc:creator><pubDate>Tue, 27 Oct 2015 15:49:00 GMT</pubDate><content:encoded><![CDATA[<p>To add an image to an already existing PDF file is a relatively simple task, using <a href="http://itextpdf.com/" title="iText">iText</a>.</p>

<p>On this example, we will add a smile image to the bottom of the PDF first page.</p>

<p>We start by loading the PDF we want to modify, and getting the reference for the first page:</p>

<pre><code class="language-java">    PdfReader reader = new PdfReader(srcPdf);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destPdf));
    PdfContentByte content = stamper.getOverContent(1);
</code></pre>

<p>srcPdf is a String with the full path to the existing PDF file, while destPdf is the full path where the modified PDF file will be created.  </p>

<p>Then, we load the image (imagePath is the full path for the imagem file):</p>

<pre><code>Image image = Image.getInstance(imagePath);

// scale the image to 50px height
image.scaleAbsoluteHeight(50);
image.scaleAbsoluteWidth((image.getWidth() * 50) / image.getHeight());
</code></pre>

<p>Since the image dimensions are large, it's scaled to 50 pixels height before we add it to the PDF.</p>

<p>We then set the page coordinates where we want it. <strong>Be aware that the 0 value for the Y axis is the bottom of the page, not the top:</strong></p>

<pre><code>image.setAbsolutePosition(70, 140);
</code></pre>

<p>All we need to do now is add it to the page reference and close the stamper:</p>

<pre><code>content.addImage(image);

stamper.close();
</code></pre>

<p>That's it! </p>

<p>The sample project with all the code, example PDF and image is available at github, <a href="https://github.com/jbaysolutions/add-image-to-pdf">here</a> </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></p>]]></content:encoded></item><item><title><![CDATA[Reading and converting XML files to Excel in Java]]></title><description><![CDATA[<p>Today we're going to show how to read a XML file and convert it's entries to lines on an excel file. </p>

<p>The XML file is located at <a href="https://github.com/jbaysolutions/xml-to-excel/blob/master/Publication1.xml?raw=true">https://github.com/jbaysolutions/xml-to-excel/blob/master/Publication1.xml?raw=true</a>.</p>

<p><strong>The XML file's main nodes are "Substances", each one has a few</strong></p>]]></description><link>http://blog.jbaysolutions.com/2015/10/16/reading-and-converting-xml-files-to-excel/</link><guid isPermaLink="false">f0159837-7141-49e2-9357-cf838f7e62c0</guid><category><![CDATA[java]]></category><category><![CDATA[apache poi]]></category><category><![CDATA[xml]]></category><dc:creator><![CDATA[Gustavo Santos]]></dc:creator><pubDate>Fri, 16 Oct 2015 14:43:45 GMT</pubDate><content:encoded><![CDATA[<p>Today we're going to show how to read a XML file and convert it's entries to lines on an excel file. </p>

<p>The XML file is located at <a href="https://github.com/jbaysolutions/xml-to-excel/blob/master/Publication1.xml?raw=true">https://github.com/jbaysolutions/xml-to-excel/blob/master/Publication1.xml?raw=true</a>.</p>

<p><strong>The XML file's main nodes are "Substances", each one has a few properties "Name", "entry_force", "directive" and a list of "Product". We're going to create an excel row for each Product. Each row will also have the Product parent Substance details.</strong></p>

<p>Below is a sample of the XML structure:</p>

<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;Pesticides&gt;
&lt;Header&gt;
    &lt;Creation_Date&gt;09/07/2015 13:45&lt;/Creation_Date&gt;
&lt;/Header&gt;
&lt;Substances&gt;
    &lt;Name&gt;Garlic extract (++)&lt;/Name&gt;
    &lt;entry_force&gt;01/09/2008&lt;/entry_force&gt;
    &lt;directive&gt;Reg. (EC) No 839/2008&lt;/directive&gt;
    &lt;Product&gt;
        &lt;Product_name&gt;FRUITS, FRESH or FROZEN; TREE NUTS&lt;/Product_name&gt;
        &lt;Product_code&gt;0100000&lt;/Product_code&gt;
        &lt;MRL/&gt;
        &lt;ApplicationDate&gt;01/09/2008&lt;/ApplicationDate&gt;
    &lt;/Product&gt;
    &lt;Product&gt;
        &lt;Product_name&gt;Oranges (Bergamots, Bitter oranges/sour oranges, Blood oranges, Cara caras, Chinottos,
            Trifoliate oranges, Other hybrids of Citrus sinensis, not elsewhere mentioned,)
        &lt;/Product_name&gt;
        &lt;Product_code&gt;0110020&lt;/Product_code&gt;
        &lt;MRL/&gt;
        &lt;ApplicationDate&gt;01/09/2008&lt;/ApplicationDate&gt;
    &lt;/Product&gt;
    &lt;Product&gt;
        &lt;Product_name&gt;Lemons (Buddha's hands/Buddha's fingers, Citrons,)&lt;/Product_name&gt;
        &lt;Product_code&gt;0110030&lt;/Product_code&gt;
        &lt;MRL/&gt;
        &lt;ApplicationDate&gt;01/09/2008&lt;/ApplicationDate&gt;
    &lt;/Product&gt;
    &lt;Product&gt;
        &lt;Product_name&gt;Limes (Indian sweet limes/Palestine sweet limes, Kaffir limes, Sweet limes/mosambis, Tahiti
            limes,)
        &lt;/Product_name&gt;
        &lt;Product_code&gt;0110040&lt;/Product_code&gt;
        &lt;MRL/&gt;
        &lt;ApplicationDate&gt;01/09/2008&lt;/ApplicationDate&gt;
    &lt;/Product&gt;
&lt;/Substances&gt;
&lt;Substances&gt;
(...)
&lt;/Substances&gt;
</code></pre>

<p>As usual, we use  <a href="http://poi.apache.org/" title="Apache POI">Apache POI</a>, to create the excel file.</p>

<p>You can get the sample project used in this post at <a href="https://github.com/jbaysolutions/xml-to-excel">GitHub</a>.</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></p>

<h2 id="downloadingthefile">Downloading the file</h2>

<p>We start by downloading the file from it's original URL location:</p>

<pre><code>File xmlFile = File.createTempFile("substances", "tmp");
String xmlFileUrl = "http://ec.europa.eu/food/plant/pesticides/eu-pesticides-database/public/?event=Execute.DownLoadXML&amp;id=1";
URL url = new URL(xmlFileUrl);
System.out.println("downloading file from " + xmlFileUrl + " ...");
FileUtils.copyURLToFile(url, xmlFile);
System.out.println("downloading finished, parsing...");
</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></p>

<h2 id="preparingtheexcelfile">Preparing the Excel file</h2>

<p>To create the Excel file where we're writing, we start by creating a new workbook, an empty sheet and writing the first line with the column headers:</p>

<pre><code>workbook = new XSSFWorkbook();

CellStyle style = workbook.createCellStyle();
Font boldFont = workbook.createFont();
boldFont.setBold(true);
style.setFont(boldFont);
style.setAlignment(CellStyle.ALIGN_CENTER);

Sheet sheet = workbook.createSheet();
rowNum = 0;
Row row = sheet.createRow(rowNum++);
Cell cell = row.createCell(SUBSTANCE_NAME_COLUMN);
cell.setCellValue("Substance name");
cell.setCellStyle(style);

cell = row.createCell(SUBSTANCE_ENTRY_FORCE_COLUMN);
cell.setCellValue("Substance entry_force");
cell.setCellStyle(style);

cell = row.createCell(SUBSTANCE_DIRECTIVE_COLUMN);
cell.setCellValue("Substance directive");
cell.setCellStyle(style);

cell = row.createCell(PRODUCT_NAME_COLUMN);
cell.setCellValue("Product name");
cell.setCellStyle(style);

cell = row.createCell(PRODUCT_CODE_COLUMN);
cell.setCellValue("Product code");
cell.setCellStyle(style);

cell = row.createCell(PRODUCT_MRL_COLUMN);
cell.setCellValue("MRL");
cell.setCellStyle(style);

cell = row.createCell(APPLICATION_DATE_COLUMN);
cell.setCellValue("Application Date");
cell.setCellStyle(style);
</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></p>

<h2 id="parsing">Parsing</h2>

<p>For this sample, the XML file is parsed using <a href="https://en.wikipedia.org/wiki/Document_Object_Model">DOM</a>.</p>

<p>We get the reference to the excel file sheet:</p>

<pre><code>Sheet sheet = workbook.getSheetAt(0);
</code></pre>

<p>We start by loading the XML document using DOM and getting the Substances node list:</p>

<pre><code>DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);

NodeList nList = doc.getElementsByTagName("Substances");
</code></pre>

<p>Then we iterate through the Substances list and get the Substance properties:</p>

<pre><code>for (int i = 0; i &lt; nList.getLength(); i++) {
    System.out.println("Processing element " + (i+1) + "/" + nList.getLength());
    Node node = nList.item(i);
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) node;
        String substanceName = element.getElementsByTagName("Name").item(0).getTextContent();
        String entryForce = element.getElementsByTagName("entry_force").item(0).getTextContent();
        String directive = element.getElementsByTagName("directive").item(0).getTextContent();

        NodeList prods = element.getElementsByTagName("Product");
</code></pre>

<p>When we get to the Product element, we get it as a NodeList and iterate it to get it's details:</p>

<pre><code>for (int j = 0; j &lt; prods.getLength(); j++) {
    Node prod = prods.item(j);
    if (prod.getNodeType() == Node.ELEMENT_NODE) {
        Element product = (Element) prod;
        String prodName = product.getElementsByTagName("Product_name").item(0).getTextContent();
        String prodCode = product.getElementsByTagName("Product_code").item(0).getTextContent();
        String lmr = product.getElementsByTagName("MRL").item(0).getTextContent();
        String applicationDate = product.getElementsByTagName("ApplicationDate").item(0).getTextContent();
</code></pre>

<p>Now that we have all the details we want to write on the excel file, we create a row with all the details:</p>

<pre><code>Row row = sheet.createRow(rowNum++);
Cell cell = row.createCell(SUBSTANCE_NAME_COLUMN);
cell.setCellValue(substanceName);

cell = row.createCell(SUBSTANCE_ENTRY_FORCE_COLUMN);
cell.setCellValue(entryForce);

cell = row.createCell(SUBSTANCE_DIRECTIVE_COLUMN);
cell.setCellValue(directive);

cell = row.createCell(PRODUCT_NAME_COLUMN);
cell.setCellValue(prodName);

cell = row.createCell(PRODUCT_CODE_COLUMN);
cell.setCellValue(prodCode);

cell = row.createCell(PRODUCT_MRL_COLUMN);
cell.setCellValue(lmr);

cell = row.createCell(APPLICATION_DATE_COLUMN);
cell.setCellValue(applicationDate);
</code></pre>

<p>When all the elements are written, we write the excel to the filesystem:</p>

<pre><code>FileOutputStream fileOut = new FileOutputStream("C:/Temp/Excel-Out.xlsx");
workbook.write(fileOut);
workbook.close();
fileOut.close();
</code></pre>

<p>Finally, we delete the downloaded XML file:</p>

<pre><code>if (xmlFile.exists()) {
    System.out.println("delete file-&gt; " + xmlFile.getAbsolutePath());
    if (!xmlFile.delete()) {
        System.out.println("file '" + xmlFile.getAbsolutePath() + "' was not deleted!");
    }
}
</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></p>

<h2 id="conclusion">Conclusion</h2>

<p>The sample project used in this post at <a href="https://github.com/jbaysolutions/excel-xml-reader">GitHub</a> has a main class <a href="https://github.com/jbaysolutions/xml-to-excel/blob/master/src/main/java/com/jbaysolutions/xmlreader/XmlToExcelConverter.java">XmlToExcelConverter</a> to download, parse the file and create the excel file.</p>

<p>Feel free to copy and adapt the code to read other XML files! <br>
Hope it helped anyone having the same issues as us!</p>

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

<p><a href="https://en.wikipedia.org/wiki/Document_Object_Model">DOM</a></p>

<p><a href="https://docs.oracle.com/javase/tutorial/jaxp/dom/">DOM Tutorial</a></p>

<p><a href="http://poi.apache.org/" title="Apache POI">Apache POI</a></p>]]></content:encoded></item><item><title><![CDATA[Starting new Activity in Android]]></title><description><![CDATA[<h2 id="fromanactivity">From an Activity</h2>

<p>To start a new Activity from another Activity:</p>

<pre><code>Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
</code></pre>

<h2 id="fromaservice">From a Service</h2>

<pre><code>Intent intent = new Intent(this, OtherActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
</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></p>

<h2 id="fromsomewhereelse">From somewhere else</h2>

<p>To start an Activity</p>]]></description><link>http://blog.jbaysolutions.com/2015/10/12/starting-new-activity-in-android/</link><guid isPermaLink="false">5dcf16d2-70a8-492c-a98a-6c3caf8ca844</guid><category><![CDATA[java]]></category><category><![CDATA[android]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Mon, 12 Oct 2015 14:22:23 GMT</pubDate><content:encoded><![CDATA[<h2 id="fromanactivity">From an Activity</h2>

<p>To start a new Activity from another Activity:</p>

<pre><code>Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
</code></pre>

<h2 id="fromaservice">From a Service</h2>

<pre><code>Intent intent = new Intent(this, OtherActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
</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></p>

<h2 id="fromsomewhereelse">From somewhere else</h2>

<p>To start an Activity from another class that does not extend Context or does not extend a class that allows access to a Context, a context must be retrieved in some way.</p>

<p>Either by passing it to the method being called:</p>

<pre><code>public void startNewActivity(Context context) {
    Intent intent = new Intent(this, OtherActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}
</code></pre>

<p>Or by using the Application Context, if the class that extends Application (if there is one) makes it available directy of by using an helper class. </p>

<h2 id="exampleofaplicationandappstatehelperclass">Example of Aplication and AppState Helper Class</h2>

<p>Following a set of classes to help with making the Application Context available to all classes of the project.</p>

<h3 id="theapplicationclassfortheproject">The Application class for the project:</h3>

<pre><code>package com.example.mytestapp;

import android.app.Application;
public class MyTestApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        MyTestAppState.setApplicationContext(this);
    }
}
</code></pre>

<h3 id="theappstateclassfortheproject">The AppState class for the project:</h3>

<pre><code>package com.example.mytestapp;

import android.content.Context;
import android.util.Log;

public class MyTestAppState {

    private static final String TAG = "MyTestAppState";
    private static Context sContext;

    private static MyTestAppState INSTANCE;

    public static MyTestAppState getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new MyTestAppState();
        }
        return INSTANCE;
    }

    private MyTestAppState() {
        if (sContext == null) {
            throw new IllegalStateException("MyTestAppState inited before app context set");
        }
        Log.v(TAG, "MyTestAppState inited");
    }

    public Context getContext() {
        return sContext;
    }

    public static void setApplicationContext(Context context) {
        if (sContext != null) {
        Log.w(TAG, "setApplicationContext called twice! old=" + sContext + " new=" + context);
        }
        sContext = context.getApplicationContext();
    }
}
</code></pre>

<h3 id="usingtheapplicationcontext">Using the Application Context</h3>

<pre><code>Intent intent = new Intent(this, OtherActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MyTestAppState.getInstance().getContext().startActivity(intent);
</code></pre>

<h2 id="whatisintentflag_activity_new_task">What is Intent.FLAG<em>ACTIVITY</em>NEW_TASK</h2>

<p>According to the Android Development API documents, when this Flag is set, the new ACtivity will become the start of a new task on the History Stack.</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></p>]]></content:encoded></item><item><title><![CDATA[Reading and parsing Excel Spreadsheet XML files with Java]]></title><description><![CDATA[<p>On one of our projects, we were asked to implement a process that updates a database with values from an Excel file on a daily basis. The file is located at <a href="https://github.com/jbaysolutions/excel-xml-reader/raw/master/ActiveSubstance.xls">https://github.com/jbaysolutions/excel-xml-reader/raw/master/ActiveSubstance.xls</a>. The problem with this file is its format. It's an</p>]]></description><link>http://blog.jbaysolutions.com/2015/03/04/parsing-excel-spreadsheet-xml/</link><guid isPermaLink="false">2c3dd67a-5ff8-48b5-8ccb-24c0f2c8bf39</guid><category><![CDATA[java]]></category><category><![CDATA[apache poi]]></category><category><![CDATA[excel]]></category><category><![CDATA[excel spreadsheet xml]]></category><category><![CDATA[excel 2003]]></category><dc:creator><![CDATA[Gustavo Santos]]></dc:creator><pubDate>Wed, 04 Mar 2015 17:29:31 GMT</pubDate><content:encoded><![CDATA[<p>On one of our projects, we were asked to implement a process that updates a database with values from an Excel file on a daily basis. The file is located at <a href="https://github.com/jbaysolutions/excel-xml-reader/raw/master/ActiveSubstance.xls">https://github.com/jbaysolutions/excel-xml-reader/raw/master/ActiveSubstance.xls</a>. The problem with this file is its format. It's an <a href="http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats#Excel_XML_Spreadsheet_example">Excel spreadsheet XML</a>.</p>

<p>Usually we parse excel files using <a href="http://poi.apache.org/" title="Apache POI">Apache POI</a>, but it has no support for Excel spreadsheet XML. The solution was to create our own parser.</p>

<p>For this specific case, we will cover the process of obtaining the substance name (column A), ADI value (column P) and ARfD value (column S).</p>

<p>You can get the sample project used in this post at <a href="https://github.com/jbaysolutions/excel-xml-reader">GitHub</a>.</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></p>

<h2 id="downloadingthefile">Downloading the file</h2>

<p>This class was to be used by a timer that runs once a day. Starts by downloading the file:</p>

<pre><code>File file = File.createTempFile("substances", "tmp");

String excelFileUrl = "http://ec.europa.eu/sanco_pesticides/public/?event=activesubstance.exportList";
URL url = new URL(excelFileUrl);
System.out.println("downloading file from " + excelFileUrl + " ...");
FileUtils.copyURLToFile(url, file);
System.out.println("downloading finished, parsing...");
</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></p>

<h2 id="parsing">Parsing</h2>

<p>Since the file format is XML, it can be parsed using <a href="http://en.wikipedia.org/wiki/Simple_API_for_XML">SAX</a>.</p>

<p>Since this file has only one sheet, we are keeping the parser simple, so we will only need to find the sheet rows and cells. We declare a class to represent the row:</p>

<pre><code>class XmlRow {
    ArrayList&lt;String&gt; cellList = new ArrayList&lt;&gt;();

    @Override
    public String toString() {
        return cellList.toString();
    }
}
</code></pre>

<p>And a SAX handler to load the rows and cell ("Data" in the XML) contents:</p>

<pre><code>class SAXHandler extends DefaultHandler {

    List&lt;XmlRow&gt; xmlRowList = new ArrayList&lt;&gt;();
    XmlRow xmlRow = null;
    String content = null;

    @Override
    //Triggered when the start of tag is found.
    public void startElement(String uri, String localName, String qName, Attributes attributes)
            throws SAXException {
        switch (qName) {
            //Create a new Row object when the start tag is found
            case "Row":
                xmlRow = new XmlRow();
                break;
        }
    }

    @Override
    public void endElement(String uri, String localName,
                           String qName) throws SAXException {
        switch (qName) {
            case "Row":
                xmlRowList.add(xmlRow);
                break;
            case "Data":
                xmlRow.cellList.add(content);
                break;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        content = String.copyValueOf(ch, start, length).trim();
    }
}
</code></pre>

<p>Once the file is downloaded, it's loaded to a string to be supplied to the SAX Parser:</p>

<pre><code>String fileContent = IOUtils.toString(new FileInputStream(file));

SAXParserFactory parserFactor = SAXParserFactory.newInstance();
SAXParser parser = parserFactor.newSAXParser();
SAXHandler handler = new SAXHandler();

ByteArrayInputStream bis = new ByteArrayInputStream(fileContent.getBytes());

parser.parse(bis, handler);
</code></pre>

<p>When we try and run this the first time, and exception occurs:</p>

<pre><code>Exception in thread "main" org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 14; The processing instruction target matching "[xX][mM][lL]" is not allowed.
</code></pre>

<p>This happens because some blank space or other visible content exists before the <?xml ?> declaration. For this file, we have to remove the first 2 lines, so it can be parsed:</p>

<pre><code>
<b>removeLineFromFile(file.getAbsolutePath(), 1, 2);</b>

String fileContent = IOUtils.toString(new FileInputStream(file));

SAXParserFactory parserFactor = SAXParserFactory.newInstance();
SAXParser parser = parserFactor.newSAXParser();
SAXHandler handler = new SAXHandler();

ByteArrayInputStream bis = new ByteArrayInputStream(fileContent.getBytes());

parser.parse(bis, handler);
</code></pre>

<p><strong>The removeLineFromFile() method can be found on the sample project source.</strong></p>

<p>When we try to parse it again, another exception is thrown:</p>

<pre><code>Exception in thread "main" org.xml.sax.SAXParseException; lineNumber: 1313; columnNumber: 70; The entity "nbsp" was referenced, but not declared.
</code></pre>

<p>This happens because the entity <code>&amp;nbsp;</code> isn't one of XML's predefined entities. To fix it, we have to prepend this to the file before parsing it:</p>

<pre><code>&lt;?xml version="1.0"?&gt;
&lt;!DOCTYPE some_name [ 
    &lt;!ENTITY nbsp "&amp;#160;"&gt; 
    &lt;!ENTITY acute "&amp;#180;"&gt;
]&gt;
</code></pre>

<p>The <code>&amp;acute;</code> entity was also found on the file, so we added it as well.</p>

<p>There was also the text "JECFA&amp;ECCO" somewhere in a cell which would cause the parser to throw another exception.</p>

<p>The code now looks like this:</p>

<pre><code>removeLineFromFile(file.getAbsolutePath(), 1, 2);

String fileContent = IOUtils.toString(new FileInputStream(file));
fileContent = fileContent.replaceAll("&amp;ECCO", "&amp;#38;ECCO");
fileContent = "&lt;?xml version=\"1.0\"?&gt;\n" +
        "&lt;!DOCTYPE some_name [ \n" +
        "&lt;!ENTITY nbsp \"&amp;#160;\"&gt; \n" +
        "&lt;!ENTITY acute \"&amp;#180;\"&gt; \n" +
        "]&gt;" + fileContent;


SAXParserFactory parserFactor = SAXParserFactory.newInstance();
SAXParser parser = parserFactor.newSAXParser();
SAXHandler handler = new SAXHandler();

ByteArrayInputStream bis = new ByteArrayInputStream(fileContent.getBytes());

parser.parse(bis, handler);
</code></pre>

<p>We now have a row list, where each row has a cell list. We are going to use this to get our values:</p>

<pre><code>//Parsing the substances list obtained from XML
int count = 0;
for (XmlRow subsRow : handler.xmlRowList) {
    if (subsRow.cellList.size() &gt; 19) {
        String substance = subsRow.cellList.get(0);
        if (substance.equals("Substance")) {
            continue;
        }

        count++;
        String adi = subsRow.cellList.get(15); // column P
        String arfd = subsRow.cellList.get(18); // column S

        System.out.println("Substance name='" + substance + "', ADI='" + adi + "', ARfD='" + arfd + "'");
    }
}
</code></pre>

<p>In this example we only care for the substance rows, so we ignore any row that has less than 19 cells. On our project class we use these values to update a DB table, but for simplicity here we are only printing them.</p>

<p>If our goal was to create a regular Excel file, we could change the code to:</p>

<pre><code>Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet();

//Converts all rows to POI rows 
int rowCount = 0;
for (XmlRow subsRow : handler.xmlRowList) {
    Row row = sheet.createRow(rowCount);
    int cellCount = 0;
    for (String cellValue : subsRow.cellList) {
        Cell cell = row.createCell(cellCount);
        cell.setCellValue(cellValue);
        cellCount++;
    }
    rowCount++;
}

String fileOutPath = "/tmp/fileOut.xls";
FileOutputStream fout = new FileOutputStream(fileOutPath);
workbook.write(fout);
workbook.close();
fout.close();
</code></pre>

<p>As you can see, it can be easily modified depending on the purpose!</p>

<p>Finally, we delete the downloaded file:</p>

<pre><code>if (file.exists()) {
    System.out.println("delete file-&gt; " + file.getAbsolutePath());
    if (!file.delete()) {
        System.out.println("file '" + file.getAbsolutePath() + "' was not deleted!");
    }
}
//System.out.println(result);
System.out.println("getAndParseFile finished, processed " + count + " substances!");
</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></p>

<h2 id="conclusion">Conclusion</h2>

<p>For the purpose of reading data from an Excel spreadsheet XML file, it's relatively simple to do it.</p>

<p>The sample project used in this post at <a href="https://github.com/jbaysolutions/excel-xml-reader">GitHub</a> has two main classes. <a href="https://github.com/jbaysolutions/excel-xml-reader/blob/master/src/main/java/com/jbaysolutions/excelparser/ExcelXmlReader.java">ExcelXmlReader</a> to download, parse the file and print the values to the console and the <a href="https://github.com/jbaysolutions/excel-xml-reader/blob/master/src/main/java/com/jbaysolutions/excelparser/ExcelXmlConverter.java">ExcelXmlConverter</a> class, to download, parse the file and converts it to OOXML file format.</p>

<p>The code can be modified to read multiple sheets or even the styles if necessary. It just wasn't needed for our use case. </p>

<p>Hope it helped anyone having the same issues as us!</p>

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

<p><a href="http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats#Excel_XML_Spreadsheet_example">Excel spreadsheet XML</a></p>

<p><a href="http://en.wikipedia.org/wiki/Simple_API_for_XML">SAX</a></p>

<p><a href="http://poi.apache.org/" title="Apache POI">Apache POI</a></p>]]></content:encoded></item><item><title><![CDATA[JPA 2 Tutorial - Queries with JPQL]]></title><description><![CDATA[<p>If you are following the tutorials here you must be dying to do some queries using JPA. So, before we go any further into other aspects of JPA, lets query the model! For this task, instead of using SQL we will be using the <strong>Java Persistence Query Language</strong> or also</p>]]></description><link>http://blog.jbaysolutions.com/2014/10/16/jpa-2-tutorial-queries-on-the-model/</link><guid isPermaLink="false">d2a1755a-9d21-4c5c-889b-2ef3b09f19ee</guid><category><![CDATA[java]]></category><category><![CDATA[jpa]]></category><category><![CDATA[eclipselink]]></category><category><![CDATA[mysql]]></category><category><![CDATA[jpql]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Thu, 16 Oct 2014 13:17:09 GMT</pubDate><content:encoded><![CDATA[<p>If you are following the tutorials here you must be dying to do some queries using JPA. So, before we go any further into other aspects of JPA, lets query the model! For this task, instead of using SQL we will be using the <strong>Java Persistence Query Language</strong> or also known as <strong>JPQL</strong>. Exciting, yes?</p>

<h3 id="sampleproject">Sample Project</h3>

<p>About the sample project provided: it is a Maven project, we do not require an App Server at this point and the database used is a MySQL database. Check the <a href="http://blog.jbaysolutions.com/jpa2-tutorials">JPA2 Tutorials</a> page for links of recommended software.</p>

<p>You can get the project at <a href="https://github.com/jbaysolutions/jpa2tut-queries">GitHub</a>.</p>

<h1 id="whatisandwhyusejpql">What is and Why use JPQL?</h1>

<p>Before going into what is <strong>JPQL</strong>, lets talk about <strong>SQL</strong>. SQL is a query language used for managing data in a relational database. It an <strong>ANSI</strong> and <strong>ISO standard</strong>, but if you try running a medium to high complexity SQL query in two different relational databases from two different vendors, you are in for a big surprise. Why is that? Because some vendors create specific dialects of the SQL language.</p>

<p>Now imagine for a second you have a big application that you just developed and deployed, which is using a specific relational database, and for some reason you decide to migrate your data to another relational database from a different vendor. Well, if you wrote your queries in SQL, you are well advised to go and double check all of your queries for correctness against the new dialect. </p>

<p><strong>JPQL</strong> to the rescue. <strong>JPQL</strong> is a query language, much like <strong>SQL</strong> (<em>syntax wise and all that</em>), but instead of querying over a relational database, it queries over the persistent schema of entities and relationships (<em>which is almost the same thing, but not quite!</em>). What this means is that, if the relational model of the new database is still represented by the schema of entities and relationships you have on your project, then your JPQL queries will be portable and will work as expected. Emphasys on <strong>Portability</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></p>

<h1 id="selectstatements">Select Statements</h1>

<p>For our tutorial we'll use the model created for the <a href="http://blog.jbaysolutions.com/2011/09/19/jpa-2-relationships-onetomany/">One-To-Many Tutorial</a> but we will extend it a bit more:</p>

<p><img src="http://blog.jbaysolutions.com/content/images/2014/10/overview-2.png" alt="Database model"></p>

<p>You can get the MySQL Workbench file for this from the <em>model</em> folder of the sample project. Along with the Workbench file there is a <strong>SQL script</strong> that creates the model and adds a few entries to it so we can test our queries:</p>

<pre><code>INSERT INTO `jpa2tut-queries`.`company` (`name`, `address`, `created_year`) VALUES ('JBay Solutions', 'Somewhere in Portugal', 2009);
INSERT INTO `jpa2tut-queries`.`company` (`name`, `address`, `created_year`) VALUES ('JetBrains', 'Somewhere in Prague', 2000);
INSERT INTO `jpa2tut-queries`.`company` (`name`, `address`, `created_year`) VALUES ('Google', 'Somewhere in the US', 1998);
INSERT INTO `jpa2tut-queries`.`company` (`name`, `address`, `created_year`) VALUES ('Yahoo', 'Somewhere in the US',1994);
INSERT INTO `jpa2tut-queries`.`company` (`name`, `address`, `created_year`) VALUES ('MySQL', 'Somewhere in an Oracle Office', 1995);
</code></pre>

<p>Also, check the <strong>src/main/java</strong> folder of the project in order to check the Entity Objects we have. An understanding of these objects is core to understanding the <strong>JPQL</strong> code we will write next. </p>

<h2 id="asimpleselect">A Simple Select</h2>

<p>As you can see from the previous <strong>SQL</strong> bits, we have a few entries on the <em>company</em> table. Lets query for the list of those entries:</p>

<pre><code><b>SELECT</b> c <b>FROM</b> CompanyEntity <b>AS</b> c
</code></pre>

<p>At this point you should be going like: <em>Wait a second please... I understand this language!</em>. Like said before, JPQL is very much like the regular SQL, except that we perform queries on the <em>persistent schema of entities and relationships</em>. </p>

<p>Lets run this in Java. Check the files inside the <strong>src/test/java</strong> folder of the sample project. You should be looking for the <strong>QueryTesting.java</strong> file at the method <strong>testSimpleQuery</strong>:</p>

<pre><code>Query query = em.createQuery("<b>SELECT</b> c <b>FROM</b> CompanyEntity <b>AS</b> c");
for ( CompanyEntity ce : (List&lt;CompanyEntity&gt;)query.getResultList()) {
    System.out.println(" -> Company : " + ce.getName() );
}
</code></pre>

<p>We give it a run:  </p>

<pre><code>[...]
[EL Info]: connection: 2014-10-14 16:41:13.476 --ServerSession(1563886825)--file:/home/rui/projects/jpa2tut-queries/target/test-classes/_jpa2tut-test login successful
 -> Company : JBay Solutions
 -> Company : JetBrains
 -> Company : Google
 -> Company : Yahoo
 -> Company : MySQL
</code></pre>

<p>Simple, yes? We create a <strong><em>Query</em></strong> Object with the JPQL query and we call <strong><em>em.getResultList();</em></strong> . We cast the result to <strong><em>List&lt;CompanyEntity&gt;</em></strong> , because we know that <strong><em>getResultList()</em></strong> returns a <em>List</em> (it does) and we also know that the query we created returns objects of <strong><em>CompanyEntity</em></strong> type.</p>

<p>We can also restrict the number of results being returned from the Query, by modifying the JPQL query used. Imagine we want to return all the companies that are called "<strong>JBay Solutions</strong>":</p>

<pre><code>SELECT c FROM CompanyEntity AS c <b>WHERE</b> c.name='JBay Solutions'
</code></pre>

<p>And the code being (<em>testSimpleQueryWhere method</em>) :  </p>

<pre><code>Query query = em.createQuery("SELECT c FROM CompanyEntity AS c <b>WHERE c.name='JBay Solutions'</b>");
for ( CompanyEntity ce : (List&lt;CompanyEntity&gt;)query.getResultList()) {
    System.out.println(" -> Company : " + ce.getName() );
}
</code></pre>

<p>Give it a quick spin:</p>

<pre><code>[EL Info]: connection: 2014-10-14 16:54:56.972--ServerSession(1861307614)--file:/home/rui/projects/jpa2tut-queries/target/test-classes/_jpa2tut-test login successful
 -> Company : JBay Solutions

Process finished with exit code 0
</code></pre>

<p>At this point one should be able to make pretty simple, but very useful queries, but some issues stand out:</p>

<ul>
<li>We must be constantly <strong>casting the results</strong></li>
<li>All our queries until now <strong>allow no input</strong></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></p>

<h2 id="entertypedquery">Enter TypedQuery</h2>

<p>In JPA2 a new type of Query object was introduced. The <strong>TypedQuery</strong>, which allows us to make a Query that is <em>Typed</em>. That is it, <em>TypedQuery extends Query</em>, allowing one to define straight away what is to be returned and avoid continuously Casting every single result. </p>

<p>Looking at our previous examples, we can modify them to use <strong>TypedQuery</strong> instead of <strong>Query</strong> by using an overloaded <strong><em>createQuery method</em></strong> from the <strong>EntityManager</strong> that also takes as a parameter the Type of the query result:</p>

<pre><code><b>TypedQuery&lt;CompanyEntity&gt;</b> query = em.createQuery("SELECT c FROM CompanyEntity AS c"<b>, CompanyEntity.class</b>);

<b>TypedQuery&lt;CompanyEntity&gt;</b> query = em.createQuery("SELECT c FROM CompanyEntity AS c WHERE c.name='JBay Solutions'"<b>, CompanyEntity.class</b>);
</code></pre>

<p>to perform the iteration now we do:  </p>

<pre><code>for (CompanyEntity ce : query.getResultList()) {
    System.out.println(" -> Company : " + ce.getName());
}
</code></pre>

<p>No casting, no nothing. For the complete code check both <em>testSimpleTypedQuery</em> and <em>testSimpleTypedQueryWhere</em> methods of the <em>QueryTesting.java</em> file on the test sources.</p>

<p>We still have the <strong>no input</strong> issue to work on. </p>

<h2 id="passinginputtothequeries">Passing Input to the Queries</h2>

<p>In a way, some examples we shown before could be easily modified in a way to allow inputs to be passed onto them. Check this out: </p>

<pre><code>String <b>inputName</b> = "JBay Solutions"; 
TypedQuery&lt;CompanyEntity&gt; query = em.createQuery("SELECT c FROM CompanyEntity AS c WHERE c.name='" + <b>inputName</b> + "'", CompanyEntity.class);
</code></pre>

<p>Can you spot the problem with this? Well, simple, if you want to perform this query several times with different inputs, then you need to continuously re-create a new Query object. Not counting the <strong>performance impact</strong> it will have, it also <strong>leads to the JPQL not being readable at all</strong>. Imagine a query like the one presented but with several <em>conditional expressions</em> on the <em>WHERE clause</em>. What a nightmare. </p>

<p>To avoid these situations we have in JPQL:</p>

<ul>
<li><strong>Named Parameters</strong></li>
<li><strong>Positional Paramenters</strong></li>
</ul>

<p>Constructing a Query with any of these types of dynamic parameters allows a Query to be reused (and therefore avoid constant instantiation of Query objects) and makes the JPQL query much more readable.</p>

<h3 id="namedparameters">Named Parameters</h3>

<p>Lets look at the following example (from <em>testSimpleTypedQueryWhereInputNamed</em> method):</p>

<pre><code>em.createQuery("SELECT c FROM CompanyEntity AS c WHERE <b>c.name=:nameParam</b>", CompanyEntity.class);
query.setParameter("<b>nameParam</b>", "JBay Solutions");
</code></pre>

<p>So, a named parameter is a parameter that is called out by name. It is defined using the <strong>:&lt; param_name ></strong> notation:</p>

<ul>
<li>They are defined using the "<strong>:</strong>" prefix</li>
<li>They are Case Sensitive</li>
<li><strong>$</strong> and <strong>_</strong> chars are allowed, </li>
<li><strong>?</strong> is not allowed.</li>
<li>They can be used more than once on the Query string</li>
<li>They must be SET to something on execution</li>
<li>There is a list of reserved identifiers that cannot be used. Some of these reserved identifiers are : <strong>SELECT</strong> , <strong>WHERE</strong>, <strong>GROUP</strong>, <strong>TRUE</strong>, and many more, but you get the gist. <strong><em>These reserved identifiers are case insensitive</em></strong>, and non can be used as a named parameter. </li>
</ul>

<p>The named parameters are then set on the Query using the <em>setParameter</em> method of the Query instance:</p>

<pre><code><b>query.setParameter</b>("<b>nameParam</b>", "JBay Solutions");
for (CompanyEntity ce : query.getResultList()) {
    System.out.println(" -> Company : " + ce.getName());
}
<b>query.setParameter</b>("<b>nameParam</b>", "Google");
for (CompanyEntity ce : query.getResultList()) {
    System.out.println(" -> Company : " + ce.getName());
}</code></pre>

<p>What happens if you don't set one of the parameters? You get an IllegalStateException:</p>

<pre><code>[...]
[EL Info]: connection: 2014-10-14 18:30:02.302--ServerSession(822392390)--file:/home/rui/projects/jpa2tut-queries/target/test-classes/_jpa2tut-test login successful

<b>java.lang.IllegalStateException</b>: Query argument nameParam not found in the list of parameters provided during query execution.
    at org.eclipse.persistence.internal.jpa.QueryImpl.processParameters(QueryImpl.java:498)
    [...]
</code></pre>

<h3 id="positionalparameter">Positional Parameter</h3>

<p>Lets look at the following example (from <em>testSimpleTypedQueryWhereInputNumbered</em> method):</p>

<pre><code>em.createQuery("SELECT c FROM CompanyEntity AS c WHERE <b>c.name=?1</b>", CompanyEntity.class);
query.setParameter(<b>1</b>, "JBay Solutions");
</code></pre>

<p>A positional parameter is defined using the <strong>?&lt; int ></strong> notation:</p>

<ul>
<li>The parameters are numbered starting with <b>1</b></li>
<li>Positional parameter can appear more than once in the Query string.</li>
<li>The order by which they are set is irrelevant</li>
</ul>

<p>So:</p>

<pre><code>query.setParameter(1, "JBay Solutions");
query.setParameter(2, "Google");
</code></pre>

<p>will return the same  as:</p>

<pre><code>query.setParameter(2, "Google");
query.setParameter(1, "JBay Solutions");
</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></p>

<h1 id="usingmultipleentities">Using Multiple Entities</h1>

<p>Right, making JPQL queries that take into account several Entities is the next logical step. For that, take into account the following SQL script (that is part of the <strong><em>create-and-populate.sql</em></strong> file of the sample project):</p>

<pre><code>INSERT INTO `jpa2tut-queries`.`employee` (`name`, `address`, `idcompany`, `birthday`) VALUES ('Rui Pereira', 'Lisbon',1 , '1981-06-27' );
INSERT INTO `jpa2tut-queries`.`employee` (`name`, `address`, `idcompany`, `birthday`) VALUES ('Gustavo Santo', 'Peniche',1, '1979-12-19');
INSERT INTO `jpa2tut-queries`.`employee` (`name`, `address`, `idcompany`, `birthday`) VALUES ('Maxim Shafirov', 'St.Petersburg, Russia',2, '1970-06-01');
INSERT INTO `jpa2tut-queries`.`employee` (`name`, `address`, `idcompany`, `birthday`) VALUES ('Valentin Kipiatkov', 'St.Petersburg, Russia',2, '1975-06-01');
<i>[... many more entries]</i>
</code></pre>

<p>This simply adds a few Employees to the previously created Companies. Now we have <strong>JBay Solutions</strong> with two employees and <strong>JetBrains</strong> with also two employees, and the remaining companies with also two employess (<em>check file for the remaining entries</em>).</p>

<p>Lets create a JPQL query that returns the employees of a particular company:</p>

<pre><code>TypedQuery&lt;EmployeeEntity&gt; query =
    em.createQuery("SELECT employee FROM <b>CompanyEntity AS company</b>, <b>EmployeeEntity as employee</b> " +
    "WHERE <b>company.name=:name</b> " +
    "<b>AND employee.company = company</b>", EmployeeEntity.class);
</code></pre>

<p>Pretty simple, yes? </p>

<ul>
<li>On the <strong>FROM</strong> clause we define <strong>two Entities</strong> with <strong>two Identifiers</strong></li>
<li>we make use of a <strong>named parameter</strong></li>
<li>we make use of the <strong>AND logical operator</strong></li>
</ul>

<p>Remember we said that <em>JPQL perform queries on the persistent schema of entities and relationships</em>. EmployeeEntity has a <strong>ManyToOne Relationship</strong> defined to CompanyEntity, and therefore we can use that relationship in our JPQL queries. The relationship is defined like this:</p>

<pre><code>@ManyToOne
@JoinColumn(name = "idcompany", referencedColumnName = "idcompany")
private CompanyEntity company;
</code></pre>

<p>Therefore when we in JPQL do something like <code>employee.company = SOMETHING</code>, we call <code>employee.company</code> a <strong>Path Expression</strong>, and the result for this case should be pretty obvious, because the relationship maps to only one other Entity. We'll talk a bit more about <strong>Path Expressions</strong> in a bit.</p>

<p>Lets give a run at <em>testMultipleEntities1</em> method on the <em>QueryTesting.java</em>, which runs this query like this:</p>

<pre><code>query.setParameter("name", "JBay Solutions");
for (EmployeeEntity client : query.getResultList()) {
    System.out.println(" -&gt; Q1 : " + client.getName());
}

query.setParameter("name", "JetBrains");
for (EmployeeEntity client : query.getResultList()) {
    System.out.println(" -&gt; Q2 : " + client.getName());
}
</code></pre>

<p>And check the results:</p>

<pre><code>[EL Info]: connection: 2014-10-14 20:58:59.383--ServerSession(1268465323)--file:/home/rui/projects/jpa2tut-queries/target/test-classes/_jpa2tut-test login successful
 -&gt; Q1 : Rui Pereira
 -&gt; Q1 : Gustavo Santo
 -&gt; Q2 : Maxim Shafirov
 -&gt; Q2 : Valentin Kipiatkov
</code></pre>

<p>Perfect!</p>

<p>Now, on the other side of the relationship, we'll have a <strong>OneToMany Relationship</strong>, like this:</p>

<pre><code>@OneToMany(mappedBy = "company")
private Collection&lt;EmployeeEntity&gt; employeeCollection;
</code></pre>

<p>And using that collection there on a JPQL query is also possible, but not as shown before. When we write something like this <code>AND employee.company = company</code> , the <code>employee.company</code> part as we said before is called a <strong>Path Expression</strong>, and one of the rules of <strong>Path Expressions</strong> is that it cannot be created from another <strong>Path Expression</strong> that evaluates to a collection. Lost you all there? In order words, check this next example.</p>

<p>Take this bit of code <code>FROM EmployeeEntity as employee</code> , we could create these <strong>Path Expressions</strong> :</p>

<ul>
<li><strong>employee.name</strong> : <em>Evaluates to a String</em></li>
<li><strong>employee.id</strong> : <em>Evaluates to an int</em></li>
<li><strong>employee.address</strong> : <em>Evaluates to a String</em></li>
<li><strong>employee.company</strong> : <em>Evaluates to a Company object</em></li>
<li><strong>employee.company.id</strong> : <em>Evaluates to an int</em></li>
<li><strong>employee.company.name</strong> : <em>Evaluates to a String</em></li>
<li><strong>employee.company.address</strong> : <em>Evaluates to a String</em></li>
<li><strong>employee.company.employeeCollection</strong> : <em>Evaluates to a Collection</em></li>
</ul>

<p>So you see, we created <strong>Path Expressions</strong> from other path expression in the way that <code>employee.company.id</code> is created from the <code>employee.company</code> <strong>Path Expression</strong>. </p>

<p>Since we have that rule of not being able to create from <strong>Path Expressions</strong> that evaluate to Collections, we can't do the following :</p>

<ul>
<li><strong>employee.company.employeeCollection.id</strong> : <em>Illegal</em></li>
<li><strong>employee.company.employeeCollection.name</strong> : <em>Illegal</em></li>
<li><strong>employee.company.employeeCollection.address</strong> : <em>Illegal</em></li>
<li><strong>employee.company.employeeCollection.company</strong> : <em>Illegal</em></li>
</ul>

<p>But <strong>Path Expressions</strong> that evaluate to Collections can be very useful in other ways. Lets give it another try at writting a JPQL query that makes use of this to achieve that same goal as the previous one:</p>

<pre><code>TypedQuery&lt;EmployeeEntity&gt; query =
    em.createQuery("SELECT employee FROM <b>CompanyEntity AS company</b>, <b>EmployeeEntity as employee</b> " +
    "WHERE <b>company.name</b>=<b>:name</b> " +
    "AND <b>employee MEMBER OF company.employeeCollection</b> ", EmployeeEntity.class);
</code></pre>

<p>See what we did there?</p>

<ul>
<li>we made use of the <strong>MEMBER OF comparison operator</strong></li>
<li>and we have a working knowledge of what is a <strong>Path Expression</strong></li>
</ul>

<p>There are a few more rules regarding <strong>Path Expressions</strong>, but a working knowledge is quite enough. If you feel you must know these right now, please check the JPA 2 Final Spec, which can be found at the bottom of this post in the References section. </p>

<p>About the <strong>MEMBER OF comparison operator</strong>, there are quite a few comparison operators, like <strong>BETWEEN</strong>, <strong>IN</strong> , <strong>EMPTY</strong>, <strong>EXISTS</strong>, <strong>LIKE</strong>, <strong>IS NULL</strong> and your well known <strong>=</strong> , <strong>></strong>, <strong>&lt;</strong>, <strong>&lt;></strong>, <strong>&lt;=</strong>, and <strong>>=</strong> .</p>

<h2 id="thememberofoperator">The MEMBER OF operator</h2>

<p>The <strong>MEMBER OF</strong> operator is used to match or <strong>NOT</strong> the existence of <em>something</em> in a <em>Collection</em>. An example if we may :</p>

<pre><code><i>employee</i> <b>MEMBER OF</b> <i>company.employeeCollection</i>
</code></pre>

<p>The <em>employee</em> section is a <em>path expression</em> that evaluates to an entity. It could evaluate to a simple value (like for example <code>employee.id</code> does) or an object (like <code>employee.company</code>), these are allowed. </p>

<p>The <em>company.employeeCollection</em> section is a <em>path expression</em> that will evaluate to a Collection of Employees. That is it.</p>

<p>To match the inexistence of <em>something</em> inside a <em>Collection</em>, we can use the <strong>NOT MEMBER OF</strong>, like this:</p>

<pre><code><i>employee</i> <b>NOT MEMBER OF</b> <i>company.employeeCollection</i>
</code></pre>

<p>The <strong>NOT</strong> is a constant in the remaing comparison operators, like we will see next. </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></p>

<h2 id="thebetweenoperator">The BETWEEN operator</h2>

<p>Lets shift our focus now to the <em>Company</em> table and <em>CompanyEntity</em> bean. There is a field there that stores the year the Company was created. It is mapped as an Integer and cannot be Null. </p>

<p>For our next task we will write a JPQL query that will return the Companies that were created in 1995 or after and in 2005 or before:</p>

<pre><code>em.createQuery("SELECT company FROM CompanyEntity AS company " +
"WHERE company.<b>createdYear >= 1995</b> " +
"AND company.<b>createdYear <= 2005<="" b=""> ", CompanyEntity.class);
</=></b></code></pre>

<p>Easy, yes? But we could use the <strong>BETWEEN</strong> operator in the following way:</p>

<pre><code>"WHERE company.createdYear <b>BETWEEN</b> 1995 AND 2005 "</code></pre>

<p>Which will return the exact same result. <br>
Expanding on what we already know, we could actually just replace both the <strong>MIN</strong> and <strong>MAX</strong> arguments of the <strong>BETWEEN</strong> operator with named parameters and allow for them to be defined dynamically:</p>

<pre><code>query = em.createQuery("SELECT company FROM CompanyEntity AS company"+
"WHERE <b>company.createdYear BETWEEN :minimum AND :maximum</b> ", CompanyEntity.class);
query.setParameter("minimum", 1995);
query.setParameter("maximum", 2000);</code></pre>

<p>But <strong>BETWEEN</strong> can be used with other types of parameters, like <strong>Dates</strong>. Lets write a JPQL query that returns now all the Employees of any company that were born between 1979-01-01 and today:</p>

<pre><code>TypedQuery<employeeentity> query =
    em.createQuery("SELECT employee FROM EmployeeEntity AS employee"+
    "WHERE <b>employee.birthday BETWEEN :minimum AND :maximum</b> ", EmployeeEntity.class);
query.setParameter(<b>"minimum", "1979-01-01"</b>);
query.setParameter(<b>"maximum", new Date()</b>);
</employeeentity></code></pre>

<p>To get the exclusion of those dates, you use the NOT :</p>

<pre><code>"WHERE employee.birthday <b>NOT BETWEEN</b> :minimum AND :maximum ", EmployeeEntity.class);</code></pre>

<p>Moving on.</p>

<h2 id="thelikeoperator">The LIKE operator</h2>

<p>We know how to compare Strings, we have the regular <strong>=</strong> and <strong>&lt;></strong> comparison operators. Lets try them out in writing a JPQL query that returns all the companies that are named Google:</p>

<pre><code>SELECT company FROM CompanyEntity AS company WHERE  company.name = 'Google'
</code></pre>

<p>But what about if on our database, that company was named "google" and not "Google"? Well, that query would fail, that's what. </p>

<p>And what if we want to return all the Companies that have "oo" (two 'o's) in their name? Well then we have to write a pattern and check which entries match that pattern. </p>

<p>For that we use the <strong>LIKE</strong> operator.</p>

<p>The <strong>LIKE</strong> works like this : on the <strong>left hand side you place a String</strong> or a path expression that evaluates to a String. On the <strong>right hand side you place a String that has a pattern</strong> to be matched. </p>

<p>So, if we do:</p>

<pre><code>WHERE  company.name LIKE 'google'
</code></pre>

<p>We would get a match for companies named:</p>

<ul>
<li>google</li>
<li>Google</li>
<li>GOOGLE</li>
<li>GoOgLe</li>
</ul>

<p>In order words: 5 letter words that have the same letters in that order, but are case insensitive.</p>

<p>Lets write a JPQL that matches all Companies with "oo" in their name, no matter where in their name:</p>

<pre><code>WHERE company.name LIKE '%oo%' 
</code></pre>

<p>Here we go. Now we will match :</p>

<ul>
<li>Google</li>
<li>Yahoo</li>
<li>oo.org</li>
<li>Boo</li>
</ul>

<p>The <strong>%</strong> character is a wildcard character that matches any sequence of characters, including an emply one. The other wildcard charater we have is the underscore <strong>_</strong> which matches exactly one character.</p>

<p>So, if we were to write:</p>

<pre><code>WHERE company.name LIKE '%oo_'
</code></pre>

<p>We would only match companies named like this:</p>

<ul>
<li>Gooa</li>
<li>Goob</li>
<li>oox</li>
<li>ooy</li>
<li>yahooa</li>
</ul>

<p>Why? Because the <strong>_</strong> wildcard must match exactly 1 character, whatever character it is, but it must be 1!</p>

<p>As with the precious operator, if we want to get all the company names that don't match that pattern, we use the <strong>NOT</strong> :</p>

<pre><code>WHERE  company.name NOT LIKE '%oo%' 
</code></pre>

<p>And we get pretty much any company whose name doesn't have exactly two 'o's together. </p>

<h2 id="theemptyoperator">The EMPTY operator</h2>

<p>The <strong>EMPTY</strong> operator simply evaluates if Collection expressed by a <em>path expression</em> is empty, or <strong>NOT EMPTY</strong>. </p>

<p>Lets write a JPQL query that returns all the companies that have no employees:</p>

<pre><code>SELECT company FROM CompanyEntity AS company WHERE <b>company.employeeCollection IS EMPTY</b>
</code></pre>

<p>The <em>company.employeeCollection</em> poins to a Collection of Employees. If we run this query against our test database, we get no returns, because all the companies on our DB have employees. So instead lets have a query that returns all the companies that have employees:</p>

<pre><code>SELECT company FROM CompanyEntity AS company WHERE <b>company.employeeCollection IS NOT EMPTY</b>
</code></pre>

<p>And now if we run that query we get returned all the Companies in our test DB.</p>

<h2 id="thenulloperator">The NULL operator</h2>

<p>Not that any of the operators are difficult to understand, but <strong>NULL</strong> is by far the easiest one. <strong>IS NULL</strong> is used to test if a give <em>path expression</em> or parameter is a NULL value , or <strong>NOT</strong>. </p>

<p>For completeness' sake lets write a JPQL query that returns all Employees that have their address NULL:</p>

<pre><code>SELECT employee FROM EmployeeEntity AS employee WHERE  employee.address IS NULL
</code></pre>

<p>And now, a query that returns all the Employees that don't have their address NULL:</p>

<pre><code>SELECT employee FROM EmployeeEntity AS employee WHERE  employee.address IS NOT NULL
</code></pre>

<p>In case you are wondering, a <em>path expression</em> that evaluates to a <strong>Collection cannot be NULL</strong>. It can however be <strong>EMPTY</strong> or <strong>NOT EMPTY</strong>. So, if you try something like this:</p>

<pre><code>SELECT company FROM CompanyEntity AS company WHERE  company.employeeCollection IS NULL
</code></pre>

<p>Well... that just isn't going to work.</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></p>

<h1 id="butthereismore">But there is more!</h1>

<p>What about Subqueries? Any more comparision operators? And Update and Delete statements? What about the Criteria API? </p>

<p>We'll take a break here, because this post is getting big and we'll continue on the next post! We'll update this one with a link as soon as the next post comes out.</p>

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

<p><a href="http://download.oracle.com/otndocs/jcp/persistence-2.0-fr-oth-JSpec/">JPA 2 Final Spec</a></p>]]></content:encoded></item><item><title><![CDATA[JPA 2 Tutorial – Many To Many with Self]]></title><description><![CDATA[<p><a href="http://syshex.files.wordpress.com/2013/06/self.png"><img src="http://syshex.files.wordpress.com/2013/06/self.png" alt="self" title=""></a>
We have just covered the subject of Many-To-Many relationships, which is a fun topic for the hole family! Now there are some particular cases on the Many-to-many front which are not particularly hard, but can lead to a bit of confusion. One of those particular cases is the M2M with</p>]]></description><link>http://blog.jbaysolutions.com/2013/06/06/jpa-2-tutorial-many-to-many-with-self-2/</link><guid isPermaLink="false">3cdd1429-e2bd-4ec3-b88f-7a47248a1aff</guid><category><![CDATA[java]]></category><category><![CDATA[jpa]]></category><category><![CDATA[eclipselink]]></category><category><![CDATA[mysql]]></category><dc:creator><![CDATA[Rui Pereira]]></dc:creator><pubDate>Thu, 06 Jun 2013 15:40:42 GMT</pubDate><content:encoded><![CDATA[<p><a href="http://syshex.files.wordpress.com/2013/06/self.png"><img src="http://syshex.files.wordpress.com/2013/06/self.png" alt="self" title=""></a>
We have just covered the subject of Many-To-Many relationships, which is a fun topic for the hole family! Now there are some particular cases on the Many-to-many front which are not particularly hard, but can lead to a bit of confusion. One of those particular cases is the M2M with same table.      </p>

<p>A reader asked : "How would one create manyToMany relationship with the same entity. Entity user can have friends (user), and can be friend to other users. With note that junction table has to have some additional columns besides user keys. How can that be achieved?"  (Thanks Felix for the feedback and question!)</p>

<p>So, to start of let us be clear that to follow this Tutorial you should :</p>

<ol>
<li><p>Have a basic understanding of JPA2 , enough to create a few entities etc</p></li>
<li><p>Know how to create a Many to many relationship between two related Entities</p></li>
</ol>

<p>If you have been following the Tutorials till now, then you can go right ahead and start this one. If you haven't been following but know the stuff that is fine as well. If you want to go and check them out : <a href="http://blog.jbaysolutions.com/tag/jpa">JPA2 Tutorials</a> .</p>

<p>You'll need EclipseLink, JUnit and MySQL, so if you are missing any of these this is the time to go and get them:</p>

<ul>
<li><p><a href="http://www.eclipse.org/eclipselink/downloads/">EclipseLink</a></p></li>
<li><p><a href="http://dev.mysql.com/downloads/mysql/">MySQL</a></p></li>
<li><p><a href="https://github.com/KentBeck/junit/downloads">JUnit</a></p></li>
</ul>

<p>Source Code for all of this can be found at <a href="https://sourceforge.net/projects/syshex/files/?source=navbar">Sourceforge</a></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></p>

<h1 id="letsgetstarted">Lets get started</h1>

<p>In the previous tutorial we have discussed about the<em>* Join Table</em>*, which is a table that has one only purpose, which is to allow the creation of a many to many relationship between two tables. This is not entirely correct, as it was pointed out by simply reading the question that was posed. The two tables can in fact be the same table, and in that case the Join Table is mapping a many to many relationship between elements of the same type.  The following diagram exemplifies:</p>

<p><a href="http://syshex.files.wordpress.com/2013/06/m2m_self2.png"><img src="http://syshex.files.wordpress.com/2013/06/m2m_self2.png" alt="m2m_self" title=""></a></p>

<p>Let us start by creating a database with these two tables. The SQL should look something like this :</p>

<pre><code> CREATE TABLE IF NOT EXISTS `jpatutorial3u1`.`person` (
  `idperson` INT NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(45) NOT NULL ,
  `phonenumber` VARCHAR(45) NULL ,
  PRIMARY KEY (`idperson`) )
 ENGINE = InnoDB;
 CREATE TABLE IF NOT EXISTS `jpatutorial3u1`.`business` (
  `seller` INT NOT NULL ,
  `buyer` INT NOT NULL ,
  PRIMARY KEY (`seller`, `buyer`) ,
  INDEX `fk_person_has_person_person1_idx` (`buyer` ASC) ,
  INDEX `fk_person_has_person_person_idx` (`seller` ASC) ,
  CONSTRAINT `fk_person_has_person_person`
  FOREIGN KEY (`seller` )
  REFERENCES `jpatutorial3u1`.`person` (`idperson` )
  ON DELETE NO ACTION
  ON UPDATE NO ACTION,
  CONSTRAINT `fk_person_has_person_person1`
  FOREIGN KEY (`buyer` )
  REFERENCES `jpatutorial3u1`.`person` (`idperson` )
  ON DELETE NO ACTION
  ON UPDATE NO ACTION)
 ENGINE = InnoDB;  
</code></pre>

<p>As for the Entity Bean, let us create one Entity called <strong>PersonEntity</strong>, and add the existing columns to it, just the columns for now. The main bits of the <strong>PersonEntity</strong> class should look somewhat like this:</p>

<pre><code>@Entity
@Table(name = "person", catalog = "jpatutorial3u1", schema = "")
public class PersonEntity implements Serializable {
 private static final long serialVersionUID = 1L;
 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "idperson", nullable = false)
 private Integer idperson;

 @Basic(optional = false)
 @Column(name = "name", nullable = false, length = 45)
 private String name;

 @Basic(optional = true)
 @Column(name = "phonenumber", length = 45)
 private String phonenumber;
</code></pre>

<p>Create now the Getters and Setters for these fields. While we are at it, lets go and take a look at the <strong>Test Packages</strong> folder and check the <strong>MemSelfTest</strong> JUnit class. For those not following the source code, the relevant bit is :</p>

<pre><code>@Test
public void testMemSelf(){
        // Start a transaction
        em.getTransaction().begin();
        // ------------
       PersonEntity c = new PersonEntity();
        c.setName("Rui");
        em.persist(c);
        em.flush();

        Object result = em.find(PersonEntity.class, c.getIdperson());
        assertEquals(c, result);

        em.remove(c);
        em.flush();

        // Commit the Transaction
        em.getTransaction().commit();
}
</code></pre>

<p>It doesn't really do much except for creating a Person, searching for it, and removing it.... just to make sure everything is working fine and we can proceed.</p>

<p>The basic stuff is now done, lets move on to the mapping of the relationship</p>

<h1 id="whosoldtowho">Who Sold To Who?</h1>

<p>Lets start with editing the <strong>PersonEntity</strong> class by adding the following bit:</p>

<pre><code> @JoinTable(name = "business", joinColumns = {
 @JoinColumn(name = "seller", referencedColumnName = "idperson", nullable = false)}, inverseJoinColumns = {
 @JoinColumn(name = "buyer", referencedColumnName = "idperson", nullable = false)})
 @ManyToMany
 private Collection&lt;PersonEntity&gt;soldToCollection;
</code></pre>

<p>and, as per usual, add the Setters and Getters for <strong>soldToCollection</strong>.</p>

<p>If you are a bit lost right now with the notation used and the way it was used, then you should probably give a read to  <a href="http://blog.jbaysolutions.com/2012/12/17/jpa-2-relationships-many-to-many/">JPA 2 Tutorial – Relationships – Many To Many</a> , but I'll recap a bit here.</p>

<p>The <strong>@JoinTable</strong> annoration is used on the Owning Entity side of the relationship, which is in fact the PersonEntity class (both the owning and the inverse to be honest, but it will depend on the context it is being used).  The <strong>Join Table</strong> is specify as "<strong>friend</strong>" , which is the name of the Join Table and then we do the <strong>JoinColumns</strong> bit, in which we specify the Fields used to map the relationship. Please do give a read at <a href="http://blog.jbaysolutions.com/2012/12/17/jpa-2-relationships-many-to-many/">JPA 2 Tutorial – Relationships – Many To Many</a> if nothing seems to make sense at this point!</p>

<p>Let us modify the <strong>M2mSelfTest</strong> JUnit class now. First let us create another few users :</p>

<pre><code>PersonEntity c = new PersonEntity();
c.setName("Rui");
PersonEntity f1 = new PersonEntity();
f1.setName("Felix");
PersonEntity f2 = new PersonEntity();
f2.setName("Gusy");
em.persist(c);
em.persist(f1);
em.persist(f2);
em.flush();
</code></pre>

<p>Now we got a few <strong>PersonEntity</strong> objects to play about with. After the <strong><em>assertEquals</em></strong> that we have created previously, add the following bit as well:</p>

<pre>
    assertEquals(c.getSoldToCollection().size(),0);
    <strong>c.getSolfToCollection().add(f1);
    em.merge(c);
    em.flush();</strong>
    assertEquals(c.getSoldToCollection().size(),1);
    System.out.println(c.getName() + " sold stuff to :");
    for (PersonEntity tempP : c.getSoldToCollection() )
          System.out.println(" - " + tempP.getName() );
</pre>

<p>and to finish it off , lets delete every object we have created and clean the DB :</p>

<pre><code>em.remove(c);
em.remove(f1);
em.remove(f2);
em.flush();
// Commit the Transaction
em.getTransaction().commit();
</code></pre>

<p>Run it and, if it was done right, everything should have work fine:</p>

<pre>    
    [EL Info]: 2013-06-06 16:07:42.49--ServerSession(805125680)--EclipseLink, version: Eclipse Persistence Services - 2.3.2.v20111125-r10461
    [EL Info]: 2013-06-06 16:07:42.753--ServerSession(805125680)--file:/home/rui/projects/syshex-code/JPATutorial3.1/trunk/build/classes/_JPATutorial3.1PU login successful
    <strong>Rui sold stuff to :
     - Felix</strong>
</pre>

<p>But you know what would be really cool too? For a us to know who he Bought stuff from, yeah?</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></p>

<h1 id="whodidheboughtfrom">Who did He Bought From?</h1>

<p>First, lets modify the <strong>PersonEntity</strong> again and add the following:</p>

<pre>    
    @ManyToMany(mappedBy = "<strong>soldToCollection</strong>")
    private Collection&lt;PersonEntity&gt;<strong> boughtFromCollection</strong>;
</pre>

<p>Feeling a bit lost? Check out  <a href="http://blog.jbaysolutions.com/2012/12/17/jpa-2-relationships-many-to-many/">JPA 2 Tutorial – Relationships – Many To Many</a> where it is explained everything about <strong>@ManyToMany</strong> and the <em><strong>mappedBy</strong></em> property.</p>

<p>Go ahead and create the Setter and Getter for this new collection, and afterward , lets go to the <strong>MemSelfTest</strong> JUnit test and modify like so:</p>

<pre>    
    System.out.println(c.getName() + " sold stuff to :");
    for (PersonEntity tempP : c.getSoldToCollection() )
         System.out.println(" - " + tempP.getName() );

    System.out.println(c.getName() + " Bought stuff from :");
    for (PersonEntity tempP : c.getBoughtFromCollection())
         System.out.println(" - " + tempP.getName() );

    <strong>em.refresh(f1)</strong>;

    System.out.println(f1.getName() + " sold stuff to :");
    for (PersonEntity tempP : f1.getSoldToCollection() )
        System.out.println(" - " + tempP.getName() );

    System.out.println(f1.getName() + " Bought stuff from :");
    for (PersonEntity tempP : f1.getBoughtFromCollection())
         System.out.println(" - " + tempP.getName() );

</pre>

<p>Lets run it !</p>

<pre><code>[EL Info]: 2013-06-06 16:18:04.464--ServerSession(745084087)--EclipseLink, version: Eclipse Persistence Services - 2.3.2.v20111125-r10461
[EL Info]: 2013-06-06 16:18:04.73--ServerSession(745084087)--file:/home/rui/projects/syshex-code/JPATutorial3.1/trunk/build/classes/_JPATutorial3.1PU login successful
Rui sold stuff to :
- Felix
Rui Bought stuff from :
Felix sold stuff to :
Felix Bought stuff from :
- Rui
</code></pre>

<p>Wicked stuff really.</p>

<p>But, what if.... we need to store some information regarding the relationship?</p>

<h1 id="storinginfoaboutrelationship">Storing Info about Relationship</h1>

<p>Well, then we would have something like this :</p>

<p><a href="http://syshex.files.wordpress.com/2013/06/m2m_self_not_really.png"><img src="http://syshex.files.wordpress.com/2013/06/m2m_self_not_really.png" alt="m2m<em>self</em>not_really" title=""></a></p>

<p>Now, as it was said in the last Tutorial :</p>

<p>The table that you see serving as a connection between the Company table and the Client table is what is called a “<strong>Join Table</strong>” ,  and its sole purpose in life is to keep track of the relations that exist between Company and Client Entities.</p>

<p>And storing information regarding <strong>Money</strong> in it will make it have<em>* more the a "sole" purpose<strong>. Not that it is wrong to do this, if you need to have information regarding the relationship, but since it has information, it should be an Entity. It could be called  *</strong></em>BusinessEntity, in which <strong>money</strong> , seller and buyer are in fact information that regard the Business.</p>

<p>In looking at this <strong>Business</strong> <strong>table</strong> and an <strong>Entity</strong> and not as a simple <strong>JoinTable</strong>, we can deduce that there are One-To-Many relationships to be used instead of the<em>* Many-To-Many</em>*.</p>

<p>So, wrapping it up, in this situation you should see this in a totally different light than a M2M</p>

<p>Hope his helped, and as per usual, leave a comment if you find errors, problems, or for a kind word. And again, thanks for checking out our blog.</p>

<p>Also, check the next tutorial on this series: <a href="http://blog.jbaysolutions.com/2014/10/16/jpa-2-tutorial-queries-on-the-model/">JPA 2 Tutorial - Queries with JPQL</a></p>]]></content:encoded></item></channel></rss>