HOW TO PROGRAMMING IN JAVA

It's easy to understand for professional and non professional.

HOW TO PROGRAMMING IN JAVA

It's easy to understand for professional and non professional.

HOW TO PROGRAMMING IN JAVA

It's easy to understand for professional and non professional.

HOW TO PROGRAMMING IN JAVA

It's easy to understand for professional and non professional.

HOW TO PROGRAMMING IN JAVA

It's easy to understand for professional and non professional.

Search

Wednesday, December 26, 2018

Reusing Classes

One of the most compelling features about Java is code reuse. But to be revolutionary, you’ve got to be able to do a lot more than copy code and change it. 


Friday, December 21, 2018

Statements break and continue

The break and continue statements alter the flow of control. The break statement, when executed in a while, for, do/while or switch structure, causes immediate exit from that structure. Execution continues with the first statement after the structure. Common uses of the break statement are to escape early from a loop or skip the remainder of a switch structure . Figure demonstrates the break statement in a for repetition structure. 

 // Using the break statement in a for structure 
 // Java extension packages  
import javax.swing.JOptionPane;
public class BreakTest 
{
 // main method begins execution of Java application
public static void main( String args[] )
{
String output = "";
int count;
 // loop 10 times
for ( count = 1; count <= 10; count++ )
{
// if count is 5, terminate loop         
if ( count == 5 ) 
break;   // break loop only if count == 5     
 output += count + " "; 
 }  // end for structure
 output += "\nBroke out of loop at count = " + count;
 JOptionPane.showMessageDialog( null, output );
System.exit( 0 ); // terminate application 
// end method main 
} // end class BreakTest

When the if structure at line 19 in the for structure detects that count is 5, the break statement at line 20 executes. This statement terminates the for structure, and the program proceeds to line 26 (immediately after the for). Line 26 completes the string to display in a message dialog at line 27. The loop fully executes its body only four times. The continue statement, when executed in a while, for or do/while structure, skips the remaining statements in the loop body and proceeds with the next iteration of the loop. In while and do/while structures, the program evaluates the loop-continuation test immediately after the continue statement executes. In for structures, the increment expression executes, then the program evaluates the loop-continuation test. Earlier, we stated that the while structure could be used in most cases to represent the for structure. The one exception occurs when the increment expression in the while structure follows the continue statement. In this case, the increment does not execute before the program evaluates the repetition-continuation condition, so the while structure does not execute in the same manner as does the for structure. Figure uses the continue statement in a for structure to skip the string concatenation statement (line 22) when the if structure (line 18) determines that the value of count is 5. When the continue statement executes, program control continues with the increment of the control variable in the for structure. 

// Java extension packages
import javax.swing.JOptionPane;
public class ContinueTest 
{
 // main method begins execution of Java application 
public static void main( String args[] )
{
String output = ""; 
 // loop 10 times 
for ( int count = 1; count <= 10; count++ )
{
// if count is 5, continue with next iteration of loop
if ( count == 5 )
continue;
 // skip remaining code in loop  
// only if count == 5 
output += count + " ";
// end for structure  
output += "\nUsed continue to skip printing 5";
JOptionPane.showMessageDialog( null, output );
System.exit( 0 ); // terminate application
}
 // end method main 
}  
// end class ContinueTest


Assignment Operators, Increment and Decrements Operators

Java provides several assignment operators for abbreviating assignment expressions. 
For example, you can abbreviate the statement

c = c + 3; 
with the addition assignment operator, +=, 
as
c += 3;
The += operator adds the value of the expression on the right of the operator to the value of the variable on the left of the operator and stores the result in the variable on the left of the operator. Any statement of the form

variable = variable operator expression;

where operator is one of the binary operators +, -, *, / or % (or others we discuss later in the text), can be written in the form 

variable operator= expression;

Thus, the assignment expression c += 3 adds 3 to c. Figure shows the arithmetic assignment operators, sample expressions using the operators and explanations of what the operators do.


Assignment/operator   Sample expression    Explanation      Assigns                       

Assume: int c = 3, d = 5, e = 4, f = 6, g = 12; 

+=                   c += 7               c = c + 7       10 to c
-=                   d -= 4               d = d - 4       1  to d
*=                   e *= 5               e = e * 5       20 to e
/=                   f /= 3               f = f / 3       2  to f
%=                   g %= 9               g = g % 9       3  to g


Increment and Decrements Operators 

Java provides the unary increment operator, ++, and the unary decrements operator, --, which are summarized in Figure. A program can increment the value of a variable called c by 1 using the increment operator, ++, rather than the expression c=c+1 or c += 1. If an increment or decrement operator is placed before a variable, it is referred to as the preincrement or predecrement operator, respectively. If an increment or decrement operator is placed after a variable, it is referred to as the postincrement or postdecrement operator, respectively. 

Operator         Called                 Sample expression           Explanation                              

++                   preincrement              ++a                              Increment a by 1, then use the                                                                                                  new value of a in the expression                                                                                                in which a resides.                       
++                   postincrement             a++                             Use the current value of a in the                                                                                                expression in which a resides,                                                                                                  then increment a by 1.                
--                     predecrement               --b                             Decrement b by 1, then use the                                                                                                new value of b in the expression                                                                                                in which b resides.                       
 --                    postdecrement               b--                           Use the current value of b in the                                                                                                expression in which b resides,                                                                                                  then decrement b by 1.               

Preincrementing (predecrementing) a variable causes the variable to be incremented (decremented) by 1, and then the new value of the variable is used in the expression in which it appears. Postincrementing (postdecrementing) the variable causes the current value of the variable to be used in the expression in which it appears, and then the variable value is incremented (decremented) by 1. The application in Figure demonstrates the difference between the preincrementing version and the postincrementing version of the ++ increment operator. Postincrementing the variable c causes it to be incremented after it is used in the System.out.println method call (line 13). Preincrementing the variable c causes it to be incremented before it is used in the System.out.println method call (line 20). The program displays the value of c before and after the ++ operator is used. The decrement operator (--) works similarly. 

// Increment.java 
// Preincrementing and postincrementing
public class Increment 
{
// main method begins execution of Java application
public static void main( String args[] ) 
{
int c;
c = 5;
System.out.println( c );   // print 5     
System.out.println( c++ ); // print then 5 postincrement
System.out.println( c );   // print 
System.out.println();      // skip a lin
System.out.println( c );   // print 5 
System.out.println( ++c ); // preincrement then print 6
System.out.println( c );   // print 6 
// end method main 
} // end class Increment

OUTPUT'S
5
6
6

Line 16,
System.out.println();      // skip a line
uses System.out.println to output a blank line. If println receives no arguments, it simply outputs a newline character. The arithmetic assignment operators and the increment and decrement operators can be used to simplify program statements. For example, the three assignment statements in  

(lines 32, 34 and 36),

passes = passes + 1; 
failures = failures + 1; 
student = student + 1;

can be written more concisely with assignment operators as

passes += 1; 
failures += 1; 
student += 1;

with preincrement operators as

++passes; 
++failures; 
++student;

or with postincrement operators as

passes++; 
failures++; 
student++;

It is important to note here that when incrementing or decrementing a variable in a statement by itself, the preincrement and postincrement forms have the same effect, and the predecrement and postdecrement forms have the same effect. It is only when a variable appears in the context of a larger expression that preincrementing and post-incrementing the variable have different effects (and similarly for predecrementing and postdecrementing). 

Common Programming Error                                                                                   
Attempting to use the increment or decrement operator on an expression other than an lvalue is a syntax error. An lvalue is a variable or expression that can  appear on the left side of an assignment operation. For example, writing ++(x + 1) is a syntax error, because (x + 1) is not an lvalue.  

The chart in Fig. 4.15 shows the precedence and associativity of the operators that have been introduced up to this point. The operators are shown from top to bottom in decreasing order of precedence. The second column describes the associativity of the operators at each level of precedence. Notice that the conditional operator (?:), the unary operators increment (++), decrements (--), plus (+), minus (-) and casts and the assignment operators =, +=, -=, *=, /= and %= associate from right to left. All other operators in the operator precedence chart in Fig. 4.15 associate from left to right. The third column names the groups of operators. 

Operators                           Associativity                                   Type                                   



()                                         left to right                                      parentheses                       ++ --                                    right to left                                      unary postfix                     ++ -- +  - (type)                   right to left                                      unary                                  *  /  %                                  left to right                                      multiplicative                     +  -                                      left to right                                      additive                               <  <= >  >=                          left to right                                      relational                            == !=                                   left to right                                      equality                              ?:                                        right to left                                      conditional                         =  += -= *= /= %=                right to left                                      assignment                        



The while Repetition Structure

A repetition structure allows the programmer to specify that an action is to be repeated while some condition remains true. The pseudo-code statement While there are more items on my shopping list Purchase next item and cross it off my list describes the repetition that occurs during a shopping trip. The condition “there are more items on my shopping list” may be true or false. If it is true, then the action “Purchase next item and cross it off my list” is performed. This action will be performed repeatedly while the condition remains true. The statement(s) contained in the while repetition structure constitute the body of the while structure.The body of the while structure may be a single statement or a block. Eventually, the condition will become false (when the last item on the shopping list has been purchased and crossed off the list). At this point, the repetition terminates, and the first pseudo-code statement after the repetition structure is executed.

          Common Programming Error 
Not providing in the body of a while structure an action that eventually causes the condition in the while to become false is a logic error. Normally, such a repetition structure will never terminate—an error called an infinite loop.Spelling the keyword while with an uppercase W, as in While, is a syntax error. (Remember that Java is a case-sensitive language.) All of Java’s reserved keywords, such as while, if and else, contain only lowercase letters.

As an example of a while structure, consider a program segment designed to find the first power of 2 larger than 1000. Suppose that the int variable product has been initialized to 2. When the following while structure finishes executing, product contains the result:
int product = 2;
while ( product <= 1000 )   
product = 2 * product;
The flowchart illustrates the flow of control of the preceding while repetition structure. Once again, note that, besides small circles and arrows, the flowchart contains only a rectangle symbol and a diamond symbol. Imagine, again, a deep bin of empty while structures that may be stacked and nested with other control structures to form a structured implementation of an algorithm’s flow of control. The empty rectangles and diamonds are then filled in with appropriate actions and decisions. The flowchart clearly shows the repetition. The flow line emerging from the rectangle wraps back to the decision, which is tested each time through the loop until the decision eventually becomes false. At this point, the while structure is exited, and control passes to the next statement in the program. When the while structure is entered, product is 2. Variable product is repeatedly multiplied by 2, taking on the values 4, 8, 16, 32, 64, 128, 256, 512 and 1024 successively. When product becomes 1024, the condition product <= 1000 in the while structure becomes false. This result terminates the repetition, with 1024 as product’s final value. Execution continues with the next statement after the while. 
[Note: If a while structure’s condition is  initially false, the body statement(s) will never be performed.]
To illustrate how algorithms are developed, we solve several variations of a class-averaging problem. Consider the following problem statement: A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz. The class average is equal to the sum of the grades divided by the number of students. The algorithm for solving this problem on a computer must input each of the grades, perform the averaging calculation and print the result.
Let us use pseudo-code to list the actions to be executed and specify the order in which these actions should be executed. We use counter-controlled repetition to input the grades one at a time. This technique uses a variable called a counter to control the number of times a set of statements will execute. In this example, repetition terminates when the counter exceeds 10. In this section, we present a pseudo-code algorithm and the corresponding program to solve this problem using counter-controlled repetition. In the next section, we show how pseudo-code algorithms are developed. Counter-controlled repetition is often called definite repetition, because the number of repetitions is known before the loop begins executing. Note the references in the algorithm to a total and a counter. A total is a variable used to accumulate the sum of a series of values. A counter is a variable used to count—in this case, to count the number of grades entered. Variables used to store totals should normally be initialized to zero before being used in a program; otherwise, the sum would include the previous value stored in the total’s memory location. 

Class average program with counter-controlled repetition. 

    // Java extension packages 5 import 
javax.swing.JOptionPane;
 public class Average 
{      
// main method begins execution of Java application 
public static void main( String args[] ) 
{
int total,                   
// sum of grades input by user 
gradeCounter,          
// number of grades entered 
gradeValue,              
// grade value 
average;
// average of all grades    
String grade;
// grade typed by user 
// Initialization Phase 
total = 0;
// clear total      
gradeCounter = 1;
// prepare to loop     
// Processing Phase     
 while ( gradeCounter <= 10 ) 
{
// loop 10 times         
// prompt for input and read grade from user         
grade = JOptionPane.showInputDialog("Enter integer grade: " );      
// convert grade from a String to an integer         
gradeValue = Integer.parseInt( grade );
// add gradeValue to total         
total = total + gradeValue;         
// add 1 to gradeCounter      
gradeCounter = gradeCounter + 1;    }  
// end while structure     
// Termination Phase      
average = total / 10; 
// perform integer division     
// display average of exam grades     
JOptionPane.showMessageDialog( null,"Class average is " + average, "Class Average",         JOptionPane.INFORMATION_MESSAGE );   
System.exit( 0 ); 
// terminate the program } 
// end method main  
// end class Average1

         OUTPUT



The if/else Selection Structure

The if selection structure performs an indicated action only when the given condition evaluates to true; otherwise, the action is skipped. The if/else selection structure allows the programmer to specify that a different action is to be performed when the condition is true rather than when the condition is false. For example, the pseudo-code statement If student’s grade is greater than or equal to 60 Print “Passed” else Print “Failed” prints Passed if the student’s grade is greater than or equal to 60 and prints Failed if the student’s grade is less than 60. In either case, after printing occurs, the next pseudo-code statement in sequence is “performed.” Note that the body of the else is also indented.
The indentation convention you choose should be carefully applied throughout your programs. It is difficult to read programs that do not use uniform spacing conventions. The preceding pseudo-code If/else structure may be written in Java as

if ( studentGrade >= 60 )    
System.out.println( "Passed" ); 
else   System.out.println( "Failed" ); 

The flowchart nicely illustrates the flow of control in an if/else structure. Once again, note that, besides small circles and arrows, the only symbols in the flowchart are rectangles (for actions) and a diamond (for a decision). We continue to emphasize this action/decision model of computing. Imagine again a deep bin containing as many empty double-selection structures as might be needed to build a Java algorithm. The programmer’s job is to assemble the selection structures (by stacking and nesting) with other control structures required by the algorithm and to fill in the empty rectangles and empty diamonds with actions and decisions appropriate to the algorithm being implemented. 
The conditional operator (?:) is related to the if/else structure. ?: is Java’s only ternary operator—it takes three operands. The operands together with ?: form a conditional expression. The first operand is a Boolean expression, the second is the value for the conditional expression if the condition evaluates to true and the third is the value for the conditional expression if the condition evaluates to false. For example, the statement

System.out.println( studentGrade >= 60 ? "Passed" : "Failed" ); 

contains a conditional expression that evaluates to the string "Passed" if the condition studentGrade>=60 is true and to the string "Failed" if the condition is false. Thus, this statement with the conditional operator performs essentially the same function as the if/else statement given previously. The precedence of the conditional operator is low, so the entire conditional expression is normally placed in parentheses. We will see that conditional operators can be used in some situations where if/else statements cannot. 
Nested if/else structures test for multiple cases by placing if/else structures inside if/else structures. For example, the following pseudo-code statement prints A for exam grades greater than or equal to 90, B for grades in the range 80 to 89, C for grades in the range 70 to 79, D for grades in the range 60 to 69 and F for all other grades: If student’s grade is greater than or equal to 90 Print “A” else If student’s grade is greater than or equal to 80 Print “B” else If student’s grade is greater than or equal to 70 Print “C” else If student’s grade is greater than or equal to 60 Print “D” else Print “F” This pseudo-code may be written in Java as

if ( studentGrade >= 90 )   
System.out.println( "A" ); 
else if ( studentGrade >= 80 )      
System.out.println( "B" ); 
else      
if ( studentGrade >= 70 )         
System.out.println( "C" );      
else
         if ( studentGrade >= 60 )            
System.out.println( "D" );         
else
System.out.println( "F" );

If student Grade is greater than or equal to 90, the first four conditions will be true, but only the System.out.println statement after the first test will be executed. After that particular System.out.println is executed, the else part of the “outer” if/else statement is skipped.

Most Java programmers prefer to write the preceding if structure as 

if ( grade >= 90 )   
System.out.println( "A" ); 
else 
if ( grade >= 80 )   
System.out.println( "B" ); 
else if ( grade >= 70 )   
System.out.println( "C" ); 
else
 if ( grade >= 60 )   
System.out.println( "D" ); 
else   
System.out.println( "F" );

Both forms are equivalent. The latter form is popular because it avoids the deep indentation of the code to the right. Such deep indentation often leaves little room on a line, forcing lines to be split and decreasing program readability. It is important to note that the Java compiler always associates an else with the previous if unless told to do otherwise by the placement of braces ({}). This attribute is referred to as the dangling-else problem. For example,

if ( x > 5 ) if ( y > 5 )      
System.out.println( "x and y are > 5" ); 
else   
System.out.println( "x is <= 5" ); 

appears to indicate that if x is greater than 5, the if structure in its body determines if y is also greater than 5. If so, the string "x and y are > 5" is output. Otherwise, it appears that if x is not greater than 5, the else part of the if/else structure outputs the string "x is <= 5". Beware! The preceding nested if structure does not execute as it would appear to. The compiler actually interprets the preceding structure as 

if ( x > 5 ) if ( y > 5 )      
System.out.println( "x and y are > 5" ); 
else      
System.out.println( "x is <= 5" );

in which the body of the first if structure is an if/else structure. This structure tests if x is greater than 5. If so, execution continues by testing if y is also greater than 5. If the second condition is true, the proper string—"x and y are > 5"—is displayed. However, if the second condition is false, the string "x is <= 5" is displayed, even though we know that x is greater than 5.

To force the preceding nested if structure to execute as it was originally intended, the structure must be written as follows:

if ( x > 5 ) 
{
 if ( y > 5 )      
System.out.println( "x and y are > 5" ); 
}
 else   
System.out.println( "x is <= 5" );

The braces ({}) indicate to the compiler that the second if structure is in the body of the first if structure and that the else is matched with the first if structure. In Exercise 4.21 and Exercise 4.22, you will investigate the dangling-else problem further. The if selection structure normally expects only one statement in its body. To include several statements in the body of an if structure, enclose the statements in braces ({ and }). A set of statements contained within a pair of braces is called a block. 

The following example includes a block in the else part of an if/else structure:

if ( grade >= 60 )   
System.out.println( "Passed" ); 
else 
{
System.out.println( "Failed" );   
System.out.println( "You must take this course again." ); 
}

In this case, if grade is less than 60, the program executes both statements in the body of the else and prints
Failed. You must take this course again.
Notice the braces surrounding the two statements in the else clause. These braces are important. Without the braces, the statement

System.out.println( "You must take this course again." );

would be outside the body of the else part of the if structure and would execute regardless of whether the grade is less than 60.

Friday, December 14, 2018

Reference Variables and Assignment

In an assignment operation, object reference variables act differently than do variables of a primitive type, such as int. When you assign one primitive-type variable to another, the situation is straightforward. The variable on the left receives a copy of the value of the variable on the right. When you assign an object reference variable to another, the situation is a bit more complicated because you are changing the object that the reference variable refers to. The effect of this difference can cause some counter intuitive results. For example,consider the following fragment:

Vehicle car1 = new Vehicle();
Vehicle car2 = car1;
At first glance, it is easy to think that car 1 and car 2 refer to different objects, but this is not the case. Instead, car 1 and car 2 will both refer to the same object. The assignment of car 1 to car 2 simply makes car 2 refer to the same object as does car 1. Thus, the object can be acted upon by either car 1 or car 2. For example, after the assignment
car 1. mpg = 26;
executes, both of the seprintln( )statements
System.out.println(car1.mpg);
System.out.println(car2.mpg);
display the same value: 26. Although car 1 and car 2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to car 2 simply changes the object to which car 2 refers. For example:
Vehicle car1 = new Vehicle();
Vehicle car2 = car1;
Vehicle car3 = new Vehicle();
car2 = car3;
// now car2 and car3 refer to the same object.
After this sequence executes, car 2 refers to the same object as car 3. The object referred to by car 1 is unchanged.