Rabu, 19 Disember 2012

CHAPTER 7 : ARRAY

  The definition of an array is a numbered sequence of items, which are all of the same type. The number of items in an array is called the length of the array. The position number of an item in an array is called the index of that item. The type of the individual items in an array is called the base type of the array.

     The base type of an array can be any Java type, that is, one of the primitive types, or a class name, or an interface name. If the base type of an array is int, it is referred to as an "array of ints." An array with base type String is referred to as an "array of Strings." However, an array is not, properly speaking, a list of integers or strings or other values. It is better thought of as a list of variables of type int, or a list of variables of type String, or of some other type. As always, there is some potential for confusion between the two uses of a variable: as a name for a memory location and as a name for the value stored in that memory location. Each position in an array acts as a variable. Each position can hold a value of a specified type (the base type of the array). The value can be changed at any time. Values are stored in an array. The array is the container, not the values.


 EXAMPLE :)


-You want to record the temperature for each day of the year .You could have

double tempDay1, tempDay2, ...

all the way to tempDay365

-But this is cumbersome.Arrays are made for situations like this



CREATING ARRAYS



1.To create an array

double [] data; // data is a variable of type double []
data = new double [ 10 ]; // data now holds 10 double values
2.Combined Declaration and Creation

double [] data = new double[10];

3.When array is created, all values are initialized depending on array type:
  • Numbers: 0
  • Boolean: false
  • Object References: null


 TYPES OF ARRAY

    In Java an array is simply a sequence of numbered items of the same type. You can create arrays of the primitive data types (e.g., characters, ints, floats, doubles) and instances of a class (e.g., an array of circle objects).
  1. One-Dimensional array
  2. Two-Dimensional array
  3. .Multi Dimensional array

One-Dimensional array



Declaration and layout of memory for a one-dimensional array of ints.

 The declaration for an array of five integers called iaA, and the corresponding layout of memory. Notice that the array element indices range from iaA [0] through iaA [4].

LOOPS AND ARRAYS

Loops can be used to process array in several ways:
  1. Initialize an array to a specific value
  2. Input data into an array
  3. Print an array
  4. Find the sum and average of an array
  5. Determine the largest element in the array

MANIPULATE DATA INTO ARRAYS

  1. Searching a value
  2. Calculation
  3. Reverse element



Arrays of Objects



  • To create an array that holds 5 BankAccount objects

    BankAccount[] account;

account = new BankAccount[5];



  • To Create a BankAccount object

account[0] = new BankAccount();

  • To fill the array with BankAccount objects

for (int i = 0; i < account.length; i++) {
   account[i] = new BankAccount();
}
    


Object Deletion - Approach 1



  • Delete BankAccount B by setting the reference in position 1 to null.
  • Before deleting B


  • After deleting B

int delIdx = 1;
account[delIdx] = null;



Object Deletion - Approach 2



  • Delete BankAccount B by setting the reference in position 1
    to the last BankAccount.
  • Before deleting B



  • After deleting B
    int delIdx = 1, last = 4;
    account[delIndex] = account[last];
    account[last] = null;
Two-Dimensional array

consists of rows and columns.


Although we think of a 2 dimensional array as consisting of rows and columns, it is actually linearly stored by row. This is an important piece of information that will come into play when passing arrays as parameters in functions.

     


INITIALIZING ARRAYS
Like other data types, it is possible to declare and initialize an array at the same time.

int[] primes = { 2, 3, 5, 7, 11 };

Multi Dimensional array





















CHAPTER 6 : MORE ABOUT OBJECTS AND METHODS


    
   More About Objects and Methods


Defining Constructors


~A special method called when instance of an object created with new create objects and initialize values of instance variables.


~ Can have parameters
-To specify initial values if desired.


~ May have multiple definitions
-Each with different numbers or types of parameters.


~ Constructor without parameters is the default constructor.


~Java will define this automatically if the class designer does not define any constructors.


~If you do define a constructor, Java will not automatically define a default constructor.



Static Variables


~ Also called class variables and contrast with instance variables.


~Do not confuse class variables with variables of a class type.


~Both static variables and instance variables are sometimes called fields or data members.


~Static variables are shared by all objects of a class.


~Variables declared static final are considered constants value cannot be changed but variables declared static without final can be changed.


~Only one instance of the variable exists and it also can be accessed by all instances of the class.


Static Methods


~ Some methods may have no relation to any type of object.


~Example :
-Compute max of two integers
-Convert character from upper- to lower case


~Static method declared in a class and can be invoked without using an object.



Wrapper Classes


~Recall that arguments of primitive type treated differently from those of a class type and may need to treat primitive value as an object.


~Java provides wrapper classes for each primitive type.


~Methods provided to act on values.

~Allow programmer to have an object that corresponds to value of primitive type.


~Contain useful predefined constants and methods.


~Wrapper classes have no default constructor so programmer must specify an initializing value when creating new object.


~Wrapper classes have no set methods.





Decomposition


~Recall pseudocode.
-With this pseudocode we decompose the task into subtasks
-Then solve each subtask
-Combine code of subtasks
-Place in a method


Addressing Compiler Concerns


~ Compiler ensures necessary tasks are done
-initialize variables
-return statement


~Rule of thumb: believe the compiler
-change the code as requested by compiler
-most likely correct



Overloading Basics


~ When two or more methods have same name within the same class.


~Java distinguishes the methods by number and types of parameters.


~If it cannot match a call with a definition, it attempts to do type conversions.


~A method's name and number and type of parameters is called the signature.



Packages 


~ A package is a collection of classes grouped together into a folder.


~Name of folder is name of package.


~Classes use packages by use of import statement.


~Package name tells compiler path name for directory containing classes of package.


~Search for package begins in class path base directory.


~Package name uses dots in place of / or \ .


~Name of package uses relative path name starting from any directory in class path.



Name Clashes


~ Packages help in dealing with name clashes when two classes have same name.


~Different programmers may give same name to two classes for ambiguity resolved by using the package name.








CHAPTER 5 : DEFINNING CLASES AND METHODS

   
     1.Class and method definition

  •           A java program consists of object of various class type,interacting with one another.
  • Object in a program can represent either object in e real world.like automobiles,houses and employee.
  • Class is a kind of object.it is a like a plan or a blueprint for constructing specific object

 
     2.Information hiding and encapsulation
  • A programer who is using a method that you have defined does not need to know the datail of the  code in the body of the method definition to be able to use the method.                                              
  • We can use the scanner method without even looking at the definition of the method.it is not that the code contain some secret that is forbidden to you
  • Designing a method so that it can be used without any need to understand the fine detail of the code is called information hiding
  • The two terms mean the same thing is context.this use of the term abstraction should not be surprising

   3.Object and reference

  •       Variable of a class type name object in a way that is different from how variables of a primitive type store their value.every variable, whether of a primitive type or a class type,is implemented as a memory location.
  • The object itself is not stored in the variable,but rather is some other location in memory.the adress of this other memory location is called reference to the object.
  • There is a reason why variables of a primitive type and variable of a class type name behave in a diffrent ways.every value,of a given primitive type,such as the type int,always requires the same amount of a memory
  • Java has a maximum value of type int,and so value of type int cannot exceed a certain size in memory however,an object,such as an object of the class string,might be any size,making it difficult for the system to set aside a fixed amount of space for variables that name object.

 4.Graphics supplement
  • Now that we have explained method and parameter more completely,we will revisit material from the previous graphics supplement to give more detail explanation.we will : 
  • -Explain the graphics class more completely
    -Use methods rewrite one of our previous graphics applet method similar      





 




         






























































CHAPTER 4 : CONTROL STRUCTURE





CONTROL STRUCTURES


Structured programming is the implementation of three control structures. Structures can be thought of as blocks of code that allows programs to implement sequence, selection and repetition. Sequence, selection and repetition structures each have one entry point and one exit point which provide an element of simplification and organization that makes programs easier to understand and maintain. All programming languages make use of these three structures in various ways. They are essential to performing the complex logic necessary in computer programming.



















The two most common structures are selection and repetition.
  • Selection,The program executes particular statement depending on one or more condition.
  • Repetition ,The program repeats particular statement a certain number of copies depending on one or more conditions.
Branch - Altering the flow of program by making a selection or choice.
Loop - Altering the flow of program execution by the repetition of statement(s)

Before that,you must understand the nature of condition expression and how to use them.

if (score is greater than or equal to 90 )
grade is A



The condition expression is score is greater than or equal to 90.
You can see that a statement such as grade is A is to be executed only if a certain condition is met.A condition is met if it evaluates to true.

is true if the value of score is greater than or equal to 90,it is false otherwise.For example,if the value of score is 95,the statement evaluates to true.Similarly,if the value of score is 86,the statement evaluates to false.So if the value of score is greater than or equal to 90,then the statement,grade is A executes.
it is useful for computer to be able to recognize expression,such as score is greater than or equal to 90,to be true for appropriate values.Futhermore,in certain situation,the truth of statement could depend on more than one condition.

RELATIONAL OPERATORS


To make decisions, you must be able to express conditions and make comparisons.

Logical(boolean)expression :  condition are either true or false.
Relational operator : An operator that that allows you to make comparisons in program.



Relational Operators in Java



NOTE !
In Java , the symbol ==,which consists of two equal signs,is called the equality operator.Recall thht the symbol = is called the assignment operator.The equality operator,==,determines whether two expressions are equal,whereas the assignment operator,=,assigns the value of an expression to a variable.



RELATIONAL OPERATORS AND PRIMITIVE DATA TYPES


You can use the relational operators with integral and floating-point primitive data types.For example,the following expression use both integers and floating-point number :


Expression                          Meaning                                                              Value
8 < 15                                 8 is less than 15                                                    true
6 != 6                                  6 is not equal to 6                                                 false
2.5 > 5.8                             2.5 is greater than 5.8                                          false
5.9 <= 7.5                           5.9 is less than or equal to 7.5                             true




LOGICAL(BOOLEAN)OPERATORS AND LOGICAL EXPRESSIONS


There are three other boolean operators that we need to learn, and a new primitive variable type (boolean). The operators are:

  • && //The AND operator
  • || //The OR operator
  • ! //The NOT operator

Boolean variables can be declared just like other variables, and can have the values "true" or "false". The Java keywords true and false can be used in your programs to set the values of boolean variables. Boolean variables can also be given values from the result of boolean expressions. Consider the statements in the program fragment below. The first one is just declaration and initialization of a couple of integers. You should have those down by now. The second statement is new. It uses the boolean keyword (remember - all Java keywords are lower case!). boolean is a primitive type just like an int or a float. It is a type, however, that can only hold the values true or false. It can't hold numbers, strings of characters, etc. It just represents the values true or false. In fact, as you can see in the 2nd statement, we can initialize a boolean variable to true or false by using the true or false keyword and the assignment operator. So the boolean variable mybool has the value true. We don't know what anotherBool or bool3 will be until the 3rd and 4th statements.

In the 3rd statement, we assign the value "false" to the boolean variable anotherBool.

It just represents the logical concept of "false". The 4th statement below then takes the result of a boolean expression ( x < y ) and assigns it to the bool3 variable. So remember, the boolean operators we are discussing all return either true or false, so the boolean expression x < y returns the value true given the values of x and y in the code below.

int x=5, y=7;
boolean mybool = true, anotherBool, bool3;
anotherBool = false;
bool3 = x < y; //bool3 will now have the value true

So, now that we know what a boolean variable is, consider the condition where we have two boolean variables P and Q. The following table indicates how the AND (&&), OR (||) and NOT (!) operators can operate on them. The first row (besides the title row) shows that if P and Q are both false, then P AND Q is false, P OR Q is false, and NOT P is true (as is NOT Q). So let's look at these operators:

AND (&&) : The && operator is a binary operator that takes two boolean operands. For && to return true, BOTH of the arguments must have the value true. If EITHER of the arguments is false, then && returns false.

OR (||) : The || operator is a binary operator that takes two boolean operands. For || to return true, EITHER or BOTH of the operands must be true. If BOTH are false, then || returns false.

NOT (!): The ! operator is a unary operator that takes one boolean argument. For ! to return true, the operand must be false. If the argument is true, ! returns false.


The table shows how this works for each operator.

You can combine boolean variables in a wide variety of equivalent ways. Consider the folloiwing variable declaration/initialization.

boolean P = true, Q = false;

The expressions (P && Q) , (!P || Q) and (!P && !Q) are all exactly the same: they all are boolean expressions that return false. Can you see why? The table tells you that if P is true and Q is false, then P && Q is false. How about (!P || Q) ? Well, if P is true, then !P is false. So the expression reduces to (false || Q). Since Q is false, then we have (false || false). Since both operands are false, then the || operator returns false. Think about the last expression the same way and make sure you can figure out why the answer is false.



SELECTION : IF AND IF . . . ELSE


The general syntax of the if-else statement is as follows:

if (expression) statement1
else statement2
 if statements may omit the else option which result in one-way selection.
 if (expression) statement;

 If the expression is non-zero, statement is executed, otherwise nothing is executed. The following flowchart illustrates the flow of control.

<!#if !vml#><!#endif#>


3. The full if-else statement allows for two-way control. If the value of the expression is true, statement1 is executed. If the value of the expression equals false, the else option results in statement2 being executed. The following flowchart from handout, H.A.8.2, illustrates the flow of control.

<!#if !vml#><!#endif#>


Compound Statements

  •     The statement executed in a control structure can be a block of statements, grouped together into a single compound statement.
  •     A compound statement is created by enclosing any number of single statements by braces as shown in the following example:

if (expression)

{

statement1;

statement2;

statement3;

}

else

{

statement4;

statement5;

statement6;

}


Multiple Selection : Nested if
In the previous sections,you learned how to imploment one-way and two-way selections in a program.However,some problem require the implementation of more than two alternatives.This particular problem has four alternatives-that is,multiple selection paths.You can include multiple selection paths in a program by using an if . . . else structure-if the action statement itself is an if or if . . else statement.When one control statement is located within another,it is said to be nested.


Conditional Operator (optional)

  C++ provides an alternate method of coding an if-else statement using the conditional operator. This operator is the only ternary operator in C++ as it requires three operands. The general syntax is:


(condition) ? statement1 : statement2;

  •     If the condition is true, statement1 is executed. If the condition is false, statement2 is executed.
  • This is appropriate in situations where the conditions and statements are fairly compact.

int max (int a, int b) // returns the larger of two integers

{

(a > b) ? return a : return b;

}


switch structures
The switch statement allow us to select one from multiple options. It is especially useful when we want to write a code that makes a selection based on an expression or a variable. switch selection structure consists of a series of case label sand optional default case as shown below.



 switch statement works by comparing the value of variable or expression within parentheses with values specified in each case. If there is a match, the statements following the case will be executed. If there is no match occurs, the default statement is executed. At the end of each case, keyword break must be placed to exit from the switch immediately after statements execution.

Comparing string

String are compared character by character,starting with the first character and using the Unicode collating sequence.The character-by-character comparison continues until one of the following three conditions is met; a mismatch is found,the last characters have been compared and are equal,or one string is exhausted.
      


      

























Related Posts Plugin for WordPress, Blogger...