7/15/2018

Learn Control Flow in Javascript(While, Do-While, For, For/in Loop)

Control flow in javascript is similar to C, C++ or any programming language. Now question is why we need Control flow in javascript or any other programming language, the reason is very simple as we all know that programs are groups of code and software are groups of programs so in a program there is a block of code we have to execute again and again and for saving space we can not write the code again and again to avoid this problem we use Control flow to control flow or block of code instead of writing again and again in programming language. In this tutorial, we will understand Control flow in details with complete syntax and example but before starting tutorials I just want to clear one doubts here in other programming languages we have only three Control flow (For Loop, Do...While Loop, and While Loop) and in Javascript we have one extra Control flow (For - in Loop), yes we have total of four loops in javascript or we can say that four Control flow statements in javascript. Basically, control flow controls the flow of programming and with the help of Loop avoid the repetitive code.

So in this tutorials, we are going to learn the Javascript Control Flow Structures or For Loop control flow javascript or For-In Loop control flow javascript or While Loop control flow javascript or Do-While control flow javascript in depth with complete explanation.

What are we going to learn?


  1. Control Flow
  2. What is Loop
  3. Types of Loops
  4. For Loop 
  5. For – in Loop
  6. While Loop
  7. Do-While Loop
  8. Syntax of Loops
  9. Examples of Loops
  10. Author Bio


Note: I just want to clarify that there is a big difference between Control flow and Conditional Statements tutorials in Javascript. If you don't know about conditions statements I suggest you have to read the Conditional Statements in-depth article before reading this article. this will helps you a lot to understand about flow control flow in javascript.

Control Flow


When a block of code needs to be executed many times with a different value, Then Control statements are required, According to a condition that is satisfied. Basically, Loops are there to avoid the repetitive code.

Loop Learn Control Flow diagram in Javascript
Image Source: Wikipedia


What are the Loops?


In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached. Typically, a certain process is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number or not.

Types of Loops or Loops in JavaScript are:


  1. For Loop 
  2. For – in Loop
  3. While Loop
  4. Do-While Loop

1. For Loop:

For loop is there to execute a block of code multiple times, For Loop is one of the best examples of a control flow of programs in programming statement in Javascript. Below is the syntax of FOR LOOP

Syntax:

for (statement 1; statement 2; statement 3)
{
    code block
}

Statement 1 is Checked or executed once before the execution.
Statement 2 Specify the condition of execution of code.
Statement 3 is executed every time until the specified condition is true.

For example:

for (i = 1; i <= 100; i++)
{
    text += "Value of i is " + i + "<br>";
}

Here i=1 is the statement1 which is executed once when execution of for loop will be started. Basically, we will use this to initialize that variable used by the loop.
I <=100 is statement 2 which is the basic condition that statements will be executed until the value of i will be 100.
i++ is the statement three which is executed every time when control satisfy the defined condition and I will increment by 1 every time.

For Loop Example:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>
<p id="ForLoopdemo"></p>
<script>
var number = "";
var n;
for (n = 0; n < 10; n++) {
    number += " Number is " + n + "<br>";
}
document.getElementById("ForLoopdemo").innerHTML = number;
</script>
</body>
</html>

We can omit these statement:

1.) Statement 1 can be omitted:

You can omit the statement 1 as it is optional for us, You can write it like:

Example:
             Initialize the variable before loop started.
           var Total = 0;
            var i = 1;
           for ( ; i < = 100; i++)
            {
             Total = Total + i;
             }
alert("Sum = " + Total);

2.) Statement 2 can be omitted:

As statement 2 is optional loop will work fine but you can put a break inside the for loop otherwise it will execute infinite times. Initialize the variable before loop started.

Example:

           var Total = 0;
            for (var i = 1 ; ; i++)
            {
             Total = Total + i;
              Break;
             }
             alert("Sum = " + Total);

3.) Statement 3 can be omitted :

  • If you don’t write the statement 3 but it can be incremented inside the for a loop.
  • if you don’t define any of the increment or decrement in the variable it will be executed only once.
  • Initialize the variable before loop started.

Example:

           var Total = 0;
           var i = 1;
           for ( ; i < = 100;)
            {
             Total = Total + i;
             i++;
             }
           alert("Sum = " + Total);

2. For-In Loop

the for..in loop is executed object's properties.

Syntax

for (variablename in object)
{
   code Block;
}

here in For-In Loop each time one property of the object is assigned to the variable and loop continues until object’s properties are exhausted.

Example

<!DOCTYPE html>
<html>
<body>
<p id="ForIn"></p>
<script>
    var book = {AuthorName:"Suman", bookName:"Tutorial", age:25}; 
    var bookProperties = "";
    var attributes;
    for (attributes in book) {
        bookProperties += book[attributes] + " ";
    }
    document.getElementById("ForIn").innerHTML = bookProperties;
</script>
</body>
</html>

3. While Loop

while loop will execute the block of code until the condition we specified is true. When the control comes to condition and found that condition is false control comes out of the loop and execute the exact next statement after the while loop.
While Loop firstly checks the condition then statements are got executed.

while (var < lastvalue)
{
block of code;
}

Example:

<html>
<body>
<script type="text/javascript">
var n=0
while (n<10)
{
document.write("Value of n is " + n)
document.write("<br />")
n=n+1
}
</script>
</body>
</html>

Here loop will be executed 10 times, the value of loop start for n=0 and condition will be true till n=9. When n=10 then the condition will be false and control comes out of the While loop.

While loop Control Flow in Javascript with gif example output


4. Do…While Loop

The do...while loop, you can also say it a variant of a while. Here the block of code will be executed at least once before testing the condition. So even if the condition becomes false though the code will be executed once.

do
{
Block of code;
}
while (var<=lastValue)

Example

<html>
<body>
<script type="text/javascript">
var n=0
do
{
document.write("value of n is " + n)
document.write("<br />")
n=n+1
}
while (n<10)
</script>
</body>
</html>

Tip: Always careful when you use control flow in programming cause if your desire conditions are not matched than your control flow may be infinite or you loop can be endless. so always twice checks the conditions of Loops and you can fix the flow of a program using loops.

Author Bio:


JavaScript Control flow Tutorials is provided by Suman Yadav. Thanks, Suman for the Awesome and Unique article. If you want to submit your article and want to be a member of our Programming With Basics Family Join us by sending a well-written article more information read Write for Us
Read More »

7/06/2018

Top 10 Very Useful Java Code Snippets for Java Developers

List of Java code snippets for every Java developer should know. Being a Java developer can be quite stressful sometimes, Java code snippets for Java developer With the need to constantly iterate and come up with new ways to combine Java with other programming languages, developers are desperate for any form of help. here is the list of latest top 10 Java code snippets that will help any Java developer.

Luckily, as with any other coding system, Java offers an extensive selection of fixed codes that never change drastically. These snippets can allow developers more freedom to explore and combine their knowledge for better effect. With that said, let’s look at the most useful code snippets that any Java developer will be happy to have in their arsenal.

10+ very useful Java code snippets for Java Developers


1. Appending text to file
2. Connecting to Oracle
3. Converting to SQL
4. Generating PDF
5. Setting up HTTP Proxy
6. Screenshots in Java
7. Emailing via Java
8. Directory listing
9. Image thumbnail
10. Compression and ZIP files

top 10 java code snippets

1. Appending text to file


Clients often ask the developers to add text to their newly-created code. This text is often used to inform the end-user of certain legal details, technical information or another announcement. However, Java developers spend a lot of time on these codes and are often left with the bloated code as a result. Using a simple appendance code that adds text to file can alleviate much of that frustration:

BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(”filename”, true));
out.write(”aString”);
} catch (IOException e) {
// error processing code
} finally {
if (out != null) {
out.close();
}
}

2. Connecting to Oracle


Oracle is the de facto hub for Java scripts, developer resources and other goodies that programmers might want access to. Writing the code needed to access Oracle is often prone to accidental mistakes due to its length and complexity. However, the code is stable and fixed in place, meaning that there is no need to write it again every time you want to add it:

public class OracleJdbcTest
{
String driverClass = "oracle.jdbc.driver.OracleDriver";

Connection con;

public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException
{
Properties props = new Properties();
props.load(fs);
String url = props.getProperty("db.url");
String userName = props.getProperty("db.user");
String password = props.getProperty("db.password");
Class.forName(driverClass);

con=DriverManager.getConnection(url, userName, password);
}

public void fetch() throws SQLException, IOException
{
PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");
ResultSet rs = ps.executeQuery();

while (rs.next())
{
// do the thing you do
}
rs.close();
ps.close();
}

public static void main(String[] args)
{
OracleJdbcTest test = new OracleJdbcTest();
test.init();
test.fetch();
}
}

3. Converting to SQL


SQL databases often require specific file formats in order to register correctly. Java scripts written in util.date need to be converted before they can be used effectively. As it turns out, a simple two-line code can help you convert to SQL fairly easily:

java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

4. Generating PDF


PDF generation is something of an odd-ball when it comes to Java implementation. Developers are required to manually write the code needed to allow for PDF generation of content available on the source site. This can be useful if you are using a writing service to edit and format your content before publishing it again. The code necessary to allow for PDF generation is as follows:

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class GeneratePDF {

    public static void main(String[] args) {
        try {
            OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));

            Document document = new Document();
            PdfWriter.getInstance(document, file);
            document.open();
            document.add(new Paragraph("Hello Kiran"));
            document.add(new Paragraph(new Date().toString()));

            document.close();
            file.close();

        } catch (Exception e) {

            e.printStackTrace();
        }
    }
}

5. Setting up HTTP Proxy


An HTTP proxy can be useful for websites that expect international traffic and want to pass all the checks presented by Google’s SERP. While it’s not difficult to add a proxy to Java code, the process is time consuming and repetitive since most websites need it. Java developers can use the following code snippet to set up a proxy through HTTP without much effort:

System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
System.getProperties().put("http.proxyUser", "someUserName");
System.getProperties().put("http.proxyPassword", "somePassword");

6. Screenshots in Java


Screenshots are a widely sought-after feature in Java-based programs, websites, and applications. When it comes to their implementation, developers are often left scratching their heads with confusion about the coding process. The reason for this is because Java screenshots need to be added in levels, between existing lines of code. Let’s take a look at how the process looks like in practice:

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;

...

public void captureScreen(String fileName) throws Exception {

   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
   Rectangle screenRectangle = new Rectangle(screenSize);
   Robot robot = new Robot();
   BufferedImage image = robot.createScreenCapture(screenRectangle);
   ImageIO.write(image, "png", new File(fileName));

}
...

7. Emailing via Java


Emails are often sent through their respective dedicated platforms such as Gmail. However, people sometimes like to add email functionality to their company applications and websites and ask developers to do so for them. The process of adding email functionality is fixed and doesn’t require much in terms of customization. This brings us to the code snippet itself:

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public void postMail( String recipients[ ], String subject, String message, String from) throws MessagingException
{
    boolean debug = false;

     //Set the host smtp address
     Properties props = new Properties();
     props.put("mail.smtp.host", "smtp.example.com");

    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++)
    {
        addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);
 

    // Optional : You can also set your custom headers in the Email if you Want
    msg.addHeader("MyHeaderName", "myHeaderValue");

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);
}
[/code]

8. Directory listing


Listing directories is something that most administrators and developers like to do. It’s often useful to get the raw data in regards to site content instead of going through everything manually. Luckily, there is a way to streamline both the coding process and the listing itself:

public static void main(String[]args)
    {
        File curDir = new File(".");
        getAllFiles(curDir);
    }
    private static void getAllFiles(File curDir) {

        File[] filesList = curDir.listFiles();
        for(File f : filesList){
            if(f.isDirectory())
                getAllFiles(f);
            if(f.isFile()){
                System.out.println(f.getName());
            }
        }

    }

9. Image thumbnail


Application development and web design often require image optimization. Java developers can easily convert high-quality images into usable thumbnails with a few extra lines of code. Fiddling with the custom values will give the developers more or less optimized images depending on their requirements:

private BufferedImage scale(BufferedImage source,double ratio) {
  int w = (int) (source.getWidth() * ratio);
  int h = (int) (source.getHeight() * ratio);
  BufferedImage bi = getCompatibleImage(w, h);
  Graphics2D g2d = bi.createGraphics();
  double xScale = (double) w / source.getWidth();
  double yScale = (double) h / source.getHeight();
  AffineTransform at = AffineTransform.getScaleInstance(xScale,yScale);
  g2d.drawRenderedImage(source, at);
  g2d.dispose();
  return bi;
}

private BufferedImage getCompatibleImage(int w, int h) {
  GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
  GraphicsDevice gd = ge.getDefaultScreenDevice();
  GraphicsConfiguration gc = gd.getDefaultConfiguration();
  BufferedImage image = gc.createCompatibleImage(w, h);
  return image;
}

10. Compression and ZIP files


Lastly, one of the more useful code snippets allows Java developers the ability to compress data. ZIP files are often used to transfer and distribute sizeable data through the internet. A few short code strings give Java developers more freedom than a traditional compression program would:

StringBuilder sb = new StringBuilder();
sb.append(“Test String”);

File f = new File(“d:\\test.zip”);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f));
ZipEntry e = new ZipEntry(“mytext.txt”);
out.putNextEntry€;

byte[] data = sb.toString().getBytes();
out.write(data, 0, data.length);
out.closeEntry();

out.close();

In Summation


It’s always a good idea to keep a file with all the useful Java code snippets handy. Copying these lines of code is far easier and simpler than writing them from scratch. You will not only save a lot of time and energy in doing so but give yourself the ability to experiment and tinker with existing code. Don’t be afraid to experiment with pre-existing lines of code in order to innovate and pleasantly surprise your clients.

Author’s Bio:


Alaine Gordon is a young and talented content manager. She has been writing professionally since 2010 about almost everything, from psychology and to finance. Alaine Gordon graduated from the University of Colorado with B.A. in Journalism, 2011. She is an open-minded, creative person who loves to make people smile. Her credo is ‘Life is a fun enterprise’. In her free time, she loves traveling, reading science fiction and knitting. Her huge dream is to visit every single country in the world.

Website Facebook Twitter
Read More »

7/05/2018

Conditional Statements Tutorials in JavaScript (IF ELSE SWITCH)

Conditional Statements in JavaScript are a block of code will be executed if the condition is true. If you are familiar with C, C++, and Java or any other programming language. A conditional statements real-life example is "IF bulb is on means power supply on ELSE IF bulb is off meant switch is off or no electricity ELSE any other issue", with the example of the bulb, switch, and electricity we can understand a Conditional Statements in JavaScript. In this tutorial, we are going to learn following Conditional Statements in JavaScript.


Conditional Statements: JavaScript tutorials.


  1. Types of conditional statements in JavaScript
  • If
  • If...Else
  • Else...If
  • Switch
  1. Diagram of conditional statements in JavaScript
  2. The syntax of conditional statements in JavaScript
  3. Examples of conditional statements in JavaScript
  4. How its work

Conditional Statements in JavaScript:


1) If
2) If...Else
3) Else...If
4) Switch


If: Conditional Statements
   
if a condition is true only when a block of code will be executed. If you are familiar with C and C++, here also if condition works same.

Syntax

if (condition is true)
{
    //a block of code or Conditional Statements in JavaScript
}

Example:

<!DOCTYPE html>
<html>
<body>
<p id="ifCondition"></p>
<script>
var i=17;
if (i < 18)
{
document.getElementById("ifCondition").innerHTML =
"Hello JavaScript!";
}

</script>
</body>
</html>


If…Else: Conditional Statements

else if statement is used to handle where something will happen on both true or false conditions. Exactly as c or c++.

If Else Conditional Statements in JavaScript Picture simple example

Syntax

if (condition1==true) {
    //a block of code will be executed for a condition or Conditional Statements in JavaScript
}
 else {
    //a block of code will be executed if false or Conditional Statements in JavaScript
}

Example:

<!DOCTYPE html>
<html>
<body>
<p id="ifelseCondition"></p>
<script>
var i=19;
if (i < 18)
{
document.getElementById("ifelseCondition").innerHTML =
"Hello JavaScript inside if Condition!";
}
else
{
document.getElementById("ifCondition").innerHTML =
"Hello JavaScript inside else Condition!";
}

</script>
</body>
</html>


If...Else…If: Conditional Statements

If there are several conditions according to which there will be some decision that code block of JavaScript will be executed is work with if else if conditional statements.

if (condition1) {
    //conndition1 is true
   //JS block of code will be executed  or Conditional Statements in JavaScript
} else if (condition2) {
     //Condition2 is true
    //JS block of code will be executed or Conditional Statements in JavaScript
}
else {
  //JS  block of code will be executed or Conditional Statements in JavaScript
    }

Example:

<!DOCTYPE html>
<html>
<body>
<p id="elseifCondition"></p>
<script>
var i=19;
if (i < 18)
{
document.getElementById("elseifCondition").innerHTML =
"Hello JavaScript inside if Condition!";
}
else if(i>18 && i<28)
{
document.getElementById("elseifCondition").innerHTML =
"Hello JavaScript inside else if Condition!";
}
else
{
document.getElementById("elseifCondition").innerHTML =
"Hello JavaScript inside else Condition!";
}

</script>
</body>
</html>


Switch: Conditional Statements

The switch statement is used one code blocks to be executed among many.

How It Works:

Firstly the expression of the switch statement is evaluated once and then the value is matched with one of the switch cases and the corresponding code block is executed.

If no case is matched with the value of the expression the default condition is executed at the end.

If no default statement is there, continues to execute the statements after Switch.


switch(exp) {
    case 1:
        //code block or Conditional Statements in JavaScript
        break;
    case 2:
        //code block or Conditional Statements in JavaScript
        break;
    default:
        //code block or Conditional Statements in JavaScript
}


Example:

<!DOCTYPE html>
<html>
<body>
 <script type="text/javascript">
       
            var grade='A';
            switch (grade)
            {
               case 'A':
               document.write("Excellent Student");
                break;
               case 'B': document.write("Medium");
               break;
               case 'C': document.write("Fail");
                break;
               default: document.write("Don’t Know")
               break;
            }
</script>
</body>
</html>

Also, you can write a common code for multiple cases, If they produce the same result.

That is Like:

<!DOCTYPE html>
<html>
<body>
 <script type="text/javascript">
       
            var grade='B';
            switch (grade)
            {
               case 'A':
               case 'B':
               document.write("Excellent Student");
                break;
               case 'C': document.write("Medium");
               break;
               case 'D': document.write("Fail");
                break;
               default: document.write("Don’t Know")
               break;
            }
</script>
</body>
</html>

Last Words


If you have any doubt and need any help feel free to contact us or you can comment below, we are responsible to reply within 24 hours and you can like our Facebook page or Facebook groups for any personal assistant. We are committed to helping student first so don't hesitate to ask any doubts and query. Join us and become the part of our organization.

Please share this article to help a newbie student or programmers.

Author Bio: 


Conditional Statements in JavaScript Tutorials is provided by Suman Yadav. Thanks, Suman for the Awesome and Unique article. If you want to submit your article and want to be a member of our ProgrammingWithBasics Family Join us by sending a well-written article more information read Write for Us
Read More »

7/04/2018

Statement Execution in JavaScript

Statement Execution in JavaScript. Let’s now study about JavaScript Statement execution. Statements are Instruction in a computer program and instruction execute by computer. In this tutorials, we also talk about the  JavaScript Statement execution these instruction called statements which are written in programming language IE. C, C++(C Plus Plus or CPP), and Java, Javascript, and any other programming language. A JavaScript program is a list of Instruction or programming statements, many Instruction or programming statements. Many exist in single javascript program.

We all know that for executing this javascript instruction we have different-different IDE(Integrated Development Environment) or editor or compiler but in javascript, these instruction or statement are executed by the web browsers ie. Google Chrome, Mozilla Firefox, Safari, Internet Explorer. Google Chrome is most recommended nowadays. Most JavaScript programs contain many JavaScript statements or instructions and these statements or instructions are executed, one by one, in the same order as they are written. Javascript statements(are often called JavaScript code) or instructions are very simple cause they follow a similar rule as a programming language follow.

JavaScript Statement execution explain

1) When Browser is trying to execute the JavaScript code, then browser understands that every statement is a command.

<!DOCTYPE html>
<html>
<body>
<p>JavaScript statements<p>
<p id="new"></p>
<script>
document.getElementById("new").innerHTML = " every statement is a command ";
</script></body>
</html>

2) Many statements are allowed in one line and statements are separated by a semicolon.

<!DOCTYPE html>
<html>
<body>
<p>Many statements </p>
<p id="MultistatementDemo"></p>
<script>
var i, j, k;
i = 5; j = 9; k = i + j;
document.getElementById("MultistatementDemo").innerHTML = k;
</script>
</body>
</html>

3) Javascript statements are always executed in sequence, means line by line rule followed by the browser when javascript statements run.

<!DOCTYPE html>
<html>
<body>
 <b>Sequence Execution of Statements</p>
<p id="abc"></p>
<script>
var a, b, c;  // Statement 1
a = 1;        // Statement 2
b = 2;        // Statement 3
c = a + b;    // Statement 4

document.getElementById("abc").innerHTML ="Here c is " + c + ".";
</script>
</body>
</html>

4) If javascript code statement is going long, you can break it in multiple lines, It is treated as a single line in JavaScript, But to make the code readable the best practice is to break the line after a comma or after some operator.

Recommendation: Always try to break a long code in lines, its easy to handle and it can save a lot of time, cause mouse doesn't have any verticle scroll option.

<!DOCTYPE html>
<html>
<body>
<p id="place"></p><script>
document.getElementById("place").innerHTML =
"Hello JavaScript!";

//this will also works
//document.getElementById("place").
//innerHTML =
//"Hello JavaScript!";

</script>
</body>
</html>

Last Words


If you have any doubt and need any help feel free to contact us or you can comment below, we are responsible to reply within 24 hours and you can like our Facebook page or Facebook group for any personal assistant. We are committed to helping student first so don't hesitate to ask any doubts and query. Join us and become the part of our organization.

Please share this article to help a newbie student or programmers.

Author Bio:


JavaScript Statement execution in JavaScript Tutorials is provided by Suman Yadav. Thanks, Suman for the Awesome and Unique article. If you want to submit your article and want to be a member of our ProgrammingWithBasics Family Join us by sending a well-written article more information read Write for Us
Read More »