D286: Java Fundamentals

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

if (condition) { if (condition) { // statements } else if { // statements } ... } else { // statements }

This is a general syntax for a nested if-else statement, commonly used to make decisions that are based on multiple features.

someString.charAt(x);

This is a general syntax to determine the character at index x of a string. Remember, a string's indices range from 0 to the string's length minus 1.

import java.util.Random;

This statement enables use of the Random class.

System.out.println("Wage is: " + wage);

This example shows how the "+" symbol is used to output multiple items using one output statement.

movieTitle = "The Martian";

This example syntax is how to assign a string literal to a String variable. String variables can be assigned other String variables as well.

String firstMonth = "January";

This example syntax shows that String variables can be initialized during their declaration.

!=

This is the inequality operator, which evaluates to true if the left and right sides are not equal (ie: different), otherwise false.

str1.compareToIgnoreCase(str2)

This is an example syntax to compare two strings relationally while ignoring case.

char myChar;

This is an example syntax to declare a variable that can store a single character literal. Any character being assigned to this variable type must be surrounded with single quotes, not double quotes. For example, myChar = 'm';.

Whitespace

This is blank space (space and tab characters) between items within a statement and blank lines between statements (called newlines). A compiler ignores most of this and is used to make a program more readable.

==

This is the equality operator, which evaluates to true if the left and right sides are equal, otherwise false.

(), !, * / % + -, < <= > >=, == !=, &&, ||

These are all arithmetic, logical, and relational operators ordered left to right based on precedence rules: Parenthesis, logical NOT, Arithmetic, Relational, Equality & Inequality, Logical AND, Logical OR.

+=, -=, *=, /=, %=

These are the five special operators known as compound operators, which all provide a shorthand way to update a variable

byte, short, int, long

These are the four main integer numeric data types that can hold 8 bits, 16 bits, 32 bits, and 64 bits, respectively.

<, >, <=, >=

These are the relational operators used to check whether one operand's value is less than, greater than, less than or equal to, or greater than or equal to another operand, respectively.

float, double

These are the two main floating-point numeric data types that can hold 32 bits and 64 bits, respectively.

(), unary -, * / %, + -

These four operator categories are listed first to last according to precedence rules for arithmetic operators.

5 / 2 = 2 vs 5.0 / 2.0 = 2.5

These two divisions show how the result depends on whether or not the involved values are integers or floating-point. Integer division neglects any remainder.

(int) vs (double) Ex: myFloat = (double)numValue;

These two perform type casting, which invoke explicit conversion to change a value from double to integer or integer to double, respectively. These must be appended on the left side of a variable to work.

str1 += str2

This alternative to using a string method is shorthand for "str1 = str1 + str2". 'str1' must be a String variable, and 'str2' may be a String variable, a string literal, or a character.

str1 + str2

This alternative to using a string method returns a new String that is a copy of 'str1' with 'str2' appended. 'str1' may be a String variable or string literal. Likewise for 'str2'. One of 'str1' or 'str2' (not both) may be a character.

if (condition) { // statements } else { // statements }

This is the general syntax for an if-else statement, which executes one group of statements when an expression is true, and another group of statements when the expression is false.

import packageName.ClassName;

This is the general syntax for any import statement. For example, for "import java.util.Scanner", 'java.util' is the package & subpackage name while 'Scanner' is the class name.

randGen.setSeed(5);

After creating a new random number generator object named randGen without a seed, this method call can be used to specify a seed, in this example "5", so each program run will yield the same sequence of pseudo-random numbers.

randGen.nextInt()

After creating a new random number generator object named randGen, this method call can be used to get a random number integer ranging from "-2^31" to "2^31 - 1".

break;

Break statement syntax, which, when in a loop, causes an immediate exit of the loop. A break statement can sometimes yield a loop that is easier to understand.

continue;

Continue statement syntax, which, when in a loop, causes an immediate jump to the loop condition check. A continue statement can sometimes improve the readability of a loop.

// FIXME: Add else-if branch for letters & hyphen

Example FIXME comment to indicate program parts to be fixed or added.

for (int i = 0; i < N; ++i);

Example syntax of declaring the initial expression as part of the for loop instead of before the loop expression (ie: int i = 0).

Not a number (NaN)

If the dividend and divisor in floating-point division are both 0, the division results in this output.

import java.util.Scanner;

Specific import code placed at the top of a file to enable the program to get input

&&, ||, !

These are the logical operators that represent AND, OR, and NOT, respectively.

str1.compareTo(str2) == 0

This is an example syntax of using the compareTo method to compare two strings relationally via their lexicographical values (ie: Unicode or ASCII values). This example compares both strings with '== 0', which is checking whether two strings' values are equal. Using '< 0' or '> 0' checks whether they're less than or greater than one another, respectively.

str1.equals(str2)

This is an example syntax of using the equals method to compare two strings 'str1' and 'str2' and return true if they are equal, otherwise false. This method must always be used instead of the equality operator '==' to compare two strings.

str1.equalsIgnoreCase(str2)

This is an example syntax to compare the equality of two strings while ignoring case.

/** This is a comment **/

This is the syntax for writing a multi-line comment, also called a block comment.

System.out.println()

Prints an item and then moves the cursor to the next line (ie: newline).

Main()

Where a program begins executing statements contained within braces {}.

scnr.nextDouble();

A scanner method that reads a floating-point value from input, which can be assigned to a double variable.

for (initialExp.; condition; updateExp.) { // statements }

General "for loop" syntax, which is a loop with three parts at the top: a loop variable initialization, a loop expression, and a loop variable update. A "for loop" describes iterating a specific number of times more naturally than a while loop. Also, for loops can be nested in other loops.

dataType[] arrayName = new dataType[numElements];

General array declaration syntax. The [] symbols after the data type indicate that the variable is an array reference. The new keyword creates space in memory to store the array with the specific number of elements. The array reference variable is assigned to refer to that newly allocated array. A programmer can declare an array reference variable without allocating the array at that time and later assign the variable with an allocated array.

public enum identifier {enumerator1, enumerator2, ...}

General enumeration type (enum) syntax, which declares a name for a new type and possible values for that type. Used when a variable only needs to store a small set of named values. The items within the braces ("enumerators") are named constants. Those constants are not assigned a specific numeric value, but instead must be referred to by the defined names.

while (expression) { // statements }

General while loop syntax, which executes (ie: iterates) the loop body while the loop's expression evaluates to true. Once entering the loop body, execution continues to the body's end even if the expression becomes false midway. Prevent infinite loops by updating the expression in the body, creating a loop expression whose evaluation to false isn't always reachable, or writing the loop to end upon receiving a sentinel value (ex: -1) from input. while loops can be nested in other loops.

Infinity, -Infinity

Java outputs these when a user divides a nonzero floating-point number by zero.

Math.PI

Java provides this to hold the first 15 digits of the irrational mathematical constant pi (π).

System.out.print()

Outputs an item on the screen, starting at the screen cursor's present location, and moving the cursor after each output item.

switch (expression) { case constantExpr1: // Statements break; case constantExpr2: // Statements break; ... default: // If no other case matches // Statements break; }

Switch statement structure, which more clearly represents multi-branch behavior involving a variable being compared to constant values. It executes the first case with a constant expression matching the value of the switch expression and then breaks. Default executes if no case matches.

"desired text"

Syntax for string literals, which is text in double quotes

+, -, *, /

Syntax for the addition, subtraction, multiplication, and division arithmetic operators, respectively.

someString1.concat(someString2)

The + operator can append one string to another; however, this example shows the syntax of another way by using the concat() method to return a new string that appends two strings.

++i, --i

The pre-increment and pre-decrement operator syntax that are short hand ways to increase or decrease a variable by one, respectively. They calculate before evaluating to a value while i++ and i-- calculate after.

Comparing characters, strings, and floating-point types

The relational and equality operators work for integer, character, and floating-point built-in types. Comparing characters compares their Unicode numerical encoding. Floating-point types should not be compared using the equality operators due to the imprecise representation of floating-point numbers. The operators should not be used with strings; unexpected results will occur.

Scanner scnr = new Scanner(System.in);

The statement that instantiates a new scanner object in the variable "scnr" so system input can be parsed.

scnr.nextInt();

The statement that retrieves the system's next integer value input. It is the variable "scnr" calling this scanner class method to read integer values from input made possible after "scnr" is instantiated with a new scanner class object.

Math.

The syntax for invoking the Math class, a Java standard package that allows about 30 math methods to be called.

sqrt(x), pow(x, y), abs(x)

The syntax of three common math methods to invoke square root, power, and absolute value for a given value, respectively. These must be appended to 'Math.' to work.

\n , \t , \' , \" , \\

Thes are five common escape sequence characters, which are two-character sequences that start with \ and then the character the user wishes to represent. This allows the user to enter a newline, tab, single quote, double quote, and backslash, respectively.

Scanner(InputStream source)

This constructor performs similarly to "new Scanner(System.in);" as they both are an InputStream object designed to take in input during program execution. However, This constructor can specify any input stream as the source, not just standard input.

randGen.nextInt(10)

This example random number generator method call syntax shows a programmer restrictiing the possible outputs to 10 values ranging from 0 to 9.

randGen.nextInt(30 - 18 + 1) + 18

This example random number generator method call syntax shows a programmer restrictiing the possible outputs to 18 values ranging from 18 to 30.

0.504 * 316 = 159.264

This example shows how calculating any integer with a floating-point number causes Java to invoke implicit conversion, a form of type conversion, to change the integer to a floating-point number prior to calculation.

System.out.printf("%.2f", myFloat);

This example shows the syntax for controlling the number of decimal places when printing a floating-point number. In this case, 'printf' for float, '.2' means to two decimal places, and 'myFloat' is an example variable where the decimal place manipulation is applied

myChar = scnr.next().charAt(0);

This example syntax shows how to get a character value from input. Note that next() gets the next sequence of non-whitespace characters (as a string), and charAt(0) gets the first character in that string.

randNum % 10

This example yields a random number between 0 and 9, made possible by the modulo operator. Note that 0 is possible, not 10.

(randNum % 11) + 20

This example yields a random number between 20 and 30, made possible by the modulo operator and then adding 20 to the result.

Character.toLowerCase(c)

This is a character method from the Character class that returns the lowercase version of character 'c'.

Character.toUpperCase(c)

This is a character method from the Character class that returns the uppercase version of character 'c'.

Character.isDigit(c)

This is a character method from the Character class that returns true if the character 'c' is a digit.

Character.isLetter(c)

This is a character method from the Character class that returns true if the character 'c' is alphabetic.

Character.isWhitespace(c)

This is a character method from the Character class that returns true if the character 'c' is whitespace.

someString.length();

This is a general syntax to identify a string's length, which can also be used when identifying the last character in a string minus one.

numValue = 8;

This is an example syntax for an assignment statement, which assigns an integer literal to a declared variable.

isMale = true;

This is an example syntax for assigning a boolean value 'true' to the variable 'isMale'.

boolean isWeekend;

This is an example syntax for declaring a boolean type variable named "isWeekend". Boolean variables hold true or false values only.

final double SPEED_OF_SOUND = 761.207;

This is an example syntax for declaring a constant variable (ie: final variable). Note the use of 'final' to prevent modification and the use of upper cases & underscores for identifiability.

double milesTravel;

This is an example syntax for declaring a variable that can store a floating-point number.

int numValue;

This is an example syntax for declaring an integer variable with the identifier "numValue". In general, any identifier that is not a reserved word (ie: keyword) can be used to name a variable. Not how this example is using lowerCamelCase.

int numValue = 100;

This is an example syntax for initializing an integer variable, which assigns an integer literal (ie: initial value) at the same time the variable is declared.

isOverweight = (userBmi >= 25);

This is an example syntax for setting a boolean value to a boolean variable with a logical expression.

6.02e23

This is an example syntax of a floating-point literal using scientific notation where the e precedes the power-of-10 exponent.

System.out.print("" + c1 + c2);

This is an example syntax showing how a programmer can output multiple character variables with one statement. The initial "" tells the compiler to output a string of characters, and the +'s combine the subsequent characters into such a string. Without the "", the compiler will simply add the numerical values of c1 and c2, and output the resulting sum.

if (condition) { // statements } else if { // statements } else { // statements }

This is the general syntax for a multi-branch if-else statement. Each branch's expression is checked in sequence. As soon as one branch's expression is found to be true, that branch's statements execute (and no subsequent branch is considered). If no expression is true, the else branch executes.

if (condition) { // statements }

This is the general syntax for an if statement, which executes a group of statements if an expression is true. Braces surround the if branch's statements. A programmer can use multiple if statements in sequence to detect multiple features with independent actions. Each if-statement is independent, and thus more than one branch can execute, in contrast to the multi-branch if-else arrangement.

condition ? exprWhenTrue : exprWhenFalse

This is the syntax for a conditional expression made with the ternary operators "?" and ":". 'exprWhenTrue' is evaluated when 'condition' returns true. 'exprWhenFalse' is evaluated when 'condition returns false. The whole conditional expression evaluates to the result of whichever two expressions was evaluated.

\n

This is the syntax for the newline character, an alternative to "println", though not used often for practical purposes.

// This is a comment

This is the syntax for writing a single-line comment that commonly appears after a statement on the same line.

break;

This statement causes a switch expression to terminate. Excluding this will cause the statements within the next case to be executed.

Random randGen = new Random(5);

This statement creates a new random number generator object named randGen that also specifies a seed "5".

Random randGen = new Random();

This statement creates a new random number generator object named randGen.

scnr.nextLine()

This statement gets the entire line from input, including all whitespace before, within, and after any characters on the line in question. Note that it removed the newline character at the end of the line, but does not include it within the string.

scnr.next();

This statement gets the next string literal from input, skipping any initial whitespace and stopping when the next whitespace is seen. For example, it can get "Hello" from " Hello World".

Math.abs(x - y) < 0.0001

This statement should be used to compare two floating-point numbers for equality instead of using ==. It compares them within a difference threshold indicating equality (ie: epsilon). In other words, "close enough" rather than exact.

myString.concat(moreString)

This string data type method creates a new String that appends the String 'moreString' at the end.

myString.lastIndexOf(item)

This string data type method finds the last occurrence of the item in a string, else returns -1. The item may be char, String variable, or string literal.

myString.indexOf(item, indx)

This string data type method gets the index of the item's first occurrence in a string starting from an specific index provided as a parameter 'indx', else returns -1. The item may be char, String variable, or string literal.

myString.indexOf(item)

This string data type method gets the index of the item's first occurrence in a string, else returns -1. The item may be char, String variable, or string literal.

myString.replace(findChar, replaceChar)

This string data type method returns a new String in which all occurrences of 'findChar' have been replaced with 'replaceChar'.

myString.replace(findStr, replaceStr)

This string data type method returns a new String in which all occurrences of 'findStr' have been replaced with 'replaceStr'.

myString.substring(startIndex)

This string data type method returns a substring starting as 'startindex'.

myString.substring(startIndex, endIndex)

This string data type method returns a substring starting at 'startIndex' and ending at 'endIndex - 1'. The length of the substring is given by endIndex - startIndex.


Set pelajaran terkait

Job 2 - Flashcard MC Questions - Ted Hildebrandt

View Set

BUAD 342 FINAL: Technology trends/issues transforming the way we conduct business (and as a result, the way we manage and leverage information)

View Set

Geometry 2017 Exam Triangle Congruence SSS and SAS

View Set