Programming I

From Studyplace

Jump to: navigation, search

Contents

Reading Resources

Delicious/paulccnmtl/Java

bookmarks tagged Java by paulccnmtl

Java Environment / Architecture

  • Java source code (.java): Source code is stored on a disk in a file with a name ending in .java.
  • Java Compiler: creates bytecodes that are stored on a disk in a file with a named ending in .class.
  • Java Virtual Machine (Java Interpreter): JVM (named java.exe) performs security checks and translates bytecodes to machine language, which executes.

Terms

Programming Structures

Sequence Structure

Sequence structure, simply put, is when “one step follows another unconditionally”

Decision Structure

Decision structures involve “choosing between alternative courses of action based on some value within a program”

Algorithm

An algorithm describes how a problem is solved in terms of the actions to be executed, and it specifies the order in which the actions should be executed. Algorithms can help the programmer plan a program before writing it in a programming language. Example:

  1. Read in the radius.
  2. Compute the area using the following formula: area = radius x radius x p
  3. Display the area.

<source lang=java> public class ComputeArea {

 public static void main(String[] args) {
   // Step 1: Read in radius
   // Step 2: Compute area
   // Step 3: Display the area
 }

} </source>

Block and Scope

Within any class or method, the code between a pair of curly braces is called a block. When you declare a variable within a block, you cannot refer to that variable outside the block. The portion of a program within which you can refer to a variable is the variable’s scope.

Data Structures

Many of the problems you will meet when taking an introductory course in programming using this text can be described with simple, straightforward algorithms. As your education progresses, and you take courses on data structures or on algorithm design and analysis, you will encounter complex problems that require sophisticated solutions. You will need to design accurate, efficient algorithms with appropriate data structures in order to solve such problems.


Primitive Data Types

Data structures involve data representation and manipulation. Java provides data types for representing integers, floating-point numbers (i.e., numbers with a decimal point), characters, and Boolean types. These types are known as primitive data types.

Java provides four integer types (byte, short, int, long) that represent integers of four different sizes, and two floating-point types (float, double) that represent floating-point numbers of two different precisions. Character type (char) represents a single character. These are called primitive data types. Java's primitive types are portable across all computer platforms. They have exactly the same values on all platforms. When they are declared, the variables of these types are created and assigned memory space.

Advanced Data Type

Some advanced data structures, such as stacks, sets, and lists, have built-in implementation in Java.

Reference Types

Java also supports array and string types as objects or reference types.

Integers

Java uses four types for integers: byte, short, int, and long. Choose the type that is most appropriate for your variable. For example, if you know an integer stored in a variable is within a range of byte, declare the variable as a byte.

Floating-Point

Java uses two types for floating-point numbers: float and double. The double type is twice as big as float. So, the double is known as double precision, while float is known as single precision. Normally, you should use the double type because it is more accurate than the float type.

Numeric Operators

The operators for numeric data types include the standard arithmetic operators: addition (+), subtraction (–), multiplication (*), division (/), and remainder (%)

Numeric Literals

A literal is a constant value that appears directly in a program. For example, 34, 1000000, and 5.0 are literals in the following statements:

<source lang=java> int i = 34; long k = 1000000; double d = 5.0; </source>

Integer Literal

An integer literal can be assigned to an integer variable as long as it can fit into the variable. A compilation error would occur if the literal were too large for the variable to hold. The statement byte b = 128, for example, would cause a compilation error, because 128 cannot be stored in a variable of the byte type. (Note that the range for a byte value is from — to 127.)

An integer literal is assumed to be of the int type, whose value is between –231 (—2147483648) and 231–1 (2147483647). The statement System.out.println (2147483648), for example, would cause a compilation error, because 2147483648 is too long as an int value.

Floating-point Literal

Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double type value. For example, 5.0 is considered a double value, not a float value. You can make a number a float by appending the letter f or F, and you can make a number a double by appending the letter d or D. For example, you can use 100.2f or 100.2F for a float number, and 100.2d or 100.2D for a double number.

Increment / Decrement

Increment and Decrement Operators
Operator Name Description
++var preincrement The expression (++var) increments var by 1 and evaluates to the new value in var after the increment.
var++ postincrement The expression (var++) evaluates to the original value in var and increments var by 1.
--var predecrement The expression (––var) decrements var by 1 and evaluates to the new value in var after the decrement.
var-- postdecrement The expression (var––) evaluates to the original value in var and decrements var by 1.

If the operator is before (prefixed to) the variable, the variable is incremented or decremented by 1, then the new value of the variable is returned. If the operator is after (suffixed to) the variable, the original old value of the variable is returned, then the variable is incremented or decremented by 1. Therefore, the prefixes ++x and --x are referred to, respectively, as the preincrement operator and the predecrement operator; and the suffixes x++ and x–– are referred to, respectively, as the postincrement operator and the postdecrement operator. The prefix form of ++ (or --) and the suffix form of ++ (or --) are the same if they are used in isolation, but they cause different effects when used in an expression.


  • ++loopCount;
  • loopCount++;
  • loopCount = loopCount +1;
  • loopCount += 1;

Type Casting

Casting a variable of a type with a small range to a variable of a type with a larger range is known as widening a type. Casting a variable of a type with a large range to a variable of a type with a smaller range is known as narrowing a type. Widening a type can be performed automatically without explicit casting. Narrowing a type must be performed explicitly.

The syntax for casting gives the target type in parentheses, followed by the variable's name or the value to be cast. For example:

<source lang=java> float f = (float)10.1; int i = (int)f;

(Liang 40) </source>

In the first line, the double value 10.1 is cast into float. In the second line, i has a value of 10; the fractional part in f is truncated.

Character Data Type and Operations

The character data type, char, is used to represent a single character. A character literal is enclosed in single quotation marks. Consider the following code:

<source lang=java> char letter = 'A'; char numChar = '4'; </source>

A string literal must be enclosed in quotation marks. A character literal is a single character enclosed in single quotation marks. So "A" is a string, and 'A' is a character.

Unicode and ASCII Code

You can use ASCII characters like 'X', '1', and '$' in a Java program as well as Unicodes. Thus, for example, the following statements are equivalent:

<source lang=java> char letter = 'A'; char letter = '\u0041'; // Character A's Unicode is 0041 </source>

The increment and decrement operators can also be used on char variables to get the next or preceding Unicode character. For example, the following statements display character b.

<source lang=java> char ch = 'a'; System.out.println(++ch); </source>

(Liang 42)

String Type

The char type only represents one character. To represent a string of characters, use the data type called String. For example, the following code declares the message to be a string that has an initial value of "Welcome to Java".

String message = "Welcome to Java";

String is a reference type.

If neither of the operands is a string, the plus sign (+) is the addition operator that adds two numbers.

The shorthand += operator can also be used for string concatenation. For example, the following code appends the string "and Java is fun" with the string "Welcome to Java" in message.

message += " and Java is fun";

So the new message is "Welcome to Java and Java is fun".

Suppose that i = 1 and j = 2, what is the output of the following statement?

System.out.println("i + j is " + (i + j);


The output is "i + j is 12" because "i + j is " is concatenated with the value of i first. To force i + j to be executed first, enclose i + j in the parentheses, as follows:

System.out.println("i + j is " + (i + j));

Applet

  • Java programs that run from a Web browser are called applets.

Java servlets or JavaServer Pages (JSP)

  • May be run from a Web server to generate dynamic Web pages.

Class Loader

  • When executing a Java program, the JVM first loads the bytecode of the class to memory using a program called the class loader.

Bytecode Verifier

  • After a class is loaded, the JVM uses a program called bytecode verifier to check the validity of the bytecode and ensure that the bytecode does not violate Java's security restrictions. Java enforces strict security to make sure that Java programs arriving from the network do not harm your computer.

Comments and Javadoc Comments

  • In addition to the two comment styles, // and /*, Java supports comments of a special type, referred to as javadoc comments. javadoc comments begin with /** and end with */. They are used for documenting classes, data, and methods. They can be extracted into an HTML file using JDK's javadoc command. For more information, see java.sun.com/j2se/javadoc.

Naming Conventions

  • Variables, fields, and methods begin with a lower case letter.
  • Classes and Interfaces begin with an uppercase letter.
  • Named constants (that is, final variables and fields) are written entirely in uppercase, and the parts of composite names are separated by underscores (_). Examples: CENTER, MAX_VALUE.
  • Package names are sequences of dot-separated lowercase names. Examples: java.awt.event. For uniqueness, they are often prefixed with reverse domain names, as in com.sun.xml.util.

Make sure that you choose descriptive names with straightforward meanings for the variables, constants, classes, and methods in your program. Names are case-sensitive. Listed below are the conventions for naming variables, methods, and classes.

  • Use lowercase for variables and methods. If a name consists of several words, concatenate them into one, making the first word lowercase and capitalizing the first letter of each subsequent word; for example, the variables radius and area and the method showInputDialog.
  • Capitalize the first letter of each word in a class name; for example, the class names ComputeArea, Math, and JOptionPane.
  • Capitalize every letter in a constant, and use underscores between words; for example, the constants PI and MAX_VALUE.

Reserved/Keywords

  • Reserved words, or keywords, are words that have a specific meaning to the compiler and cannot be used for other purposes in the program. For example, when the compiler sees the word class, it understands that the word after class is the name for the class. Other reserved words are public, static, void and others.

Modifiers

  • Java uses certain reserved words called modifiers that specify the properties of the data, methods, and classes and how they can be used. Examples of modifiers are public and static. Other modifiers are private, final, abstract, and protected. A public datum, method, or class can be accessed by other classes. A private datum or method cannot be accessed by other classes.

Statements

  • A statement represents an action or a sequence of actions. The statement System.out.println("Welcome to Java!"); in the program in Listing 1.1 is a statement to display the greeting "Welcome to Java!" Every statement in Java ends with a semicolon (;).

Blocks

  • The braces in the program form a block that groups the components of the program. In Java, each block begins with an opening brace ({) and ends with a closing brace (}). Every class has a class block that groups the data and methods of the class. Every method has a method block that groups the statements in the method. Blocks can be nested, meaning that one block can be placed within another.

Concatenating Strings

The plus sign (+) has two meanings: one for addition and the other for concatenating strings.

Identifiers

Programming languages use special symbols called identifiers to name such programming entities as variables, constants, methods, classes, and packages. Here are the rules for naming identifiers:

  • An identifier is a sequence of characters that consists of letters, digits, underscores (_), and dollar signs ($).
  • An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit.
  • An identifier cannot be a reserved word.
  • An identifier cannot be true, false, or null.
  • An identifier can be of any length.
  • Do not name identifiers with the $ character. By convention, the $ character should be used only in mechanically generated source code.

Java Anatomy

Every Java program is a set of class definitions. The keyword class introduces a class definition. The contents of the class are included in a block. A block begins with an opening brace and ends with a closing brace Methods are contained in a class.

Classes

  • In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.
  • Every Java program must have at least one class. A class is a construct that defines data and methods. Each class has a name. By convention, class names start with an uppercase letter. In order to run a class, the class must contain a method named main. The JVM executes the program by invoking the main method. (Liang 17)

Inheritance

Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses

Integer Class

Converting String into Int

The input returned from the input dialog box is a string. If you enter a numeric value such as 123, it returns "123". You have to convert a string into a number to obtain the input as a number.

To convert a string into an int value, use the parseInt method in the Integer class, as follows:

<source lang=java> int intValue = Integer.parseInt(intString); </source>


where intString is a numeric string such as "123".

To convert a string into a double value, use the parseDouble method in the Double class, as follows:

<source lang=java> double doubleValue = Double.parseDouble(doubleString); </source>

<source lang=java> where doubleString is a numeric string such as "123.45". </source>

The Integer and Double classes are both included in the java.lang package, and thus are automatically imported.

Scanner Class

Scanner API

Console input is not directly supported in Java, but you can use the Scanner class to create an object to read input from System.in, as follows:

<source lang=java> Scanner scanner = new Scanner(System.in);</source>

Scanner is a new class in JDK 1.5. The syntax new Scanner(System.in) creates an object of the Scanner type. The syntax Scanner scanner declares that scanner is a variable whose type is Scanner. The whole line Scanner scanner = new Scanner(System.in) creates a Scanner object and assigns its reference to the variable scanner. An object may contain methods. Invoking a method on an object is to ask the object to perform a task. A Scanner object contains the following methods for reading an input:

  • next(): reading a string. A string is delimited by spaces.
  • nextByte(): reading an integer of the byte type.
  • nextShort(): reading an integer of the short type.
  • nextInt(): reading an integer of the int type.
  • nextLong(): reading an integer of the long type.
  • nextFloat(): reading a number of the float type.
  • nextDouble(): reading a number of the double type.

For example, the following statements prompt the user to enter a double value from the console.

<source lang=java> System.out.print("Enter a double value: "); Scanner scanner = new Scanner(System.in); double d = scanner.nextDouble(); </source>

One benefit of using the console input is that you can store the input values in a text file and pass the file from the command line using the following command:

java TestScanner < input.txt


where input.txt is a text file that contains the data. You can also save the output into a file using the following command:

java TestScanner < input.txt > out.txt

Objects

Objects Explained by Sun

Objects are instances of a class and contain states (data) and behaviors (operations on data)

Class: Cat

  • Object: Siamese
  • Object: Maine Coon

Class: Purchase

  • Object: Ebay Purchase
  • Object: Target Purchase (class notes)

Objects are instances of a class and contain: data, operations on data; nouns and verbs; or variables and methods.

Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.

Variables

  • Variables are used to store data and computational results in the program.
  • Every variable has a name, a type, a size, and a value.

Variable Declaration

To use a variable, you declare it by telling the compiler the name of the variable as well as what type of data it represents. This is called a variable declaration. Declaring a variable tells the compiler to allocate appropriate memory space for the variable based on its data type. The syntax for declaring a variable is:

datatype variableName;

examples:

  • int x; // Declare x to be an integer variable;
  • double radius; // Declare radius to be a double variable;
  • double interestRate; // Declare interestRate to be a double variable;
  • char a; // Declare a to be a character variable;

For variables are of the same type, they can be declared together, as follows: datatype variable1, variable2, ..., variablen;

By convention, variable names are in lowercase. If a name consists of several words, concatenate all of them and capitalize the first letter of each word except the first.

Variable declarations are composed of three components, in order:

  • Zero or more modifiers, such as public or private.
  • The variable’s type.
  • The variable’s name.

Instance Variables

Member variables created inside a class.

Local Variables

Variables created in a method or block of code.

Parameters

Variables in method declaration.

Assignment Statement and Assignment Expressions

After a variable is declared, you can assign a value to it by using an assignment statement. In Java, the equal sign (=) is used as the assignment operator. The syntax for assignment statements is as follows:

variable = expression;

<source lang=java> nt x = 1; // Assign 1 to variable x; double radius = 1.0; // Assign 1.0 to variable radius; x = 5 * (3 / 2) + 3 * 2; // Assign the value of the expression to x; x = y + 1; // Assign the addition of y and 1 to x; area = radius * radius * 3.14159; // Compute area


A variable can also be used in an expression. For example,

x = x + 1; </source>

In Java, an assignment statement can also be treated as an expression that evaluates to the value being assigned to the variable on the left-hand side of the assignment operator. For this reason, an assignment statement is also known as an assignment expression. For example, the following statement is correct:

<source lang=java>

System.out.println(x = 1);


which is equivalent to

x = 1; System.out.println(x);


The following statement is also correct:

i = j = k = 1;

</source>

Constants

The value of a variable may change during the execution of the program, but a constant represents permanent data that never changes.

Here is the syntax for declaring a constant:

final datatype CONSTANTNAME = VALUE;

<source lang=java>final double PI = 3.14159; // Declare a constant</source>

By convention, constants are named in uppercase: PI, not pi or Pi.

There are three benefits of using constants: (1) you don't have to repeatedly type the same value; (2) the value can be changed in a single location if necessary; (3) a descriptive name for a constant makes the program easy to read.

Methods

  • A method is a construct that contains statements.
  • In general, a method has the following syntax:

<source lang=java> modifier returnValueType methodName(list of parameters) {

 // Method body;

}</source>

  • What is System.out.println? System.out is known as the standard output object. println is a method in the object, which consists of a collection of statements that perform a sequence of operations to display a message to the standard output device. If you run the program from the command window, the output from the System.out.println is displayed in the command window. The method can be used even without fully understanding the details of how it works. It is used by invoking a statement with a string argument. The string argument is enclosed in parentheses. In this case, the argument is "Welcome to Java!" You can call the same println method with a different argument to print a different message.

Example method header:

  • public returnType methodName(parameters aka what is needed in order for the method to execute)
  • public String getBreed()
  • public void setWeight(double dogWeight)

(class notes)

Method Declaration

Consists of a method header and method body.

Method Header

The method header specifies the modifiers, return value type, method name, and parameters of the method.

Method Body

The method body contains a collection of statements that define what the method does. A return statement using the keyword return is required for a nonvoid method to return a result. The method terminates when a return statement is executed.

Modifiers

The modifier, which is optional, tells the compiler how to call the method. "Static" is an example of a modifier.

Void Method (Procedure)

For example, the returnValueType in the main method is void, as well as in System.exit, System.out.println, and JOptionPane.showMessageDialog. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void. The method that does not return a value is called a void method. A method with a void return value type is called a procedure.

Nonvoid Method (Function)

A method may return a value. The returnValueType is the data type of the value the method returns. The method that returns a value is called a nonvoid method. A method with a nonvoid return value type is called a function.

Parameters

The variables defined in the method header are known as formal parameters or simply parameters. A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. The method name and the parameter list together constitute the method signature. Parameters are optional; that is, a method may contain no parameters.

Passing Parameters by Values

When you invoke a method with a parameter, the value of the argument is passed to the parameter. This is referred to as pass-by-value. If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter. The variable is not affected, regardless of the changes made to the parameter inside the method. We will examine an interesting scenario in the following example, in which the parameters are changed in the method but the arguments are not affected.

Method Invocation

In creating a method, you give a definition of what the method is to do. To use a method, you have to call or invoke it. There are two ways to call a method; the choice is based on whether the method returns a value or not.

When a program calls a method, program control is transferred to the called method. A called method returns control to the caller when its return statement is executed or when its method-ending closing brace is reached (Liang 131-134).

If the method returns a value, a call to the method is usually treated as a value. For example,

<source lang=java>int larger = max(3, 4);</source>


calls max(3, 4) and assigns the result of the method to the variable larger. Another example of a call that is treated as a value is

<source lang=java> System.out.println(max(3, 4)); </source>


which prints the return value of the method call max(3, 4).

If the method returns void, a call to the method must be a statement. For example, the method println returns void. The following call is a statement:

<source lang=java> System.out.println("Welcome to Java!");</source>

ClassName.methodName

One of the benefits of methods is for reuse. The max method can be invoked from any class. If you create a new class you can invoke the max method using ClassName.methodName

Method Overloading

The max method that was used earlier works only with the int data type. But what if you need to find which of two floating-point numbers has the maximum value? The solution is to create another method with the same name but different parameters, as shown in the following code:

<source lang=java> /** Return the max between two int values */

public static int max(int num1, int num2) {
    if (num1 > num2)
       return num1;
     else
       return num2;
   }
   /** Find the max between two double values */
   public static double max(double num1, double num2) {
     if (num1 > num2)
       return num1;
     else
       return num2;
   }
   /** Return the max among three double values */
   public static double max(double num1, double num2, double num3) {
     return max(max(num1, num2), num3);
  }
 }

(Liang 137-138)</source>

If you call max with int parameters, the max method that expects int parameters will be invoked; if you call max with double parameters, the max method that expects double parameters will be invoked. This is referred to as method overloading; that is, two methods have the same name but different parameter lists within one class. The Java compiler determines which method is used based on the method signature.

Main Method

Every Java application must have a user-declared main method that defines where the program execution begins. The JVM executes the application by invoking the main method. The main method looks like this:

<source lang=java> public static void main(String[] args) {

 // Statements;

} </source>

Constructor

Constructors are special methods that construct objects, initialize them with parameters, and return a reference to the newly-constructed objects. new is the Java operator that creates an object

<source lang=java> Public ClassName(parameters) I. Constructors for Class Cat public Cat() public Cat(String breedName) II. Calling these constructors new Cat() new Cat(“Maine Coon”) </source>

Static Method

Such a method should be invoked by using the class name followed by a dot operator (.) and the method name with arguments.

showMessageDialog method

<source lang=java> JOptionPane.showMessageDialog(null, "Welcome to Java!",

   "Display Message", JOptionPane.INFORMATION_MESSAGE);

</source>

Above: The first argument can always be null. The second argument can be a string for text to be displayed. The third argument is the title of the message box. The fourth argument can be JOptionPane.INFORMATION_MESSAGE, which causes the icon (i) to be displayed in the message box.


There are several ways to use the showMessageDialog method. For the time being, all you need to know are two ways to invoke it. One is to use a statement, as shown in the example:

JOptionPane.showMessageDialog(null, x, y, JOptionPane.INFORMATION_MESSAGE);


where x is a string for the text to be displayed, and y is a string for the title of the message box. The other is to use a statement like this one:

JOptionPane.showMessageDialog(null, x);


where x is a string for the text to be displayed.

(Liang 23)

Instance Methods

Instance methods operate on an object, and do not use the static keyword.

A method that doesn't use variables other than parameters should be declared static. If the static keyword is omitted, the method will be an instance method.

<source lang=java> Instance method: public void setEmpNum(int emp) { empNum = emp; } </source>


Class Method

Class methods use the static keyword and do not need an object instance in order to be used.

<source lang=java> public static void personalStatement() { System.out.println(“This is my personal statement…”); } </source>

Loops

  • A special input value, known as a sentinel value, signifies the end of the loop. (Liang 99)
  • The part of the loop that contains the statements to be repeated is called the loop body. A one-time execution of a loop body is referred to as an iteration of the loop.
  • The while loop and for loop are called pre-test loops because the continuation condition is checked before the loop body is executed. The do-while loop is called a post-test loop because the condition is checked after the loop body is executed. The three forms of loop statements, while, do-while, and for, are expressively equivalent; that is, you can write a loop in any of these three forms.

<source lang=java> for (Initialization; Condition; Update) { Statements }</source>

  • Initialization: Set at the outset, this is executed once when the program first reaches the for loop.
  • Condition: Tested each time the for loop completes (at the start of each iteration).
  • Update: Evaluated several times (at the end of each iteration).

While

  • A compound statement, including blocks of statements between curly braces. The individual statements between the curly braces compound to behave as one large statement. (Burd 200)
  • Used when you want the computer to repeat several smaller statements over and over again. To repeat several statements you combine those statements into one big statement.

For Loop

With the while statement, the condition must be altered in the body of the loop. If, however, we want the statement to handle how many times to loop (definite loop), then a for loop statements should be used

<source lang=java> for (Initialization; Condition; Update) { Statements } </source>

Unlike the while loop, where the statement must change the value for the condition; the for loop statement handles these values in the parenthesis. (Class Notes)


In general, the syntax of a for loop is as shown below: <source lang=java> for (initial-action; loop-continuation-condition;

    action-after-each-iteration) {
 // Loop body;
 Statement(s);

} </source> A for loop can be used to simplify: <source lang=java> for (i = initialValue; i < endValue; i++) {

 // Loop body
 ...

} (Laing 102)</source>

A for loop generally uses a variable to control how many times the loop body is executed and when the loop terminates. This variable is referred to as a control variable. The initial-action often initializes a control variable, the action-after-each-iteration usually increments or decrements the control variable, and the loop-continuation-condition tests whether the control variable has reached a termination value.

Control Variable

A for loop generally uses a variable to control how many times the loop body is executed and when the loop terminates. This variable is referred to as a control variable. The initial-action often initializes a control variable, the action-after-each-iteration usually increments or decrements the control variable, and the loop-continuation-condition tests whether the control variable has reached a termination value. For example, the following for loop prints "Welcome to Java!" a hundred times: <source lang=java> int i; for (i = 0; i < 100; i++) {

 System.out.println("Welcome to Java!");

} </source>

The control variable must always be declared inside the control structure of the loop or before the loop. If the loop control variable is used only in the loop, and not elsewhere, it is good programming practice to declare it in the initial-action of the for loop. If the variable is declared inside the loop control structure, it cannot be referenced outside the loop. For example, you cannot reference i outside the for loop in the preceding code, because it is declared inside the for loop.

Do-While

  • The do-while loop is a variation of the while loop. Its syntax is given below:

<source lang=java> do {

 // Loop body;
 Statement(s);

} while (loop-continuation-condition); (Laing 100) </source> This loop statement "checks the value of the loop control variable at the bottom of the loop after one repetition has occurred."

Use the loop statement that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message a hundred times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before the continuation condition is tested.

Iteration

  • The repetition of a sequence or statement in a loop.
  • When a loop cycles through a loop body it is said to 'iterate' through the loop. While and do...while loops do not explicitly determine the number of iterations the loop may complete whereas the for loop includes the finite number of loops in its condition. (Class Notes)

Nesting

  • With all of these looping constructs, you can next one loop within another. If, for example, you wanted a while loop within another while loop, then the outer loop would complete only when the inner evaluated to true. (Class Notes)
  • Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is repeated, the inner loops are reentered, and started anew. (Liang 105)

Key Commands

  • Ctrl+C stops the execution of a runaway program. (Burd 205)

Escape Sequences

  • \b Backspace \u0008
  • \t Tab \u0009
  • \n Linefeed--Moves Cursor to a new line \u000A
  • \f Formfeed \u000C
  • \r Carriage Return \u000D
  • \\ Backslash \u005C
  • \' Single Quote \u0027
  • \" Double Quote \u0022

Suppose you want to print the quoted message shown below:

He said "Java is fun"


The statement to print it should be:

<source lang=java> System.out.println("He said \"Java is fun\""); </source>


Debugging

Programming errors can be categorized into three types: syntax errors, runtime errors, and logic errors. Errors that occur during compilation are called syntax errors or compilation errors. Runtime errors are errors that cause a program to terminate abnormally. Logic errors occur when a program does not perform the way it was intended to.

In general, syntax errors are easy to find and easy to correct, because the compiler gives indications as to where the errors came from and why they are there. Runtime errors are not difficult to find either, since the Java interpreter displays them on the console when the program aborts. Finding logic errors, on the other hand, can be very challenging.

Logic errors are called bugs. The process of finding and correcting errors is called debugging. A common approach to debugging is to use a combination of methods to narrow down to the part of the program where the bug is located. You can hand-trace the program (i.e., catch errors by reading the program), or you can insert print statements in order to show the values of the variables or the execution flow of the program. This approach might work for a short, simple program. But for a large, complex program, the most effective approach for debugging is to use a debugger utility.

JDK includes a command-line debugger (jdb), which is invoked with a class name. jdb is itself a Java program, running its own copy of Java interpreter. All the Java IDE tools, such as JBuilder, NetBeans, and Eclipse, include integrated debuggers. The debugger utilities let you follow the execution of a program. They vary from one system to another, but they all support most of the following helpful features:

  • Executing a single statement at a time: The debugger allows you to execute one statement at a time so that you can see the effect of each statement.
  • Tracing into or stepping over a method: If a method is being executed, you can ask the debugger to enter the method and execute one statement at a time in the method, or you can ask it to step over the entire method. You should step over the entire method if you know that the method works. For example, always step over system-supplied methods, such as System.out.println.
  • Setting breakpoints: You can also set a breakpoint at a specific statement. Your program pauses when it reaches a breakpoint and displays the line with the breakpoint. You can set as many breakpoints as you want. Breakpoints are particularly useful when you know where your programming error starts. You can set a breakpoint at that line and have the program execute until it reaches the breakpoint.
  • Displaying variables: The debugger lets you select several variables and display their values. As you trace through a program, the content of a variable is continuously updated.
  • Displaying call stacks: The debugger lets you trace all of the method calls and lists all pending methods. This feature is helpful when you need to see a large picture of the program-execution flow.
  • Modifying variables: Some debuggers enable you to modify the value of a variable when debugging. This is convenient when you want to test a program with different samples but do not want to leave the debugger.
Personal tools