Sunday, May 17, 2009

Tutorial 3 - Control Flow

NOTE : -  THIS IS NOT THE ORIGINAL CONTENT

Tutorial 3 - Control Flow

This tutorial on basic Java control flow assumes some introductory programming experience in another language.

Conditional Statements

Conditional statements execute a block or set of other statements only if certain conditions are met. The condition is always enclosed in round brackets. The statements to be performed if the condition is true are enclosed in curly brackets. For example:

if (value > 5) {x=7;}

Note: If the block (ie. curly brackets) contains only one statement, you may leave the brackets off. But this is not good programming practice. The curly brackets make the code more consistent and easier to read.

Occasionally you may want to perform some actions for the false outcome of a condition as well. The else keyword is used to separate branches.

if (name == "Fred") {x=4;}   else {x=20;};

Note: When the conditional if statement is used only to make an assignment to one variable, you can use the terse Cconditional operator. A simple example is:

x=(name == "Fred") ? 4 : 20;

Loops

For statements allow a set of statements to be repeated or looped through a fixed number of times. The round bracket contains initializer(s) ; conditional test ; incrementer(s). If more than one initializer or incrementer is used they are separated with commas. The test condition is checked prior to executing the block. The incrementing is doneafter executing the block. For example to output #1 #2 etc.(or #5 #4 etc.) on separate rows you could write:

for (int i=1;i<=5;i++) {document.writeln("#"+i);}; for (int i=5;i>=1;i--) {document.writeln("#"+i);};

Note: A special case of the for loop is the infinite loop for (;;){...}. This could be used with appropriate 'breakout' logic where a continuous operation was needed.

Caution: For loops can be written in ways that violate structured programming principles by allowing counter variables to be used outside of the scope of the loop block if they are defined outside the loop. Avoid the looseness of the language by always localizing the loop variable.

The enhanced for statement allows iteration over a full set of items or objects. For example:

int[] squares={0,1,4,9,16,25}; for (int square : squares) {...;} // is equivalent to for (int 1;i

While statements allow a set of statements to be repeated or looped until a certain condition is met. The test condition is checked prior to executing the block. For example to output #1 #2 etc. on separate rows you could write:

int i=0; while (i<=5) {    document.writeln("#"+i); i++;    };

Do While statements allow a set of statements to be repeated or looped until a certain condition is met. The test condition is checked after executing the block. For example to output #1 #2 etc. on separate rows you could write:

int i=1; do {    document.writeln("#"+i); i++;    } while (i<=5);

The Switch Statement

Switch (or case) statements are used to select which statements are to be executed depending on a variable's value matching a label. default is used for the else situation. Note that the selection variable can only be int or chardatatype.

switch (selection)    {    case '1': System.out.println("You typed a 1"); break;    case '2': System.out.println("You typed a 2"); break;    default : System.out.println("Oops!, that was an invalid entry.");    };

Continue, Break and Return

Continue statements are used in looping statements to force another iteration of the loop before reaching the end of the current one. Most often continue is used as part of a conditional statement that only happens in certain cases. The following is a trivial example.

int x=0; while (x <>

Break statements are used in looping and 'switch' statements to force an abrupt termination or exit from the loop or switch. In the following example the loop is never completed. Once again the normal use of break is as part of a conditional statement.

int x=0; while (x <>

Return statements are used to force a quick exit from a method. They are also used to pass values back from methods.

Command Line Arguments

Command line arguments are accessible through the args[] array (assuming that args is the name used in the specification for main [Note: args[] is a Java coding convention!]). The array does not include the interpreter javacommand or the class name and the count starts at 0. Each argument is passed as a string but may be converted as in the following:

int w=Integer.parseInt(args[0]); // or sometimes you want the argument to be a character type char s=args[1].charAt(0); // uses first letter of argument only

Note: The methods parseInt() and charAt() are referenced in the type wrappers and string class topics.

Warning: Double quote marks are consumed by the command line parser and are not passed on to the args[] array!

The number of arguments passed in from the command line can be determined by using the args.length property. This is important when testing for required arguments, when there is a variable number of arguments or when there is an unpredictable number of arguments (eg. the file glob expansions (* and ?) in batch operation).

Command line options are arguments with a prefix of - (dash) and is UNIX-centric. They normally precede pathnames in the command line. Options are normally a single character but sometimes are a number or followed by a number. Examples of command line options are:

pr -d *.htm  ; print double spacing lines head -10 *.htm ; show first 10 lines head -c 10 *.htm ; show first 10 characters

Command line switches are arguments with a prefix of / (slash) and is msDOS-centric. They normally toggle boolean flags but can be found in many variations such as a following argument qualifier or a parsing situation. Depending on programmer, they may have to precede or follow file arguments.Examples are:

find /p fred *.htm  ;page pause requested progname /help ;help or man page requested format /head=4. *.htm ;include 4 lines of header space print -lines 45 *.htm ;print first 45 lines of file(s)

Note: I personally prefer switches to options but YMMV! Try to develop a standard argument option|switch handling routine that is as user tolerant as possible regarding switches and filenames. The routine should identify switches by the prefix / and act appropriately. Routines that are accessing filenames from the args[] array should skip switches (as identified with the / prefix). You may want to view the one used in include.java.

Project: Basic Problems

This project is a series of simple problems that use arraysloopscommand line arguments for input and a simpleSystem.out.println(string); statement for output.

Problem 1: Write a program that allows you to create an integer array of 18 elements with the following values:int A[]={3,2,4,5,6,4,5,7,3,2,3,4,7,1,2,0,0,0}. The program computes the sum of element 0 to 14 and stores it at element 15, computes the average and stores it at element 16 and identifies the smallest value from the array and stores it at element 17.

Problem 2: Write a program that accepts two numbers from the command line and prints them out. Then use a for loop to print the next 13 numbers in the sequence where each number is the sum of the previous two. For example:

input> java prob2 1 3 output> 1 3 4 7 11 18 29 47 76 123 322 521 843 1364

Problem 3: Write a program that accepts two numbers in the range 1 to 40 from the command line. It then compares these numbers against a single dimension array of five integer elements ranging in value from 1 to 40. The program displays the message BINGO if the two inputted values are found in the array element. For example:

input>java prob3 3 29 output>Your first number was 3        Your second number was 29        Its Bingo! // this message if 3 and 29 is found in the array        Bokya!     // this message if 3 and 29 is not found in the array        The array was 7 25 5 19 30

An extension for problem 3 would be to generate the array of five unique integers using random numbers

Problem 4: Create a program using loops to form this figure:

         n=3                n=4           *                  *          *$*                *$*         *$*$*              *$*$*          *$*              *$*$*$*           *                *$*$*                             *$*                              *
 

Project: Metric Converter

This project tests your knowledge of syntax without getting too involved in the complexities of object manipulation or a user interface. A toy metric converter should be just about right as it allows three basic stages of application development; IPO, branching, and switch selection.

The First Stage [Input - Process - Output]

The goal of the first stage of this project is to input from the command line a temperature given in degrees Fahrenheit (a geezer's unit), calculate the value in Celsius (the modern way) and then display the answer. This will test your ability to get some input, do a math process and finally display the output. It also gives some practice working with the development environment and doing compilations.

The basic input procedure will be to get the Fahrenheit reading from the command line using the methodInteger.parseInt(args[0]) which returns an integer from the first argument on the command line.

The math processing part is really easy. Celsius, a scientist, used water as his gauge so freezing was 0 and boiling was 100. Fahrenheit, an engineer used a more commonly available liquid, alcohol for his range :-). As alcohol freezes at lower temperatures, that is why the 32° difference. Because of the difference in range from freezing to boiling of the two liquids the ratio of size of the units turns out to be 100 to 180 or 5 to 9. This is the basic principle for the formuladeg_C=((deg_F-32) * 5)/9. Since division may produce a real number with a decimal value, you should cast the input number into a double and work with double precision floating point numbers (aka real numbers). Caution: Be sure to rewrite the formula with decimal numbers!

Once the answer is calculated, it can be output to your display by using the method System.out.println(deg_C)

Note: This program must be run from the command line with an integer following the program name. No error checking has been done yet!

Second Stage [Branching]

The second stage is to modify the application so that the conversion can be made in either direction. This will require a logical branch based on some additional input. Let's say the input has to look like 40 F or 10 C

    char units=args[1].charAt(0);     units=Character.toUpperCase(units);     if (units == 'F')     {     //do F --> C conversion     }     else     {     //do C --> F conversion     }

Also the command line should be checked to make sure that the number of arguments is correct (which we failed to do in stage one). A simple error message can be printed after checking the count such as:

    if (args.length != 2)     {       System.out.println ("Usage: Metric_2 ## F|C");       return;     }

Third Stage [Switches]

The third stage is to use the units argument to select an appropriate conversion routine (temperature, mass, distance, etc.) and switch to routines accordingly. For our program just add routines to convert lbs to kilograms and kg to lbs. This stage maxes out the limits of programming in the small. In later tutorials you will learn how to use custom objects to encapsulate data and procedures as well as how to use GUI objects to allow for interactive input.

switch (units) {   case 'F': { /* conversion routine */ } ; break;   case 'C': { /* conversion routine */ } ; break;   case 'L': { /* conversion routine */ } ; break;   case 'K': { /* conversion routine */ } ; break;   default : System.out.println("Oops! I do not understand the units..."); }

BIBLIOGRAPHY / REFERENCE : -

FOR REFERENCE....PLEASE VISIT :


P.S. : THIS CONTENT IS TAKEN FROM THE ABOVE MENTIONED SITE

Saturday, May 16, 2009

Tutorial 2 - Syntax & Grammar

NOTE : -  THIS IS NOT THE ORIGINAL CONTENT

Tutorial 2 - Syntax & Grammar

Java like many languages (eg. C, JavaScript, awk, perl) is based on a common syntax and grammar developed by the Bell Labs in the 60's. This makes it easy to cross over from one language to another based on program requirements, resources and politics. This tutorial on basic Java syntax and grammar (ie. programming in the small) assumes some introductory programming experience in another language.

Lexical Structure

The lexical structure of a programming language is the set of elementary rules that define what are the tokens or basic atoms of the program. It is the lowest level syntax of a language and specifies what is punctuation, reserved words, identifiers, constants and operators. Some of the basic rules for Java are:

  • Java is case sensitive.
  • Whitespace, tabs, and newline characters are ignored except when part of string constants. They can be added as needed for readability.
  • Single line comments begin with //
  • Multiline comments begin with /* and end with */
  • Documentary comments begin with /** and end with **/
  • Statements terminate in semicolons! Make sure to always terminate statements with a semicolon.
  • Commas are used to separate words in a list
  • Round brackets are used for operator precedence and argument lists.
  • Square brackets are used for arrays and square bracket notation.
  • Curly or brace brackets are used for blocks.
  • Keywords are reserved words that have special meanings within the language syntax.
  • Identifiers are names for constants, variables, functions, properties, methods and objects. The first charactermust be a letter, underscore or dollar sign. Following characters can also include digits. Letters are A to Z, a to z, and Unicode characters above hex 00C0. Java styling uses initial capital letter on object identifiers, uppercase for constant ids and lowercase for property, method and variable ids.
    Note: an identifier must NOT be any word on the Java Reserved Word List.

Data Types

Java is a strongly-typed language. Its primitive data types are:

TypeBitsRange
boolean1true, false
char160 to 65,535
byte8-128 to +127
short16-32,768 to +32,767
int32-232 to +232-1
long64-264 to +264-1
float32-3.4E+38 to +3.4E+38 (approx)
double64-1.8E+308 to +1.8E+308 (approx)

Literal Constants

Literal constants are values that do not change within a program. Numeric constants default to integer or double unless a suffix is appended. Note that a character can be represented by an ASCII equivalent. The literal types are:

  • Boolean: true, false
  • Character: 'c', '\f'
  • String: "Fred", "B and E"
  • Null: null
  • Integer: 5, 0xFF (hexadecimal)
         073 [leading zero] (octal), 5l (long), 0xFFlD (hex)
  • Floating Point: 2.543, -4.1E-6 (double)
         2.543f, 8e12f (float)

Note: Do not use leading zeros to format integers as this can cause an unintended octal meaning. Use spaces instead!

Escape (aka backslash) characters are used inside literal strings to allow print formatting as well as preventing certain characters from causing interpretation errors. Each escape character starts with a backslash. The available character sequences are:

SeqNameSeqName
\bbackspace\fformfeed
\thorizontal tab\"double quote
\nnewline\'single quote
\rcarriage return\\backslash
\###Latin encoded character\uHHHHUnicode encoded character

Variables

Variables are temporary data holders. Variable names are identifiers. Variables are declared with a datatype. Java is a strongly typed language as the variable can only take a value that matches its declared type. This enforces good programming practice and reduces errors considerably. When variables are declared they may or may not be assigned or take on a value (initialized). Examples of each of the primitive datatypes available in Java are as follows:

byte x,y,z;             /* 08bits long, not assigned, multiple declaration */ short numberOfChildren; /* 16bits long */ int counter;            /* 32bits long */ long WorldPopulation;   /* 64bits long */  float pi;               /* 32bit single precision */ double avagadroNumber;  /* 64bit double precision */ boolean signal_flag;    /* true or false only */ char c;                 /* 16bit single Unicode character */

Variables can be made constant or read only by prepending the modifier final to the declaration. Java convention uses all uppercase for final variable names.

Arrays

Arrays allow you to store several related values in the same variable (eg. a set of marks). Declaration of an array only forms a prototype or specification for the array. Multi-dimensional arrays are considered to be arrays of arrays (of arrays...). Note that in a declaration the brackets are left blank.

int i[];        /* one dimension array */ char c[][];     /* two dimension array */ float [] f;     /* geek speak way */ Bowl shelfA[];  /* array of objects */

Array memory allocation is assigned explicitly with the new operator and requires known static bounds (ie. number of elements). The number of items in an array can then be determined by accessing its length property. For a two dimensional array named mm.length gives the number of elements in its first dimension and m[0].length gives the number of elements in its second dimension.

Array1 = new int[5]; //previously declared, now created int markArray[] = new int[9]; //declaration and allocation at same time int grades[] = new int[maxMarks]; //maxMarks must be a positive integer

Array initialization can take place at declaration. Size of the array is determined by the contents.

String flintstones[] = {"Fred", "Wilma", "Pebbles"}; //init values String pairs[][] = {  {"Adam","Eve"},{"Lucy","Ricky"},{"Fred","Ethel"},{"Bert","Ernie"}};

Operators and Expressions

Operators are actions that manipulate, combine or compare variables. They fall into several categories as follows:

Assignment:           = += -= *= \= %= Arithmetic:           + - * / % (modulus) ++ (increment) -- (decrement) String Concatenation: + Comparison:           == != > >= < <= Boolean Comparison:   ! & | ^ && || (&& are short circuit ops) Bitwise Comparison:   ~ & | ^ (xor) << >> >>> Bitwise Assignment:   &= |= ^= (xor) <<= >>= >>>= Conditional:          ? (eg (expr1) ? expr2 : expr3 ) Object Creation:      new (eg int a[] = new int[10];) Class of Object:      instanceof Casting of Type:      (var_type)

Note: Changes in data type are done explicitly using a cast operation. For example a = (int) b; assumes a is of type int and b is of another type.

Expressions are phrases used to combine values and/or operands using operators to create a new value. One example of an expression is 5 + 3.

Conditions, Statements and Blocks

Conditions are phrases that can be evaluated to a boolean value such as a comparison operator between two constants, variables or expressions used to test a dynamic situation. Examples are x <= 5 and bool_flag != true.

Statements are complete program instructions made from constants, variables, expressions and conditions. Statements always end with a semicolon. A program contains one or more statements.

Assignment statements use an assignment operator to store a value or the result of an expression in a variable. Memory allocation is done at the time of assignment. Primitive datatypes have static allocation with size determined by their type. Simple examples include first_name = "Fred"; and count +=;

Variables may be assigned an initial value when declared. This is considered good programming practice. Examples are boolean fileOpenFlag = true;int finalScore = null; and final float PI = 3.14159;

Array variables can use a shortcut method of initial value assignment. Examples are:

int v[] = {2,4,20}; //declaration/creation/assignment in one step! int m[][] = {{2,3,4}, {4,5,6}, {1,1,1}}; // two dimensional array

Local variables must be assigned a value prior to use. There is no default assumption. Failure to initialize will cause a compiler error! Field variables (aka properties) have defaults but initialization is good programming practice.

Execution blocks are sets or lists of statements enclosed in curly brackets. Variables maintain their definition (or 'scope') until the end of the execution block that they are defined in. This is the reason why variable declarationand assignment can be a two step process.

Note: It is a good rule of thumb to declare variables in as nested a scope as possible to limit the chance of spurious assignment.

Beware: A variable's content can be hidden by redeclaration of its name within a nested execution block. At times this is convenient but beginning programmers should avoid reuse (ie. 'overload') of variable names.



BIBLIOGRAPHY / REFERENCE : -

FOR REFERENCE....PLEASE VISIT :


P.S. : THIS CONTENT IS TAKEN FROM THE ABOVE MENTIONED SITE