Search This Blog

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Flow Control and Looping Statements in java, javsscript, c#

 Flow control statements determine the next statement to execute. In this sense, the statements if-else, if, switch, while, for are flow control statements.
Conditional Statements:
    Conditional statements control whether a part of a script is executed depending the result of a particular expression (i.e. whether an expression returns a boolean true or false value). The two types of conditional structures are if and if ... else. In this section we will take a closer look at both of these conditional structures and provide some examples of their use.
Syntax:
if (condition)
{
   ...
} else if (condition1)
{
   ...
} else
{
   ...
}

Example: ( in javascript )
if (customerName == "Fred")
{
      document.write ("Hello Fred!");
} 
else if (customerName == "John")
{
      document.write ("Hello John!");
} 
else
{
      document.write ("You're not Fred! Where's Fred?");
}

Looping Statements:
1. for loops
Syntax:
for ( ''initializer''; ''conditional expression''; ''loop expression'' )
{
      statements to be executed
}

The initializer typically initializes a counter variable. Traditionally the variable i is used for this purpose. For example:
i = 0

This sets the counter to be the value i and sets it to zero.

The conditional expression specifies the test to perform to verify whether the loop has been performed the required number of times. For example, if we want to loop 100 times:

i < 100

Finally the loop expression specifies the action to perform on the counter variable. For example to increment by 1:

i++

Bringing this all together we can create a for loop to perform the task outlined in the earlier example:

var j = 10;

for (i=0; i<10; i++)
{
      j += j;
}

2. while loops: The for loop described above works well when you know how many times a particular task needs to be repeated. Clearly there will often be instances where something needs to be repeated until a certain condition is met, with no way of knowing how many repetitions are going to be needed to meet those criteria. To address this need JavaScript provides the while loop. In essence the while loop repeats a set of tasks until a specified condition is met.
Syntax:
while (''condition'')
{
      ''Statements''
}

    In that above syntax outline, condition is an expression that will return either true or false and JavaScript Statements represents the JavaScript to be executed while the expression is true. For example:

while ( i < 10 )
{
      i = i + j;
}

    In the above example, the while expression will evaluate whether i is less than 10. If it is already greater than 10 then the code in the braces is skipped and the loop exits without performing any tasks. If it is not greater than 10 the code in the braces is executed and the loop returns to the while statement and repeats the evaluation of i. This process repeats until i is greater than 10, at which point the loop exits

switch Statements: when a need arises to evaluate a large number of conditions. An easier way to handle such situations is to use the switch statement.
Syntax:
switch (''value'')
{
     case "''match1''" :
     ''statements''
     break;

     case "''match2''" :
     ''statements''
     break;

     case "''match3''" :
     ''statements''
     break;

     case "''match4''" :
     ''statements''
     break;

     case "''match5''" :
     ''statements''
     break;

     default :
     ''statements''
     break;
}
    There can be any number of case statements - basically as many as you need to fully compare the value in the switch statement against the possible options (represented by match1 through to match5 in the above example) specified by the case statements. When a match is found the statements corresponding to the matching case are executed. Note the break; statement. Without the break all the cases after the matching case will also be executed.

    The default statement specifies the action that should be taken if no match is found. The following provides an example of the switch statement in action:

Example: (in javascript)
var carModel = "Focus";

switch (carModel)
{
     case "Durango" :
     document.write ("Manufactured by Dodge");
     break;

     case "Camry" :
     document.write ("Manufactured by Toyota");
     break;

     case "Focus" :
     document.write ("Manufactured by Ford");
     break;

     case "320i" :
     document.write ("Manufactured by BMW");
     break;

     case "Civic" :
     document.write ("Manufactured by Honda");
     break;

     default  :
     document.write ("Unknown Car Model");
     break;
}

Breaking a Loop: Occasionally it is necessary to exit from a loop before it has met whatever completion criteria were specified. To achieve this, the break statement must be used. The following example contains a loop that uses the break statement to exit from the loop when i = 100, even though the loop is designed to iterate 1000 times:

for (i = 0; i < 1000; i++)
{
        if (i == 10) 
        {
             break;
        }
}

Skipping Statements in Current Loop Iteration: The break statement, when encountered in a loop breaks skips all remaining statements in the loop body and breaks the loop. The continue statement also skips all remaining statements in the loop for the current iteration, but returns to the top of the loop and allows it to continue running.
Share:

Declaring a constant in Java

 Java does not directly support constants. However, a static final variable is effectively a constant.
    The static modifier causes the variable to be available without loading an instance of the class where it is defined. The final modifier causes the variable to be unchangeable.

    Ex: public static final int FOUNDING_YEAR = 2001;

    Naming Standards for Java Constants
    Although these aren’t syntactical rules, they are widely used as accepted conventions.

    Java constants are normally declared in ALL CAPS.
    Underscores normally separate Words in Java constants.
    Sample Java Constant Declaration
    public class MAX_UNITS {
     public static final int MAX_UNITS = 25;
    }
Share:

Declaring a variable in java

 A variable is a container that holds values that are used in a Java program. To be able to use a variable it needs to be declared. Declaring variables is normally the first thing that happens in any program.
How to Declare a Variable
    Java is a strongly typed programming language. This means that every variable must have a data type associated with it. For example, a variable could be declared to use one of the eight primitive data types: byte, short, int, long, float, double, char or boolean.

    A good analogy for a variable is to think of a bucket. We can fill it to a certain level, we can replace what's inside it, and sometimes we can add or take something away from it. When we declare a variable to use a data type it's like putting a label on the bucket that says what it can be filled with. Let's say the label for the bucket is "Sand". Once the label is attached, we can only ever add or remove sand from the bucket. Anytime we try and put anything else into it, we will get stopped by the bucket police. In Java, you can think of the compiler as the bucket police. It ensures that programmers declare and use variables properly.

    To declare a variable in Java, all that is needed is the data type followed by hte variable name:
    int numberOfDays; 
    In the above example, a variable called "numberOfDays" has been declared with a data type of int. Notice how the line ends with a semi-colon. The semi-colon tells the Java compiler that the declaration is complete.

    Now that it has been declared, numberOfDays can only ever hold values that match the definition of the data type (i.e., for an int data type the value can only be a whole number between -2,147,483,648 to 2,147,483,647).

    Declaring variables for other data types is exactly the same:

     byte nextInStream;
     short hour;
     long totalNumberOfStars;
     float reactionTime;
     double itemPrice;

Initializing Variables
    Before a variable can be used it must be given an initial value. This is called initializing the variable. If we try to use a variable without first giving it a value:
     int numberOfDays;
     //try and add 10 to the value of numberOfDays
      numberOfDays = numberOfDays + 10;

the compiler will throw an error:
 variable numberOfDays might not have been initialized
     To initialize a variable we use an assignment statement. An assignment statement follows the same pattern as an equation in mathematics (e.g., 2 + 2 = 4). There is a left side of the equation, a right side and an equals sign (i.e., "=") in the middle. To give a variable a value, the left side is the name of the variable and the right side is the value:
     int numberOfDays;
      numberOfDays = 7; 
    In the above example, numberOfDays has been declared with a data type of int and has been giving an initial value of 7. We can now add ten to the value of numberOfDays because it has been initialized:
     int numberOfDays;
     numberOfDays = 7;
     numberOfDays = numberOfDays + 10;
     System.out.println(numberOfDays); 
    Typically, the initializing of a variable is done at the same time as its declaration:
     //declare the variable and give it a value all in one statement
     int numberOfDays = 7; 

Choosing Variable Names
    The name given to a variable is known as an identifier. As the term suggests, the way the compiler knows which variables it's dealing with is through the variable's name.

There are certain rules for identifiers:
  - reserved words cannot be used.
  - they cannot start with a digit but digits can be used after the first character (e.g., name1, n2ame are valid).
  - they can start with a letter, an underscore (i.e., "_") or a dollar sign (i.e., "$").
  - you cannot use other symbols or spaces (e.g., "%","^","&","#").
    Always give your variables meaningful identifiers. If a variable holds the price of a book, then call it something like "bookPrice". If each variable has a name that makes it clear what it's being used for, it will make finding errors in your programs a lot easier.

    Finally, there are naming conventions in Java that we would encourage you to use. You may have noticed that all the examples we have given follow a certain pattern. When more than one word is used in combination in a variable name the words following the first one are given a capital letter (e.g., reactionTime, numberOfDays.) This is known as mixed case and is the preferred choice for variable identifiers.
Share:

Basic outline for learning a programming language:

 Basic outline for learning a programming language:
  - Requires about keywords when name variables, function
  - Operators
    + Mathematical operators: +, -, *, /, ++, --, \, %
    + Relational operators: ==, !=, >, <, >=, <=
    + Logical operators: &&, ||
    + Bitwise Operators: &, |
  - Data types; char, string, number ( byte, integer, long, float, double)
  - Declare and assign constant, variable, function, class
  - Control commands: if, for, while, switch, continue, break
Share:
Powered by Blogger.

Recent Posts

Pages