Docsity

Java Programming Information Review Sheet | CS 1110, Study notes of Computer Science

Toggle sidebar
bg1
CS101X Quick Sheet Draft
© 2007
1
Java information sheet
Syntax vs. Semantics vs. Style
A syntax rule is a requirement imposed by the Java programming
language; e.g., a variable must be defined before it can be used.
A semantics rule defines how something works; e.g., in Java the +
operator performs addition when it has numeric operands.
A style rule is a programming convention to program appearance; e.g., a
Java constant should only use uppercase letters and underscores in its
name.
Comments
The sequence // indicates the rest of the line is not to be translated as
part of the program. The text is a comment to a program reader.
Programs often have header comment section that identifies the purpose
of the program, the authors, and contact information.
A method normally begins with a comment indicating its purpose.
A section of code within a method is typically preceded by a comment
indicating its task.
Whitespace
Whitespace between programming elements is ignored during
compilation.
Whitespace is used to separate program elements for increased
readability.
Indentation is used to indicate whether a program element is part of
another program element; e.g., the statements within a method are
indented with respect to the method.
Standard indentation level is 3 or 4 spaces.
If necessary for readability, long statements are normally broke up into
multiple lines. The additional lines are indented with respect to the
starting line of the statement.
If necessary for readability, expressions long in length are broken
immediately before an operator. If feasible, indenting the operator so that
it lies below its operand is a standard practice.
Programs
A Java program must have the name of its class be identical to the name
file containing its definition.
A Java class is a program if it has a method public static void
method name main() taking a single parameter of type String[]. By
convention the name of the parameter is args.
Keywords
A keyword is a word reserved by Java and has special meaning within a
program.
All Java keywords are case sensitive and lowercase.
The most frequently used keywords are public, class, static,
void, int, double, char, boolean, if, else, final, null,
switch, while, for, throws, and catch.
Identifiers
Identifier is computing term for a name.
A Java identifier must begin with a letter. Subsequent characters – if any
– can be letters or numbers. Because Java uses the Unicode alphabet,
letters from other languages are okay to use. The _ and $ are considered
letters.
Identifier names are case dependent; e.g., peasPerPod and
peasperpod are different identifiers.
Keywords cannot be used as names.
The preferred naming scheme for a class is a noun whose letters are all
lowercase except for the first letter of each word in the name; e.g.,
DataCoordinate rather than datacoordinate.
The preferred naming scheme for a variable is all lowercase letters
except for the first letter of each word after the initial word in the name;
e.g., peasPerPod rather than peasperpod.
The preferred naming scheme for a constant is all uppercase letters
except for underscore characters separating the words within the name;
e.g., HOURS_PER_DAY rather than hoursPerDay or HOURSperDAY.
Variables
A variable is a symbolic name for a memory location whose contents can
be modified during the execution of a program.
A variable must be defined before it can be used.
A variable must be initialized before it can be evaluated; that is, used in a
calculation.
The value of a primitive variable is a primitive value; i.e., a numeric or
Boolean value.
The value of an object variable is a reference – think pointer – to an
object.
pf3
pf4
pf5

Partial preview of the text

Download Java Programming Information Review Sheet | CS 1110 and more Study notes Computer Science in PDF only on Docsity!

Java information sheet

Syntax vs. Semantics vs. Style  A syntax rule is a requirement imposed by the Java programming language; e.g., a variable must be defined before it can be used.  A semantics rule defines how something works; e.g., in Java the + operator performs addition when it has numeric operands.  A style rule is a programming convention to program appearance; e.g., a Java constant should only use uppercase letters and underscores in its name. Comments  The sequence // indicates the rest of the line is not to be translated as part of the program. The text is a comment to a program reader.  Programs often have header comment section that identifies the purpose of the program, the authors, and contact information.  A method normally begins with a comment indicating its purpose.  A section of code within a method is typically preceded by a comment indicating its task. Whitespace  Whitespace between programming elements is ignored during compilation.  Whitespace is used to separate program elements for increased readability.  Indentation is used to indicate whether a program element is part of another program element; e.g., the statements within a method are indented with respect to the method.  Standard indentation level is 3 or 4 spaces.  If necessary for readability, long statements are normally broke up into multiple lines. The additional lines are indented with respect to the starting line of the statement.  If necessary for readability, expressions long in length are broken immediately before an operator. If feasible, indenting the operator so that it lies below its operand is a standard practice. Programs  A Java program must have the name of its class be identical to the name file containing its definition.  A Java class is a program if it has a method public static void method name main() taking a single parameter of type String[]. By convention the name of the parameter is args. Keywords  A keyword is a word reserved by Java and has special meaning within a program.  All Java keywords are case sensitive and lowercase.  The most frequently used keywords are public, class, static, void, int, double, char, boolean, if, else, final, null, switch, while, for, throws, and catch. Identifiers  Identifier is computing term for a name.  A Java identifier must begin with a letter. Subsequent characters – if any

  • can be letters or numbers. Because Java uses the Unicode alphabet, letters from other languages are okay to use. The _ and $ are considered letters.  Identifier names are case dependent; e.g., peasPerPod and peasperpod are different identifiers.  Keywords cannot be used as names.  The preferred naming scheme for a class is a noun whose letters are all lowercase except for the first letter of each word in the name; e.g., DataCoordinate rather than datacoordinate.  The preferred naming scheme for a variable is all lowercase letters except for the first letter of each word after the initial word in the name; e.g., peasPerPod rather than peasperpod.  The preferred naming scheme for a constant is all uppercase letters except for underscore characters separating the words within the name; e.g., HOURS_PER_DAY rather than hoursPerDay or HOURSperDAY. Variables A variable is a symbolic name for a memory location whose contents can be modified during the execution of a program. A variable must be defined before it can be used. A variable must be initialized before it can be evaluated; that is, used in a calculation. The value of a primitive variable is a primitive value; i.e., a numeric or Boolean value. The value of an object variable is a reference – think pointer – to an object.

A variable only exist within the block of statements containing its definition. A variable can be defined only once within a block of statements. Constants A constant is a symbolic name for a memory location whose contents once they are initialized cannot be modified during the execution of a program. A constant must be defined before it can be used. A constant must be initialized before it can be evaluated; that is, used in a calculation. Escape sequence An escape sequence allows a special character to be represented as a normal character. The primary escape sequences are \t represents the tab character. \n represents the newline character. \ represents the backslash character. ' represents the single quote character. " represents the double quote character. Type A type is a collection of values along with the operators and methods that manipulate the values. Java divides its type into categories – primitive and object. The integer primitive types are byte, char, short, int, and long. These types respectively use 1, 2, 2, 4, and 8 bytes to represent an integer. char is also the character type. The floating point (decimal) primitive types are float and double. They respectively use 4 and 8 bytes to represent a decimal. An object typically has both attributes and behaviors. Values and objects A literal value is either explicit primitive value or a character string; e.g., 19 , 2.8, true, and "aardvark". The value of a primitive type variable or constant is a value from its type. The value of an object variable is a reference to an object. Java uses keyword null to indicate a nonreference. There is a difference between uninitialized and null. The former indicates no value as of yet; the latter indicates the nonreference value. The dot operator. is the Java selection operator giving access to an element of an object; e.g., s.x is the x attribute of the object referenced by s and s.f() is the f() behavior of the object referenced by s. System.out System.out represents the standard output stream; i.e.; where output should go by default. The System.out.print() method displays the value of its parameter to standard output. The System.out.println() method displays value of its parameter to standard output along with a newline character. When requesting input from a user it is standard to display a prompting message using the System.out.print() method. Operators and evaluation When even close to doubt uses parentheses. Java provides the standard arithmetic operators +, - , *, and / along with the remainder (modulus) operator %. Java does not provide an exponentiation operator. The standard Java library defines a method Math.pow(). The method takes to double parameters. The method returns the value of the first parameter to the power of the second parameter. If the operands to an arithmetic operator are integer then, integer arithmetic is performed; e.g., 7 / 4 evaluates to the int value 1. If the operands to a arithmetic operator are both numeric and at least one of the operands is a floating point value (decimal), then floating point arithmetic is performed; e.g. 7 / 4.0 evaluates to the double value 1.75. The + operator performs concatenation when at least one of its operands is a String value; e.g., "house" + "boat" evaluates to the String "houseboat"; " 1 " + "2" evaluates to the String " 12 "; and "1"

  • 2 evaluates to the String "12". In expressions composed of more than one operator, Java uses precedence and associativity rules for determining the order of operator evaluation. The grouping operator () has higher precedence than unary, numeric, relational, logical, and assignment operators. The unary operators +, - ,! have higher precedence than numeric, relational, logical, and assignment operators. The numeric operators have precedence than relational, logical, and assignment operators.

File Java uses File to provide a system-independent view of a file. A File object has no methods to access file contents. System.in InputStream variable System.in represents the standard input stream; i.e.; where input should come from by default. System.in methods are not programmer friendly – they only provide access to the input in byte representation. Scanner Java uses Scanner to provide a text view of an input data stream. Suppose stream is a Scanner. stream.next() returns the next input value as a String. stream.nextInt() returns the next input value as an int. stream.nextDouble() returns the next input value as a double. stream.nextBoolean() returns the next input value as a boolean. stream.nextLine() returns the remainder of the current input line as a String. stream.hasNext() returns a boolean value indicating whether there is any nonblank input left in the input stream. stream.hasNextLine()returns a boolean value indicating whether there is another line of input (i.e., is there an unprocessed new line character). stream.hasNextInt() returns a boolean value indicating whether the next input is integer. If there is no more input, the method returns false. stream.hasNextDouble() returns a boolean value indicating whether the next input is decimal. If there is no more input, the method returns false. stream.hasNextBoolean() returns a boolean value indicating whether the next input is boolean. If there is no more input, the method returns false The following definition Scanner stream = new Scanner( System.in ); makes stream a variable giving a Scanner view of standard input. The following definition using File variable filename Scanner stream = new Scanner( filename ); makes stream a variable giving a Scanner view of the file represented by filename. The following definition using InputStream variable dataSource Scanner stream = new Scanner( dataSource ); makes stream a variable giving a Scanner view of the input stream represented by dataSource. The following definition using String variable s Scanner stream = new Scanner( s ); makes stream a variable giving a Scanner view of the character string represented by s. URL and URLConnection Java uses URL to provide as system-independent view of a URL – uniform resource locator; i.e., a web resource. A URL object has a method openConnection() for establishing a URLConnection between the program and a URL. A URLConnection object has a method getInputStream() for establishing a URLConnection between the program and a URL.

A URL object has a convenience method openStream() for

creating an InputStream view of a URL.

If statement The if-else statement uses a boolean expression to determine the next action executed by a program. An if statement is not a loop. Its action actions can only be executed once, An if-else statement has form if ( Expression ) Action 1 else Action 2 where The else part of the statement is optional. The if action or else action is either a single statement or a block of statements within braces. It is highly recommended that an if action or else action always be a block of statements within braces The statements in an if action or else action can by any Java statement including if-else statements. If the test expression is true, the if action executes; otherwise, the else action executes. After the if action or else action completes, executions with the statement following the if-else statement.

Equality The operators == and != test respectively whether two values are the same or different; e.g., two numbers or two object references. The object method equals() tests whether two objects are identical or different. Doing assignments Normally each part of an assignment corresponds to something recently covered in class. If this does not seem to be the case, look again. While statement The while statement uses a boolean expression to determine the next action executed by a program. A while statement has form while ( Expression ) Action where The action is either a single statement or a block of statements within braces. It is highly recommended that the action always be a block of statements within braces The statements in the action can by any Java statement including while statements. If the test expression is false, the action of the while statement is ignored and execution continues with the statement following the loop. If the test expression is true, the action executes. After the action completes, the process of testing and action executing repeats until the test expression is false. For statement The for statement uses a boolean expression to determine the next action executed by a program. A for statement has form for ( OneTimeAction ; Expression ; AfterAction ) Action where The one time action is either a variable definition or assignment. The one time action is executed only once – right before the first evaluation of the test expression. The scope of a variable defined in the one time action is limited to the for loop. The action is either a single statement or a block of statements within braces. It is highly recommended that the action always be a block of statements within braces The statements in the action can by any Java statement including for statements. If the test expression is false, the action and the after action are both ignored and execution continues with the statement following the loop. If the test expression is true, the action executes. After the action completes, the after action executes. The process of testing and action and after action executing repeats until the test expression is false. Loop processing Because the while and for only execute their action if the test expression is true; if the test expression is initially false, the action never executes. A loop that does not terminate is called an infinite loop Scanner has next message methods are useful when processing input. Suppose stream is a Scanner. stream.hasNext() returns a boolean value indicating whether there is any nonblank input left in the input stream. stream.hasNextLine() returns a boolean value indicating whether there is another line of input (i.e., is there an unprocessed new line character). stream.hasNextInt() returns a boolean value indicating whether the next input is integer. If there is no more input, the method returns false. stream.hasNextDouble() returns a boolean value indicating whether the next input is decimal. If there is no more input, the method returns false. stream.hasNextBoolean() returns a boolean value indicating whether the next input is boolean. If there is no more input, the method returns false Blocks and scope A block is a list of statements nested within braces. A method body is a block. A block can be placed anywhere a statement would be legal

is, because only a COPY of the actual parameter’s value is passed into

the method, if a method changes that value, only the COPY is affected. Any change is not visible outside the method. Once the method returns, the copy is forgotten. Object parameters

If a formal parameter is an object variable, then the formal

parameter can change the attributes of the object it references.

When the method completes, the actual parameter still references

the same object it did before the invocation. However, any changes

to that object made during the invocation remain.

Signature The signature of a method is name along with the types specified in the list of the formal parameters. Overloading Java supports method overloading – different methods can have the same name. Method overloading is useful when methods are needed for similar tasks but with different types of parameter lists. Method name can be overloaded as long as its signature is different from the other methods of its class (i.e., different types or number of parameters). Common looping ideas When processing all the values from a scanner stream The test expression should use hasNext() if the values are strings, hasNextInt() if they are integers, and hasNextDouble() if they are decimals. Example, if stdin is your Scanner variable, then the while loop test expression should be stdin.hasNext()

  • while ( stdin.hasNext() ) { ♦ String value = stdin.nex(); ♦ Process value
  • } When summing n values. Initialize your total variable to 0. Initialize your counter variable to 0 While the counter variable is less than n Add the next value to the total. (The particular value will depend on the list you have been told to sum.) Increment the counter variable by 1. int total = 0; int counter = 0; while ( counter < n ) { Get/make the value total = total + value; } When multiplying n values. Initialize your total variable to 1. Initialize your counter variable to 0 While the counter variable is less than n Multiply the next value to the total. (The particular value will depend on the list you have been told to multiply.) Increment the counter variable by 1. int product = 1; int counter = 0; while ( counter < n ) { Get/make the value total = total * value; } When concatenating n strings. Initialize your result variable to "". Initialize your counter variable to 0 While the counter variable is less than n Add the next value to the result. (The particular value will depend on the list you have been told to process .) Increment the counter variable by 1. String result = ""; int counter = 0; while ( counter < n ) { Get/make the value total = total + value; }