Sunday, 30 January 2011

C Language Keywords

C Language Keywords

Standard ANSI C recognizes the following keywords:
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
long
register
return
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while

In addition to these standard keywords, TIGCC recognizes some extended keywords which do not exist in ANSI C, like asm, typeof, inline, etc., which are described in details in the section GNU C language extensions. This section also describes extensions to standard keywords, not only new ones.

Note: If square brackets '[...]' are used in syntax descriptions, they mean optional arguments (as usual in syntax-describing languages), not square brackets as literals.

auto

Defines a local variable as having a local lifetime.
Keyword auto uses the following syntax:
[auto] data-definition;
As the local lifetime is the default for local variables, auto keyword is extremely rarely used.

Note: GNU C extends auto keyword to allow forward declaration of nested functions.

break

Passes control out of the compound statement.
The break statement causes control to pass to the statement following the innermost enclosing while, do, for, or switch statement. The syntax is simply
break;

const

Makes variable value or pointer parameter unmodifiable.
When const is used with a variable, it uses the following syntax:
const variable-name [ = value];
In this case, the const modifier allows you to assign an initial value to a variable that cannot later be changed by the program. For example,
const my_age = 32;
Any assignments to 'my_age' will result in a compiler error. However, such declaration is quite different than using
#define my_age 32
In the first case, the compiler allocates a memory for 'my_age' and stores the initial value 32 there, but it will not allow any later assignment to this variable. But, in the second case, all occurences of 'my_age' are simply replaced with 32 by the preprocessor, and no memory will be allocated for it.

Warning: a const variable can be indirectly modified by a pointer, as in the following example:
*(int*)&my_age = 35;
When the const modifier is used with a pointer parameter in a function's parameter list, it uses the following syntax:
function-name (const type *var-name)
Then, the function cannot modify the variable that the pointer points to. For example,
int printf (const char *format, ...);
Here the printf function is prevented from modifying the format string.

continue

Passes control to the begining of the loop.
continue causes control to pass to the end of the innermost enclosing while, do, or for statement, at which point the loop continuation condition is re-evaluated. The syntax is simply
continue;
For example,
for (i = 0; i < 20; i++)
  {
    if (array[i] == 0)
      continue;
    array[i] = 1/array[i];
  }
This example changes each element in the array with its reciprocal, but skips elements which are equal to zero.

do

Do-while loop.
Keyword do is usually used together with while to make another form of repeating statement. Such form of the loop uses the following syntax:
do statement while (expression)
statement, which is usually a compound statement, is executed repeatedly as long as the value of expression remains non-zero. The test takes place after each execution of the statement. For example,
i = 1; n = 1;
do
  {
    n *= i;
    i++;
  } while (i <= factorial);

enum

Defines a set of constants of type int.
The syntax for defining constants using enum is
enum [tag] {name [=value], ...};
The set can optionally be given a type tag name with tag. name is the name of a constant that can optionally be assigned the (constant) value of value, etc. For example,
enum Numbers {One = 1, Two = 2, Three = 3, Four = 4, Five = 5};
If value is missing, then a value is assumed to be the value of the previous constant in the list + 1. If this is the first constant in the list, the default value is 0.

If you give a type tag name, then you can declare variables of enumerated type using
enum tag variable-names;
For example,
enum Numbers x, y, z;
declares three variables x, y and z, all of type Numbers (they are, in fact, integer variables). More precise, 'enum tag' becomes a new type which is equal in rights with any built-in type.

extern

Indicates that an identifier is defined elsewhere.
Keyword extern indicates that the actual storage and initial value of a variable, or body of a function, is defined elsewhere, usually in a separate source code module. So, it may be applied to data definitions and function prototypes:
extern data-definition;
extern function-prototype;
For example,
extern int _fmode;
extern void Factorial (int n);
The keyword extern is optional (i.e. default) for a function prototype.

float, double

Floating point data types.
The keyword float usually represents a single precision floating point data type, and double represents a double precision floating point data type. In TIGCC, both float and double (and even long double) are the same. The TI-89 and TI-92 Plus use a non-IEEE floating point format called SMAP II BCD for floating point values.

These values have a range from 1e-999 to 9.999999999999999e999 in magnitude, with a precision of exactly 16 significant digits. Principally, the exponent range may be as high as 16383, but a lot of math routines do not accept exponents greater than 999.

for

For loop.
For-loop is yet another kind of loop. It uses for keyword, with the following syntax:
for ([expr1]; [expr2]; [expr3]) statement
statement is executed repeatedly until the value of expr2 is 0. Before the first iteration, expr1 is evaluated. This is usually used to initialize variables for the loop. After each iteration of the loop, expr3 is evaluated. This is usually used to increment a loop counter. In fact, the for-loop is absolutely equivalent to the following sequence of statements:
expr1;
while (expr2)
  {
    statement;
    expr3;
  }
That's why expr1 and expr3 must contain side effects, else they are useless. For example,
for (i=0; i<100; i++) sum += x[i];

for (i=0, t=string; i<40 && *t; i++, t++) putch(*t);
putch('\n');

for (i=0, sum=0, sumsq=0, i<100; i++)
  {
    sum += i; sumsq += i*i;
  }
All the expressions are optional. If expr2 is left out, it is assumed to be 1. statement may be a compound statement as well.

goto

Unconditionally transfer control.
goto may be used for transfering control from one place to another. The syntax is:
goto identifier;
Control is unconditionally transferred to the location of a local label specified by identifier. For example,
Again:
  ...
  goto Again;
Jumping out of scope (for example out of the body of the for loop) is legal, but jumping into a scope (for example from one function to another) is not allowed.

Note: The GNU C extends the usage of goto keyword to allow computed goto. Also, it supports local labels, useful in macro definitions.

if, else

Conditional statement.
Keyword if is used for conditional execution. The basic form of if uses the following syntax:
if (expression)
   statement1
Alternatively, if may be used together with else, using the following syntax:
if (expression)
   statement1
else
   statement2
If expression is nonzero when evaluated, then statement1 is executed. In the second case, statement2 is executed if the expression is 0.

An optional else can follow an if statement, but no statements can come between an if statement and an else. Of course, both statement1 and statement2 may be compound statements (i.e. a sequence of statements enclosed in braces). Here will be given some legal examples:
if (count < 50) count++;

if (x < y) z = x;
else z = y;

if (x < y)
  {
    printf ("x is smaller");
    return x;
  }
else
  {
    printf ("x is greater")
    return y;
  }
The #if and #else preprocessor statements look similar to the if and else statements, but have very different effects. They control which source file lines are compiled and which are ignored.

int, char

Basic data types (integer and character).
Variables of type int are one machine-type word in length. They can be signed (default) or unsigned, which means that in this configuration of the compiler they have by default a range of -32768 to 32767 and 0 to 65535 respectively, but this default may be changed if the compiler option '-mnoshort' is given. In this case, the range of type int is -2147483648 to 2147483647 for signed case, or 0 to 4294967295 for unsigned case. See also short and long type modifiers.

Variables of type char are 1 byte in length. They can be signed (this is the default, unless you use the compiler option '-funsigned-char') or unsigned, which means they have a range of -128 to 127 and 0 to 255, respectively.

All data types may be used for defining variables, specifying return types of functions, and specifying types of function arguments. For example,
int a, b, c;                       // 'a', 'b', 'c' are integer variables
int func ();                       // 'func' is a function returning int
char crypt (int key, char value);  // 'crypt' is a function returning char with
                                   // two args: 'key' is int and 'value' is char
When function return type is omitted, int is assumed.

All data type keywords may be used in combination with asterisks, brackets and parentheses, for making complex data types, like pointer types, array types, function types, or combinations of them, which in the C language may have an arbitrary level of complexity (see asterisk for more info).

register

Tells the compiler to store the variable being declared in a CPU register.
In standard C dialects, keyword auto uses the following syntax:
register data-definition;
The register type modifier tells the compiler to store the variable being declared in a CPU register (if possible), to optimize access. For example,
register int i;
Note that TIGCC will automatically store often used variables in CPU registers when the optimization is turned on, but the keyword register will force storing in registers even if the optimization is turned off. However, the request for storing data in registers may be denied, if the compiler concludes that there is not enough free registers for use at this place.

Note: The GNU C extends the usage of register keyword to allow explicitely choosing of used registers.

return

Exits the function.
return exits immediately from the currently executing function to the calling routine, optionally returning a value. The syntax is:
return [expression];
For example,
int sqr (int x)
{
  return (x*x);
}

short, long, signed, unsigned

Type modifiers.
A type modifier alters the meaning of the base type to yield a new type. Each of these type modifiers can be applied to the base type int. The modifiers signed and unsigned can be applied to the base type char. In addition, long can be applied to double.

When the base type is omitted from a declaration, int is assumed. For example,
long x;                 // 'int' is implied
unsigned char ch;
signed int i;           // 'signed' is default
unsigned long int l;    // 'int' is accepted, but not needed
In this implementation of the compiler, the valid range of valid data types is as listed in the following table:
short int              -32768 to 32767
long int               -2147483648 to 2147483647
signed char            -128 to 127
signed int             -32768 to 32767 (signed is default)
                       [or -2147483648 to 2147483647 if '-mnoshort' is given]
signed short int       -32768 to 32767
signed long int        -2147483648 to 2147483647
unsigned char          0 to 255
unsigned int           0 to 65535
                       [or 0 to 4294967295 if '-mnoshort' is given]
unsigned short int     0 to 65535
unsigned long int      0 to 4294967295
Note: GNU C extends the long keyword to allow double-long integers (64-bit integers in this implementation), so they have range from -9223372036854775808 to 9223372036854775807 if signed, or from 0 to 18446744073709551615 if unsigned.

sizeof

Returns the size of the expression or type.
Keyword sizeof is, in fact, an operator. It returns the size, in bytes, of the given expression or type (as type size_t). Its argument may be an expression of a type name:
sizeof expression
sizeof (type)
For example,
workspace = calloc (100, sizeof (int));
memset(buff, 0, sizeof buff);
nitems = sizeof (table) / sizeof (table[0]);
Note that type may be an anonymous type (see asterisk for more info about anonymous types).

static

Preserves variable value to survive after its scope ends.
Keyword static may be applied to both data and function definitions:
static data-definition;
static function-definition;
For example,
static int i = 10;
static void PrintCR (void) { putc ('\n'); }
static tells that a function or data element is only known within the scope of the current compile. In addition, if you use the static keyword with a variable that is local to a function, it allows the last value of the variable to be preserved between successive calls to that function.

Note that the initialization of automatic and static variables is quite different. Automatic variables (local variables are automatic by default, except you explicitely use static keyword) are initialized during the run-time, so the initialization will be executed whenever it is encountered in the program. Static (and global) variables are initialized during the compile-time, so the initial values will simply be embeded in the executable file itself. If you change them, they will retain changed in the file. By default, the C language proposes that all uninitialized static variables are initialized to zero, but due to some limitations in TIGCC linker, you need to initialize explicitely all static and global variables if you compile the program in "nostub" mode.

The fact that global and static variables are initialized in compile-time and kept in the executable file itself has one serious consequence, which is not present on "standard" computers like PC, Mac, etc. Namely, these computers always reload the executable on each start from an external memory device (disk), but this is not the case on TI. So, if you have the following global (or static) variable
int a = 10;
and if you change its value somewhere in the program to 20 (for example), its initial value will be 20 (not 10) on the next program start! Note that this is true only for global and static variables. To force reinitializing, you must put explicitely something like
a = 10;
at the begining of the main program!

Note, however, that if the program is archived, the initial values will be restored each time you run the program, because archived programs are reloaded from the archive memory to the RAM on each start, similarly like the programs are reloaded from disks on "standard" computers each time when you start them.

struct

Groups variables into a single record.
The syntax for defining records is:
struct [struct-type-name]
  {
    [type variable-names] ;
    ...
  } [structure-variables] ;
A struct, like an union, groups variables into a single record. The struct-type-name is an optional tag name that refers to the structure type. The structure-variables are the data definitions, and are also optional. Though both are optional, one of the two must appear.

Elements in the record are defined by naming a type, followed by variable-names separated by commas. Different variable types can be separated by a semicolon. For example,
struct my_struct
  {
    char name[80], phone_number[80];
    int age, height;
  } my_friend;
declares a record variable my_friend containing two strings (name and phone_number) and two integers (age and height). To declare additional variables of the same type, you use the keyword struct followed by the struct-type-name, followed by the variable names. For example,
struct my_struct my_friends[100];
declares an array named my_friends which components are records. In fact, 'struct my_struct' becomes a new type which is equal in rights with any built-in type.

To access elements in a structure, you use a record selector ('.'). For example,
strcpy (my_friend.name, "Mr. Wizard");
A bit field is an element of a structure that is defined in terms of bits. Using a special type of struct definition, you can declare a structure element that can range from 1 to 16 bits in length. For example,
struct bit_field
  {
    int bit_1 : 1;
    int bits_2_to_5 : 4;
    int bit_6 : 1;
    int bits_7_to_16 : 10;
  } bit_var;

switch, case, default

Branches control.
switch causes control to branch to one of a list of possible statements in the block of statements. The syntax is
switch (expression) statement
The statement statement is typically a compound statement (i.e. a block of statements enclosed in braces). The branched-to statement is determined by evaluating expression, which must return an integral type. The list of possible branch points within statement is determined by preceding substatements with
case constant-expression :
where constant-expression must be an int and must be unique.

Once a value is computed for expression, the list of possible constant-expression values determined from all case statements is searched for a match. If a match is found, execution continues after the matching case statement and continues until a break statement is encountered or the end of statement is reached. If a match is not found and this statement prefix is found within statement,
default :
execution continues at this point. Otherwise, statement is skipped entirely. For example,
switch (operand)
  {
    case MULTIPLY:
      x *= y; break;
    case DIVIDE:
      x /= y; break;
    case ADD:
      x += y; break;
    case SUBTRACT:
      x -= y; break;
    case INCREMENT2:
      x++;
    case INCREMENT1:
      x++; break;
    case EXPONENT:
    case ROOT:
    case MOD:
      printf ("Not implemented!\n");
      break;
    default:
      printf("Bug!\n");
      exit(1);
  }
See also break.

Note: GNU C extends the case keyword to allow case ranges.

typedef

Creates a new type.
The syntax for defining a new type is
typedef type-definition identifier;
This statement assigns the symbol name identifier to the data type definition type-definition. For example,
typedef unsigned char byte;
typedef char str40[41];
typedef struct {float re, im;} complex;
typedef char *byteptr;
typedef int (*fncptr)(int);
After these definition, you can declare
byte m, n;
str40 myStr;
complex z1, z2;
byteptr p;
fncptr myFunc;
with the same meaning as you declare
unsigned char m, n;
char myStr[41];
struct {float re, im;} z1, z2;
char *p;
int (*myFunc)(int);
User defined types may be used at any place where the built-in types may be used.

union

Groups variables which share the same storage space.
A union is similar to a struct, except it allows you to define variables that share storage space. The syntax for defining unions is:
union [union-type-name]
  {
    type variable-names;
    ...
  } [union-variables] ;
For example,
union short_or_long
  {
    short i;
    long l;
  } a_number;
The compiler will allocate enough storage in a number to accommodate the largest element in the union. Elements of a union are accessed in the same manner as a struct.

Unlike a struct, the variables 'a_number.i' and 'a_number.l' occupy the same location in memory. Thus, writing into one will overwrite the other.

void

Empty data type.
When used as a function return type, void means that the function does not return a value. For example,
void hello (char *name)
{
  printf("Hello, %s.", name);
}
When found in a function heading, void means the function does not take any parameters. For example,
int init (void)
{
  return 1;
}
This is not the same as defining
int init ()
{
  return 1;
}
because in the second case the compiler will not check whether the function is really called with no arguments at all; instead, a function call with arbitrary number of arguments will be accepted without any warnings (this is implemented only for the compatibility with the old-style function definition syntax).

Pointers can also be declared as void. They can't be dereferenced without explicit casting. This is because the compiler can't determine the size of the object the pointer points to. For example,
int x;
float f;
void *p = &x;    // p points to x
*(int*)p = 2;
p = &r;          // p points to r
*(float*)p = 1.1;

volatile

Indicates that a variable can be changed by a background routine.
Keyword volatile is an extreme opposite of const. It indicates that a variable may be changed in a way which is absolutely unpredictable by analysing the normal program flow (for example, a variable which may be changed by an interrupt handler). This keyword uses the following syntax:
volatile data-definition;
Every reference to the variable will reload the contents from memory rather than take advantage of situations where a copy can be in a register.

while

Repeats execution while the condition is true.
Keyword while is the most general loop statemens. It uses the following syntax:
while (expression) statement
statement is executed repeatedly as long as the value of expression remains nonzero. The test takes place before each execution of the statement. For example,
while (*p == ' ') p++;
Of course, statement may be a compound statement as well.

All about C#

What is C# all about?

C# was developed at Microsoft. It is an object-oriented programming language and provides excellent features such as strong type checking, array bounds checking and automatic garbage collection. We will explore these and several other features in this article.

C# has features that make it an excellent choice for developing robust distributed n-tier Enterprise applications, web applications, windows applications and embedded systems. It is used for building applications ranging from the very large that use sophisticated operating systems, down to the very small having specialist functions

Getting Started:

Here is a very simple “Hello World” program written using C#. The code for C# program is written in text files with an extension “.cs”

Example:

1) Create a text file “First.cs”
2) Type the following code and ‘save’

using System;
class myClass
{
     static void Main()
     {
          Console.WriteLine("Hello World");
     }
}

3) From the command line compile the above code by typing the following
csc First.cs 4) This creates First.exe
5) Run this exe from the command line and you see an output –
Hello World

Having seen the example above we will now review the concepts and elements of the C# programming language. After that we will review the above example once again to understand what each line of code does. To get a better grasp of the C# language it is helpful if you have some programming experience and even better if you have experience in Object Oriented Programming. We now examine the C# language concepts and elements one by one.

A) OOP

C# is an object oriented Programming language and it supports the Object Oriented Programming Methodology. When creating a software solution you can represent the real world entities as “objects” of different “types”.

a. Types: C# supports mainly two kinds of types: value types and Reference types. The difference lies in the way in which handles these tow kinds of types. Examples of value types are – char, int, structures, enums . Examples of Reference types are – class, interface, delegate, arrays

i. Variables represent storage locations. Every variable is of a specific ‘type’. This determines what values can be stored in it.

ii. Field is a variable that is associated with a Class or Struct, or an instance of a class or struct.

iii. Parameters: There are four kinds of parameters: value parameters, reference parameters, output parameters, and parameter arrays.

iv. Classes: Classes are blueprints for objects. You instantiate an object from class. An object thus instantiated if said to be of a reference types. As C# is an Object Oriented Programming Language a class can inherit from another class, and can implement interfaces. Each Class can have one or members such as methods, properties, constants, fields, events, constructors, destructors and so on.

v. Structs: Structs are similar to classes in many ways. They have members and they can implement interfaces. They are fundamentally different from classes. STRUCTS are value types. STRUCT values are stored "on the stack" or "in-line". They cannot be inherited from any other class or reference type.

vi. Interfaces: What is an interface? An Interface simplifies a complex process by providing easy to use methods. Consider you need to change the channel on your TV or increase its volume, how do we do this, we use a Remote Control to change the channel or increase the volume. In this context, a Remote Control acts as an interface between you and your TV. Using a Remote Control one can perform required operation and control various functionality available in TV.

An interface defines a contract. When a class or a struct implements an interface with the help of methods and properties. A type (CLASS or STRUCT) that implements an interface must adhere to its contract. Interfaces can contain methods, properties, events, and indexers as members.

vii. Delegates: C# implements the functionality of function pointers using Delegates.

A delegate instance encapsulates a list of one or more methods, each of which is referred to as a callable entity. When a delegate instance is invoked it causes the delegate instance's callable entity to be invoked.

viii. Enums: An enum type declaration defines a type name for a related group of symbolic constants.

ix. Predefined types: The predefined value types include

  • signed integral types (sbyte, short, int, and long)
  • unsigned integral types (byte, ushort, uint, and ulong)
  • floating-point types (float and double)
  • bool
  • char
  • decimal
x. Nullable types These are constructed using the ‘?’ type modifier.

int? is the nullable form of the predefined type int.
int? x = 42;
int? z = null;

The nullable type is a structure. This structure has two members :

- A value of the underlying type (“Value”)
- A Boolean null indicator (“HasValue”)

HasValue is true for a non-null instance and false for a null instance. When HasValue is true, the Value property returns the contained value.
When HasValue is false, an attempt to access the Value property throws an exception.
if (x.HasValue) Console.WriteLine(x.Value);

An implicit conversion exists from any non-nullable value type to a nullable form of that type.

B) Namespaces

C# programs are organized using namespaces. Namespaces provide a hierarchical means of organizing the elements of one or more programs. They also provide a way of presenting program elements that are exposed to other programs. For instance in our example

using System;
class myClass
{
     static void Main()
    
{           Console.WriteLine("Hello World");      }
}

The statement – “using system;” helps us use the “Console” class in it. A namespace-declaration consists of the keyword namespace, followed by a namespace name and body

namespace Company1.Dept2
{
    
class manager {}      class emp {}
}


namespace Company1
{
    
namespace Dept2      {           class manager {}           class emp {}      }
}

Namespaces are open-ended, and two namespace declarations with the same fully qualified name contribute to the same declaration space In the example

namespace Company1.Dept2
{
    
class manager {}
}


namespace Company1.Dept2
{
    
class emp {}
}

the two namespace declarations above contribute to the same declaration space,

Assemblies Assemblies are used for physical packaging and deployment. An assembly can contain the executable code and references to other assemblies.

C) Language Grammar

a. Expressions: An expression is a sequence of operands (variables, literals, etc) and operators An expression can be classified as one of the following:

  • value
  • variable
  • namespace
  • type
  • method group
  • property access
  • event access
  • indexer access
  • void or Nothing
The output of an expression can never be a namespace, type, method group, or

b. Statements: C# statements can be classified as one of the following:

  • labeled-statement
  • declaration-statement
  • embedded-statement
  • embedded-statement: (statements that appear within other statements)
  • empty-statement
  • expression-statement
  • selection-statement
  • iteration-statement
  • jump-statement
  • try-statement
  • checked-statement
  • unchecked-statement
  • lock-statement
  • using-statement
c. Constants: A constant is a class member that represents a constant value: a value that can be computed at compile-time. Constants can depend on other constants within the same program.

class myClass
{
     public const int A = 1;
     public const int B = A + 1;
}

d. Fields: A field is a member that represents a variable associated with an object or class.

e. Operators: The operators of an expression indicate which operations to apply to the operands. Examples of operators: +, -, *, /, new. There are three kinds of operators:

  • Unary operators. The unary operators take one operand and use either prefix notation (such as –-counter) or postfix notation (such as counter++).
  • Binary operators. The binary operators take two operands and all use infix notation (such as intA + intY).
  • Ternary operator. Only one ternary operator, ?:, exists; it takes three operands and uses infix notation (condition? intX: intY).
Certain operators can be overloaded. Operator overloading permits user-defined behavior for the operator.

f) Methods: A method is a member of the class. It implements functionality or behavior or action that can be performed by an instance of that class. Methods can have one or more formal parameters, an optional return value

g) Properties: A property is a member of the class. It provides access to a feature or characteristic of an instance of the class. In the example below: class car has a property CarColor

public class car
{
    
private string _CarColor;      public string CarColor      {           get           {                return _CarColor;           }
    
     set           {                _CarColor = value;
          }      }
}

h) Event: An event is also a member of the class. It enables an object or class to provide notifications when an event occurs. Example

public delegate void EventHandler(object sender, System.EventArgs e);
public class Button
{
    
public event EventHandler Click;      public void Reset() {           Click = null;      }
}


using System;
public class Form1
{
    
public Form1() {
         
Button1.Click += new EventHandler(doSomething);      }      Button Button1 = new Button();      void doSomething(object sender, EventArgs e) {           Console.WriteLine("Button1 was clicked and I did Something!");      }      public void Disconnect() {           Button1.Click -= new EventHandler(doSomething);      }
}

i) Comments: Two forms of comments are supported: delimited comments and single-line comments. A delimited comment begins with the characters /* and ends with the characters */. Delimited comments can occupy a portion of a line, a single line, or multiple lines. A single-line comment begins with the characters // and extends to the end of the line.

/* This is my First Program
This is where it gets started
*/
class myFirstProgram
{
    
static void Main() {           System.Console.WriteLine("Welcome Aboard!"); // Comment      }
}

j) Conditional Statements The if statement selects a statement for execution based on the value of a Boolean expression. Examples:

if ( boolean-expression ) embedded-statement
if ( boolean-expression ) embedded-statement else embedded-statement
if (x) if (y) F(); else G();


if (x)
{
    
if (y) {           F();      }      else {           G();      }
}

The switch statement: Based on the value of the switch expression. The switch statement matches a switch label and executes the statement(s) that corresponds to it
Example:

switch (iMatch) {
    
case 0:           Matched_Zero();           break;      case 1:           Matched_One();           break;      default:           Matched_None();           break;
}

k) Iteration statements : Iteration statements repeatedly execute an embedded statement.

Types of iteration statements:

  • while-statement
  • do-statement
  • for-statement
  • foreach-statement
Keywords in C#

abstractasbaseboolbreak
bytecasecatchcharchecked
classconstcontinuedecimaldefault
delegatedodoubleelseenum
eventexplicitexternfalsefinally
fixedfloatforforeachgoto
ifimplicitinintinterface
internalislocklongnamespace
newnullobjectoperatorout
overrideparamsprivateprotectedpublic
readonlyrefreturnsbytesealed
shortsizeofstackallocstaticstring
structswitchthisthrowtrue
trytypeofuintulongunchecked
unsafeushortusingvirtualvoid
volatilwhile   



l) Conversions A conversion enables an expression of one type to be treated as another type. Conversions can be implicit or explicit. A conversion enables an expression of one type to be treated as another type. Conversions can be implicit or explicit.
A conversion enables an expression of one type to be treated as another type. Conversions can be implicit or explicit.

m) Arrays An array is a data structure. It contains one or more variables that are accessed through computed indices. The elements of the array, are all of the same type.




n) Memory Management: One of the most important features of C# is automatic memory management implemented using a ‘garbage collector’. The process scans thru the objects created in the program and if the object can no longer be accessed the memory is cleared up

o) Indexers : An indexer enables an object to be indexed in the same way as an array.

Indexer declarations are similar to property declarations. The indexing parameters are provided between square brackets. Example

using System;
public class AllmyCars
{
     private Car GetCar(int index)
    
{           //process and return appropriate car      }      public object this[int index]      {           get           {                return GetCar (index).Value;           }                set           {                GetCar(index).Value = value;           }      }     
}
class Test
{
     static void Main()      {           AllmyCars c = new AllmyCars();           c[0] = “Rolls Royce”;           c[1] = “Alpha Romeo”;           c[2] = “Saab”;      }
}

Sunday, 23 January 2011

Java World

Basic Java WorldFrom Wikiversity
Jump to:
navigation, search
This lesson discusses the basics of the Java language, including variables, primitives, operators, statements and Java writing conventions.
Contents[hide]
1 Touch on Classes 1.1 Protection or Access Levels 1.2 class 1.3 Name 1.4 Extends/Implements 2 Statements 3 Comments 4 Variables 4.1 Declaring Variables 4.2 Primitive Data Types 5 Operators 5.1 Assignment Operators 5.2 Addition Operator '+' 5.3 Subtraction '-', multiplication '*', division '/', and modulus '%' operators 5.3.1 Plus-equals 5.3.2 Minus-equals, multiply-equals, divide-equals, and mod-equals 5.4 Concatenation operator 6 Valid Identifiers 7 System.out 8 Compiling and running your program 9 User Input 10 Exercises
edit] Touch on ClassesEverything in Java is written in classes. A Class in this context is a section of code that can contain data (variables), and instructions for processing that data (methods). Returning to the Hello World example from the Introduction to Java, the class is defined on the first line, and everything within the curly brackets is within that class.public class HelloWorld
{
public static void main (String[] args)
{
System.out.println("Hello World!");
}
}
The first line is always of the general form:
[Protection] class [Name] [Extend/Implements...]
{
/*Class Code Here*/
}
[edit] Protection or Access LevelsJava provides two types of access levels.

[

Class access: public or package level (no modifier)
Member access: public, protected, package (no modifier or default), and private
A class with public modifier is visible by all other classes. Class with no modifier has package level protection. It means that only other classes within the same package can see it.
Member access levels control visibility of member data or methods from its own class, within package, subclass, or the world. See table below for the summary.
However, in order to get started without being bogged down by choosing one, just declare all of your classes as public. The idea behind protection is that, if only the class itself can make changes to the data stored within itself, the other parts of the program do not need to know where the data is coming from or how it is stored. This is great for two reasons, firstly, it is easy to rewrite the structure of a class without changing the external application, and secondly it allows the class to make assumptions about the data, and do slightly less exception handling. You should know that if your code tried to break the protection of a class, the java compiler will stop and report an error.
Access Levels
ModifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN

[
edit] classThis is the bit that tells the Java compiler we are writing a new class, the only slightly notable thing about it is that it must be written in small letters. It is not Class![edit] NameThis is the name by which you will reference your class when you use it in your code, it can be called almost anything you want, containing numbers, letters and underscores, though it must start and end with a letter. One thing to watch out for, is that, like everything in Java, it is case sensitive. This means that Hello is not the same as hello. You could, if you wanted have two different classes, one called hello and the other called HeLlO, however this might get confusing and so is strongly discouraged. In fact, in order to try and make things less confusing, there is a convention amongst Java programmers that all words in a class name start with a capital letter, and the rest are lower case letters. eg. public class VeryUseful or public class CompanyDepartment[edit] Extends/ImplementsExtends/Implements not complete yet. Soon..
Every java class has a parent class, if it has not been specified then the default parent class is
java.lang.Object.
[edit] StatementsAll operations are done in statements. Every statement ends in a semicolon: ;. Statements can set a variable with the '=' operator. This sets the variable you wish to set to another variable or a value. Values can only be used on primitive types. As you saw in the HelloWorld program, there was one statement: System.out.println("Hello, World"). This is one type of statement called "calling a method". More will be discussed later. Finally, you can declare a variable. If a class has no statements, it would do nothing.[edit] CommentsComments are short notes that the developer can insert into their code. This allows the developer to keep track of their code and helps when developers are collaborating on a project. It is good to write a summary of the following code at the beginning of your methods, classes, etc. The Java compiler completely ignores comments, so you can say anything in them.
Comments are written using two forward slashes
// This is a commentComments can be written at the end of a line
System.out.println("I love comments"); // This is also a commentComments can also be written on multiple lines by starting with /* and ending with*/.
/*
Comment 1
Comment 2
Comment 3
*/
A multi-line comment that opens with two asterisks
/**
* Like this
*/
is called a
Javadoc comment. These comments are used to generate documentation for your code, and they generally appear at the beginning of a class or a method definition. A special program (also named javadoc) can be used to automatically create documentation from the Javadoc comments, usually in the form of a set of HTML files. It is generally good practice to fully document your code by using Javadoc comments, but it is not required. We will use comments to document and explain our code from now on.[edit] VariablesVariables are used to store information in a computer's memory. Like its name implies, variables are values that can be changed. There are two main categories of variables: reference variables and primitive variables. Reference variables are place holders for objects (More on objects in Lesson 4, Java Objects and Classes.) Primitive variables are given a value of a primitive data type, a fundamental value. Variables are all given a type when they are declared, such as "int" or "float".[edit] Declaring VariablesTo declare a variable, use this syntax:
[protection] [classname] [identifier]This is one type of statement. The class name is the type of variable you want. Currently, you will only use basic primitive variables, but you will learn about objects soon. Here is an example of declaring a variable:
public int myIntmyInt has protection of public. It is of class int, or Integer (see Primitive Types). int is a class in Java. When you say that, you are basically making a primitive object.
[edit] Primitive Data TypesPrimitives are the simplest type of data. The following table shows all the types of primitives.
PrimitiveDescriptionValues
byteA brief, 8-bit integerInteger numbers -128 through 127
shortA short, 16-bit integerInteger numbers -32,768 through 32,767
intA 32 bit integerInteger numbers -2,147,483,648 through 2,147,483,647
longA long, 64 bit integerInteger numbers -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807
floatSingle-precision floating point (32-bit IEEE 754)Smallest positive non-zero: 14e-45, Largest positive non-zero: 3.4028234e38
doubleDouble-precision floating point (64-bit IEEE 754)Smallest positive non-zero: 4.9e-324, Largest positive non-zero: 1.797693157e308
charA single characterAll Unicode characters
booleanA Boolean value(1-bit)true or false



Using what you have learned, you may have guessed how to create these primitives:
long myLong; double myDouble;[edit] OperatorsOperators are the symbols defining a certain operation to be performed.[edit] Assignment OperatorsAn assignment operator assigns a value to a certain variable after evaluating the expression to be assigned.
The assignment operator, "=", sets the variable on its left equal to the value on its right. This code creates the variable a and sets it equal to 5
int a;
a = 5;
Fairly simple, right? Here is where it can get a slightly more tricky.
int a;
int b;
b = 6;
a = b; //a equals 6
At first glance, you might think that the last statement is setting a equal to the letter "b", but instead it is setting a equal to the value of b, which is 6. Essentially, a holds the value of 6. You can also set a variable and declare it on the same line:
int a = 6;However, you can't say char myChar = y; to set a character to 'y'. That would set the character variable myChar to the value stored in the character variable y. To set myChar equal to the character y, use a character literal — a technical term for "a character in single-quotes": char myChar = 'y';. Note that a char primitive can only hold a single character. char myChar = 'Yo'; is illegal.
Finally, what's so special about floats and doubles? Doubles and floats can have decimals: float myFloat = 5.1;. (The term "float" is short for "floating-point number," referring to the decimal point.)
Now, why would you want to set a variable? You would need to set a variable for further use, i.e., to access at a later time.
[edit] Addition Operator '+'The addition operator returns the sum of the the values to the left, and the value to the right of it.
If you want to evaluate the expression 23 plus 75, you would type:
23+75The addition operator also works with variables:
myInt+yourIntNote, this operator is not to be confused with the concatenation operator, which we will discuss later.
[edit] Subtraction '-', multiplication '*', division '/', and modulus '%' operatorsJust like the addition operator, the subtraction, multiplication, division, and modulus operators are used as follows:int a = 9;

a-1; // evaluates to 8
a/3; // evaluates to 3
a*2; // evaluates to 18
a%4; // evaluates to 1
Subtraction, multiplication, and division, you have seen before, but the modulus operator is much less commonly used. Actually, it is commonly used, but is known under a different name, the remainder. Nine divided by four gives a remainder of one, so therefore 9%4 (pronounced "9 mod 4") evaluates to 1.
When more than one of the operators are used in the same statement, for example:
int a, b, c, d;
a = a-b/c*d;
the Java language would use the order-of-operations in this case.
[
edit] Plus-equalsedit] Minus-equals, multiply-equals, divide-equals, and mod-equalsMinus-equals, multiply-equals, divide-equals, and mod-equals works in the same way as plus-equals, except instead of addition, they do subtraction, multiplication, division, and modulus, respectively.[edit] Concatenation operatorThe concatenation operator (+) looks exactly like the addition operator, however it performs a different operation. The concatenation operator concatenates or "puts together," for lack of a better term, two Strings.String myString = "Hello, ";
String yourString = "world.";
String ourString = myString + yourString; // evaluates to "Hello, world."
[edit] Valid IdentifiersThere are several rules for the naming of your variables. Identifiers can be named using all the letters from A through Z (capital or lowercase, you choose), numbers 0-9 and underscore _ and the dollar sign $. The first character of the identifier cannot be a number, but it can be a letter, _ or $. Identifiers can be no longer than 32 characters.
You can't create two variables with the same identifier; all identifiers must be unique. You also can't use an identifier that is a Java keyword, listed below.
Flashcards for Java keywords provides some assistance in memorizing the concepts behind specific keywords.
abstractassertbooleanbreakbytecase
catchcharclassconstcontinuedefault
elseenumextendsfalsefinalfinally
floatforgotoifimplementsimport
instanceofintinterfacelongnativenew
nullpackageprivateprotectedpublicreturn
shortstaticstrictfpsuperswitchsynchronized
thisthrowthrowstransienttruetry
voidvolatilewhile

Identifiers should also be meaningful, while maintaining practicality. If calculating the sum of a set of numbers, sum is better than cumulativeTotal, but s might be too short.
[edit] System.outIt is often useful (and necessary) to view the output of your program, especially when you are just getting started or when you are debugging. Java provides a way to do this. System.out is a static member (don't worry about what this means for right now) which contains various methods which allow programmers to output text to the console. Two commonly used methods are System.out.print() and System.out.println(). The first allows you to print text without a line break, and the second inserts a new line after every call.
Using System.out.println() is extremely simple, though C/C++ programmers may find it cumbersome to type up compared to simply typing printf(). The method println() takes one parameter, the variable you wish to output, and writes it to the console.
System.out.println( myInt );You can also print out multiple variables on the same line:
System.out.println( false + " " + 54 );Note that this won't work for two literal numeric values:
System.out.println( 54 + 32 );.
The plus sign would be mistaken for the addition operator for adding numeric values. So to print out "5432", you would have to type:
System.out.println( 54 + "" + 32 );Now you can do calculations and print the result! For example, say you want to evaluate 6*6*6*6 and then print the result ("1296"). Here is the code:
public class Multiplying
{
public static void main(String args[])
{
int a = 6;
int b = a*a*a*a;
System.out.println(b + "");
}
}
[edit] Compiling and running your programTo compile your program, go to the directory you saved it in. Note that if your class was named NaMe then your file must be named NaMe.java. Notice that Java is case-sensitive. Anyways, type: javac NaMe.java where NaMe is your class name in a command-line window. To run the program, type java NaMe. Do not forget to include the ".java" extension when compiling the file, and to leave out any extensions when running the program.
If the compiler reports syntax errors with your code, you must look in your source code and fix them. These are usually typos, but can be missing semi-colons or other formatting issues.
If, when running, it reports "invalid class file", the compiler might not have created a file. It should have given an error message at compile time.
[edit] User InputThe first way to get user input is from the keyboard without using the swing gui. You must first import the Scanner package first like so. import java.util.Scanner; Once you have done that you will have to create a Scanner object. Scanner scan1 = new Scanner(System.in); Finally after the user has entered the input asked for you retrieve using your Scanner object. For example if we wanted a string as input we could use the following code.import java.util.Scanner;
public class GettingStringInput
{
public static void main(String[]args)
{
String yourinput = new String();
Scanner scan1 = new Scanner(System.in);
System.out.print("Please enter a string: ");
yourinput = scan1.nextLine();
}
}
In order for the following to work properly, you must place the following code on the first line of your .java file. Importing packages will be explained later.import javax.swing.JOptionPane;Now, let's go on to asking the user to enter a number and doing calculations on it. Basically:
JOptionPane.showInputDialog( null, "Hello, enter something" );. Try putting that in a class (in the main method, of course) and run it. Currently, we can't do anything with it because the value is deleted. Because what you enter can consist of letters OR numbers, and any length of them, what is "produced" by that is a String. The following will work:
String mine = JOptionPane.showInputDialog( null, "Now I can set a String!" );. Now lets say that after you get the string you want to print it. Just like regularly, add the following line:
System.out.println( mine );. Now you probably want to be able to enter a number. Java provides a method of changing a String to an int. It is
Integer.parseInt( String_Here );. So lets say you want the user to enter a number and you print it. Do:
int mine = Integer.parseInt( JOptionPane.showInputDialog( null, "Now I can set an int!" ) );
System.out.println( mine );
And now, of course, you can do whatever you want with that...
The plus-equals operator ("+=") adds the value on the right, to the variable on the left, and then assigns that value back into the variable on the left.
Example:
int a = 6; // assigns the value 6 to variable a
a += 5; // adds 5 to a, and assigns that value back into a, now a is 11
[