Evo. G Tech Team Forum
Welcome to Evo. G Tech Team Forum. We have moved to a new website : www.evogtechteam.com

Thanks you.

by Evo. G Tech Team Management.

Join the forum, it's quick and easy

Evo. G Tech Team Forum
Welcome to Evo. G Tech Team Forum. We have moved to a new website : www.evogtechteam.com

Thanks you.

by Evo. G Tech Team Management.
Evo. G Tech Team Forum
Would you like to react to this message? Create an account in a few clicks or log in to continue.

C.2 REVISION OF FUNDAMENTAL IN PROGRAMMING (Data, Operations and Control Structures)

Go down

C.2 REVISION OF FUNDAMENTAL IN PROGRAMMING (Data, Operations and Control Structures) Empty C.2 REVISION OF FUNDAMENTAL IN PROGRAMMING (Data, Operations and Control Structures)

Post by LifeStyle June 21st 2014, 01:08


Chapter 2: REVISION OF FUNDAMENTAL IN PROGRAMMING
(Data, Operations and Control Structures)


Identifiers

You need to choose names for the things you will refer to in your programs. Identifiers are used
for naming such programming entities as variables, constants, methods, classes, and packages.

Here are the rules for naming identifiers:
• Can be a sequence of characters that consist of letters, digits, underscores (_) and a dollar sign ($).
• Must start with a letter, an underscore or dollar sign. It cannot begin with a digit.
• Cannot be a reserved word.
• Cannot be ‘true’, ‘false’ or null.
• Can be of any length.

Note: Since java is case-sensitive, X and x are different identifiers.

Data Types

The Java language provides for eight primitive types of data:
[You must be registered and logged in to see this image.]

Variables

• Data is variable when its value may change during program execution. They are used to store data input, output or intermediate data.

Declaring variables

--To use a variable, you declare it by telling the compiler the name of the variable as well as the type of data it represents.
--The computer will allocate appropriate memory space for the variable based on its data type.

 HOW ----- ?

The Syntax:
                        datatype variableName;

--Other examples:
                        double Old_Price;
                        double radius;
                        int qtty;
                        char grade;
                        int x;

--Short-hand form:
If variables are the same type, they can be declared together (separated by
commas), as follows:
                  double bookPrice ;
                  double pricePayed ;                     = = double bookPrice, pricePayed ;

Note:
1) By conversion, variable names are in lowercase.
2) A variable must be declared before it can be assigned a value.

Assignment Statements and Expressions
--After a variable is declared, you can assign a value to it by using an assignment
statement (=). The syntax as follows:

                                    variableName = expression;

--Expression – represents a computation involving values, variables, and operators
that evaluates to a value. For example:

                                     int x = 5; //assign 5 to a variable x
                                     double radius = 2.3; //assign 2.3 to a variable radius
                                     char a = ‘A’; //assign ‘A’ to a variable a
                                     x = 5 * (2/3) + 5; //assign the value of the expression to x
                                     area = radius * radius * 3.142; //compute area

Constants

• The value of a variable may change during program execution, but a constant represents permanent data that never be changed. For example, to compute area of a circle - p is a constant.
• If you don’t want to keep typing 3.142; instead you can define a constant for p.
• HOW ----- ?

Syntax:
                       final datatype constantName = VALUE;

Example:
                       final double PI = 3.142;

Note:
1) The word final is a Java Keyword, which means that the constant cannot be changed.
2) By conversion, constants are named in uppercase: PI

• A constant must be declared and initialized before it can be used.
• Benefits of using constants:
o You don’t have to repeatedly type the same value
o The value can be changed in a single location, if necessary
o The program is easy to read.

• Declare and display value
                                           // DemoVariables.java
                                          // Declare and display value

                                         public class DemoVariables
                                         {
                                                    public static void main(String[] args)
                                                    {
                                                                   int d = 315;
                                                                   System.out.println(“The int is”);
                                                                   System.out.println(d);
                                                                   //or u can write like this
                                                                  // System.out.println(“The integer is” + d);
                                                     }
                                         }

• Declare two more variables in a program
                                                // DemoVariables2.java
                                                // Declare and display value
                                                public class DemoVariables2
                                                {
                                                          public static void main(String[] args)
                                                          {
                                                                       int oneInt = 315;
                                                                       short oneShort =23;
                                                                       long oneLong = 1234567876543L;
                                                                       System.out.println(“The int is “);
                                                                       System.out.println(oneInt);
                                                                       System.out.println(“The short is” + oneShort);
                                                                       System.out.println(“The long is “);
                                                                       System.out.println(oneLong);
                                                          }
                                                 }

Note:
The plus (+) in the System.out.println(“ “) statement means to concatenate strings if one of the operands is a string. If both operands are numbers, the + operator will add them.

Arithmetic Statements
--There are five standard arithmetic operators in Java:
o addition (+)
o subtraction (-)
o division (/)
o multiplication (*)
o modulus (%). The modulus operator is for integers, and returns the remainder of integer division

[You must be registered and logged in to see this image.]

Example:
[You must be registered and logged in to see this image.]

--When mathematical operators are combined in an expression, you must understand the effects of operator precedence. In the absence of parenthesis, multiplication, division and modulus operations will be done before addition and subtraction operations

The Boolean data type
• A Boolean variable may contain only one of two values - true or false.
                                   boolean isInOffice = false;
                                   boolean isOutOffice = true;

• Another example, the following statement displays true.
                                   System.out.println (1<2);

• Java supports six comparison operators to be used in comparing two data items, equal to (==), greater than (>), less than (<), not equal (!=), greater or equal (>=), less than or equal (<=). Expressions which contain comparison operators result in a
Boolean value, refer the table below.

Note:
The equality comparison operator is two equal signs (==), not a single equal sign
(=). The latter symbol is for assignment.

Logical operators:
[You must be registered and logged in to see this image.]

Floating point data types

• Floating-point data types are used to store values that contain decimal positions.
Java supports two floating-point types, float and double.
• A float data type can represent 6 or 7 significant digits of precision, while a double
can represent 14 or 15 significant digits of precision



• Example:
                             double dnum1 = 1.5, dnum2 = 0.5, dResult;
                             dResult = dnum1 + dnum2;
                             System.out.println(“the sum of the doubles is “ + dResult);
                             DResult = dnum1 * dnum2;
                             System.out.println(“the product of the doubles is “ + dResult);

Modulus operations should not be performed on floating point data

Numeric type conversion

• When performing arithmetic on variables and constants of the same type, the result of the operation retains that type. Example:
                                                Result1 = 10 / 5
                                                Result2 = 15.8 – 10.5

• When performing operations on operands of unlike types, Java selects a unifying type for the result. Java then implicitly, or automatically, converts the nonconforming operands to the unifying type
                             
                                                 int quantity = 5;
                                                 double price = 2.00
                                                 double totalPrice = quantity * price;

• List of data type in order for establishing unifying types between two variables.
1. double
2. float
3. long
4. int
5. short
6. byte

• You can explicitly override the unifying type by placing the desired result type in
parenthesis before the variable or constant to be cast. This is called type casting.
                           

double income = 127.00;
float share = (float) income / 5; // 25.40
int ringgitPerPerson = (int) share; //ringgitPerPerson is 25


The char data type

• Char: character
• Use the char data type to store a single character.
                                     char aChar = ‘9’;
                                     int aNum = 9;
                                     char aChar = 9;
                                     int aNum = ‘9’;
                                 ================
                                     char myInitial = ‘A’;
                                     char perssign = ‘%’ ;
                                     char numChar = ‘9’ ;

• The char type is only for single characters. To store a string, you must use the String data structure
                                     String myName = “Fatima”;

Note: A string must be enclosed in quotation marks. So, “A” is a string and ‘A’ is a character.

• Characters may be assigned to char variables, or assignments maybe made using an escape sequence containing the Unicode value of the character. Non-standard and international characters may be assigned in this way
                                            char aBackSpaceChar = ‘\b’ ;

• Escape sequences are to represent special characters as shown in the table below. It
has a special meaning to the compiler.
[You must be registered and logged in to see this image.]

• For example, you want to print the quoted message:
                      They shouted “Malaysia Boleh!”.

• The statement:
                            System.out.println(“They shouted \”Malaysia Boleh\” ”);

• The characters used in Java are represented in Unicode, which is a 16-bit coding scheme for characters.
char letter = ‘A’;
char letter = ‘\u0041’;                           Same: variable letter store character A

Operator Precedence and Associativity

• Determine the order in which operators are evaluated.
• For example: 3 + 4 * 4 > 5 * ( 4 + 3 ) – 1 What’s the answer?

CONTROL STRUCTURES

Introduction

The order in which statements are executed in a running program is called the flow of control. Unless otherwise specified, the execution of a program proceeds in a linear fashion. We can alter the flow of control through the code by using certain types of programming statements. Java has 2 categories of control structures:

• Selection: lets you choose actions with two or more alternative courses.
• Repetition/Loop: control the repeated execution of statements.

In this chapter, you will learn various selection and loop control statements.
[You must be registered and logged in to see this image.]

Selection Statements

Java has several types of selection statements: simple if statements, if…else statements, nested if statements, switch statements and conditional statements.
Simple if statements

--Simple if statement executes an action only if the condition is true.
 The syntax:
                           if (booleanExpression)
                           {
                                      statement(s);
                           }

--Simple example:
                               if (grade >=80)
                               System.out.println(“Passed”);

--Another Example:
                               if (radius >=0)
                               {
                                          area = radius * radius* PI;
                                          System.out.println (“The area is “ + area);
                               }
                                          System.out.println (“Thank you”);

Note:
1) If the value of radius is greater than or equal to 0, then the area is computed the result and ‘Thank you’ are displayed.
2) Otherwise, the two statements in the block will be not executed. Only the
‘Thank you’ is displayed.

 CAUTION:
1) Adding a semicolon at the end of an if clause is a common mistake. For example,
                                 If (grade <=80) ; logic error

o This mistake is hard to find, because it is not a compilation error or runtime error, it is logic error.
2) The example below does not have syntax errors. It assign true to e so that e is
always true.
                                       if ( e = true)
                                       System.out.println (“ It is OK ”);

Note:
1) If we include the Boolean expression, we need to enclose in parentheses for all forms of the if statement. For example:
                              if ( ( i>0) && ( i<0) )
                              System.out.println (“ i is an integer between 0 and 10 ”);

2) The braces { } can be omitted if there is only ONE statement within them.

If…else statements

--A simple if statement takes an action if the specified condition is true. If the condition is false, nothing is done. But if you want to take alternative actions when condition is false? You can use an if …else statement
--The actions that an if…else statement specifies differ based on whether the
condition is true or false.

 The syntax:
                              if (booleanExpression)
                              {
                                       statement(s) for the true case;
                              }
                              else
                              {
                                       statement(s) for the false case;
                              }

 Example:
                              if (grade >=80)
                              System.out.println(“Passed”);
                              else
                              System.out.println(“Failed”);

If number % 2 is 0, the message number is even is printed, if it is false, the odd
number is printed.

HOW TO COMPARE BETWEEN STRINGS?

Nested if statements
--The statement can be used to implement multiple alternatives.
--Nested if can contain another if statement, in fact there is no limit to the depth of the nesting.


 Example:
                  if (score>=90.0)
                  grade = ‘A’;
                  else if (score >= 80.0)
                  grade = ‘B’;
                  else if (score >= 70.0)
                  grade = ‘C’;
                  else if (score >= 60.0)
                  grade = ‘D’;
                  else
                  grade = ‘F’;
                  System.out.println(“Your grade is ” +grade);

Note:
1) As usual, the braces can be omitted if there is only one statement within them.
2) This is the preferred writing style for multiple alternative if statements. It avoids deep indentation and makes the program easy to read.

Switch statements
--Overuse of nested if statement makes a program difficult to read. Java provides a switch statement to handle multiple conditions efficiently.

[You must be registered and logged in to see this image.]

--The switch statement observes the following rules:
o The switch–expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses ( ).
o The value1, value2…..valueN must have the same data type as the value of the switch-expression.
o The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed.
o The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression.
o The order of the cases (including the default case) does not matter.
However, it is good programming style to follow the logical sequence of the cases and place the default case at the end.

--CAUTION:
o Do not forget to use a break statement when one is needed. If it is not present, the next case statement will be executed.


Loop Statements
• Loops are structures that control repeated executions of a block of statements. The part of the loop that contains the statements to be repeated is called the loop body.
• Each loop contains a Boolean expres​sion(loop-continuation-condition) that controls the execution of the body.
• If the condition is true, the execution of the body is repeated. If false, the loop terminates.

Java provides three types of loop statements: the while loop, the do-while loop and the for loop.
The while loop
The syntax:
                        while (loop-continuation-condition)
                        {
                                 statement(s);//loop body
                        }

Example:
                             int i = 0;
                             do
                             {
                                     System.out.println(“Good day!”);
                                     i++;
                             } while ( i<5);

NOTE:
o The do-while loop executes the loop body first, and then checks the loop condition to determine whether to continue or terminate the loop.

The for loop
The syntax:
                        for (i= initialValue; i                         {
                                       statement(s);//loop body
                        }

[You must be registered and logged in to see this image.]

--Flowchart: (same as while loop)
Example:
                       int i;
                       for ( i = 0; i<5; i++)
                       {
                                  System.out.println(“Good day!”);
                       }

NOTE:
1) The for loop statement starts with the keyword for, followed a pair of parentheses.
2) Each statement is separated by semicolons.
3) The flow is same with while loop.

CAUTION:
o Adding a semicolon at the end of the for clause before the loop body is a
common mistake.
                               for (int n = 0; n<10; n++) ; ~~~~~ no semicolor

LifeStyle
LifeStyle
Beginner
Beginner

Posts : 10
Points : 75430
Reputation : 0
Join date : 2014-01-06
Location : Behide you

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum