1/145
Looks like no tags are added yet.
Java primitive data types
Built-in value types that store simple data directly. Unit 2 focuses on int, double, and boolean.
int
A primitive type for whole numbers, such as -4, 0, or 27. It cannot store a decimal fraction.
double
A primitive type for decimal numbers, such as 3.14 or -0.5; it generally uses more memory than int.
boolean
A primitive type whose only possible values are true and false.
Primitive vs. reference type
A primitive variable stores its value directly; a reference variable such as String stores a reference to an object.
Declaring an int
Example: int score; declares a variable named score that can store a whole number.
Initializing an int
Example: int score = 10; declares score and gives it the initial value 10.
Declaring a double
Example: double price = 4.99; stores a decimal value.
Declaring a boolean
Example: boolean passed = true; stores a logical value.
Assignment operator (=)
Stores the value on the right in the variable on the left; it does not test equality.
Equality operator (==)
Compares two primitive values for equality and produces a boolean result; do not confuse it with assignment (=).
Valid int literal
A whole-number literal such as 42 or -7, with no decimal point.
Valid double literal
A numeric literal containing a decimal point, such as 42.0 or -7.25.
Integer division
When both operands of / are integers, Java discards the fractional part of the quotient.
6 / 4
Evaluates to 1 because both operands are int values and the .5 is truncated.
14 / 5
Evaluates to 2 because integer division discards the fractional part.
Floating-point division
If at least one operand is a double, Java produces a double quotient that can include a fractional part.
6.0 / 4
Evaluates to 1.5 because 6.0 is a double, so Java promotes 4 and performs floating-point division.
14 / 5.0
Evaluates to 2.8 because one operand is a double.
Truncation in integer division
The fractional part is discarded toward zero; Java does not round to the nearest integer.
Integer division with negatives
-7 / 2 evaluates to -3 because Java truncates the quotient toward zero.
Implicit casting
An automatic conversion Java performs when moving from a narrower compatible type to a wider type, such as int to double.
Implicit int-to-double conversion
In 6.0 / 4, Java automatically converts 4 to 4.0 before division.
Explicit casting
A programmer-requested conversion written with a target type in parentheses, such as (double) 5.
14 / (double) 5
Evaluates to 2.8 because 5 is explicitly converted to a double before division.
(double) 14 / 5
Evaluates to 2.8 because casting either operand before division causes floating-point division.
(double) (14 / 5)
Evaluates to 2.0, not 2.8, because integer division happens first and the resulting 2 is then cast.
Casting double to int
Example: (int) 3.9 produces 3 by discarding the fractional part; it does not round.
Narrowing conversion
A conversion that may lose information, such as double to int; Java generally requires an explicit cast.
Widening conversion
A conversion that preserves the general numeric value, such as int to double; Java can perform it implicitly.
Division by zero with int
An integer expression such as 5 / 0 causes an ArithmeticException at runtime.
Division by zero with double
Floating-point division by 0.0 does not cause an integer ArithmeticException; it can produce Infinity or NaN.
Modulus operator (%)
Returns the remainder after division.
12 % 5
Evaluates to 2 because 12 divided by 5 has remainder 2.
Even-number test
A whole number n is even when n % 2 == 0.
Odd-number test
For nonnegative n, n % 2 != 0 identifies an odd number; this comparison is safer than n % 2 == 1 when negatives are possible.
Last digit of a positive integer
For positive n, n % 10 returns its last decimal digit.
Cycle with modulus
index % size keeps a nonnegative index within 0 through size - 1, useful for repeating patterns.
Divisibility test
If a % b == 0, then a is evenly divisible by b, assuming b is not zero.
Modulus precedence
% has the same precedence as multiplication and division and is evaluated before addition and subtraction.
Escape character
A backslash sequence inside a literal that represents a special character or a character that is difficult to type directly.
\n
The newline escape sequence; it moves subsequent output to a new line.
\t
The tab escape sequence; it inserts a horizontal tab.
\"
The double-quote escape sequence; it places a quotation mark inside a String literal.
\'
The single-quote escape sequence; it can place an apostrophe or quote inside a character literal.
\
The backslash escape sequence; it represents one literal backslash.
Printing quoted text
System.out.println("She said \"Hello\"."); prints: She said "Hello".
Printing a Windows-style path
System.out.println("C:\Users\Sam"); prints one backslash at each escaped location.
println vs. \n
println adds a line break after the entire argument; \n inserts a line break at a specific point inside a String.
String concatenation
Joining Strings or joining a String with another data type using the + operator.
"one" + "two"
Evaluates to the String "onetwo".
"one" + 2
Evaluates to the String "one2" because the int is converted to text during concatenation.
"Total: " + 2 + 2
Evaluates left to right to "Total: 22"; once concatenation begins, later + operations concatenate.
"Total: " + (2 + 2)
Evaluates to "Total: 4" because the parentheses force numeric addition first.
2 + 2 + " total"
Evaluates to "4 total" because the two ints are added before Java reaches the String.
Concatenation order trap
The meaning of + depends on the operands evaluated so far: it performs numeric addition before a String is involved and concatenation afterward.
String immutability
String methods and concatenation create new String values; they do not alter the original String object.
Scanner class
A Java utility class used to read keyboard or other formatted input.
Scanner import
Place import java.util.Scanner; before the class declaration to use Scanner by its simple name.
Creating a Scanner
Scanner in = new Scanner(System.in); creates a Scanner named in that reads standard keyboard input.
next()
Reads the next whitespace-delimited token, usually one word; it stops at spaces, tabs, or line breaks.
nextLine()
Reads all remaining characters on the current line, including spaces, and consumes the line separator.
nextInt()
Reads the next token as an int; non-integer input can cause an InputMismatchException.
nextDouble()
Reads the next token as a double; incompatible input can cause an InputMismatchException.
next() vs. nextLine()
next() reads one token; nextLine() reads the remainder of an entire line.
nextInt() followed by nextLine() trap
nextInt() leaves the line-ending character unread, so the following nextLine() may return an empty String.
Fixing the Scanner newline trap
After nextInt() or nextDouble(), call an extra nextLine() to consume the leftover line ending before reading a full line.
Scanner variable name
The identifier in, input, or keyboard is programmer-chosen; method calls must use the same variable, such as input.nextInt().
Prompt before input
Use System.out.print("Enter age: "); before reading so the user knows what value is expected.
Input validation concept
Check whether input meets requirements before using it; otherwise malformed or out-of-range input can break the program or produce invalid results.
Parsing
Converting text into another data type so it can be used in calculations or other typed operations.
Integer.parseInt(String)
Converts a valid integer String such as "42" into the primitive int 42.
Double.parseDouble(String)
Converts a valid decimal String such as "3.5" into the primitive double 3.5.
parseInt return value
Integer.parseInt returns an int; save or use the result, as in int n = Integer.parseInt(text).
Ignored parsing result
Calling Integer.parseInt(text); alone validates/converts momentarily but loses the returned value if it is not assigned or used.
Invalid numeric parsing
Parsing text such as "four" with Integer.parseInt causes a NumberFormatException.
Whitespace and parsing
A String with extra whitespace may fail direct parsing; trim() can remove leading and trailing whitespace first.
Scanner numeric method vs. parsing
nextInt() reads and converts an input token directly; nextLine() plus parseInt() first reads text and then converts it.
Why use nextLine() plus parsing
It gives the program the complete line as text before conversion, which can make input handling and validation more predictable.
String.length()
Returns the number of characters in a String as an int.
"hello".length()
Returns 5.
String index positions
String indexes begin at 0; the first character is at index 0 and the last is at length() - 1.
Valid String index range
For a nonempty String s, valid character indexes are 0 through s.length() - 1.
substring(beginIndex)
Returns the portion from beginIndex through the end of the String.
"computer".substring(3)
Returns "puter" because index 3 is the letter p.
substring(beginIndex, endIndex)
Returns characters from beginIndex inclusive to endIndex exclusive.
"computer".substring(0, 3)
Returns "com"; index 0 is included and index 3 is excluded.
Substring length
For s.substring(a, b), the result contains b - a characters when the indexes are valid.
Entire String with substring
s.substring(0, s.length()) returns the entire String.
Empty substring
s.substring(k, k) returns the empty String because the start and end indexes are equal.
substring boundary trap
The second argument is an exclusive boundary, not the index of the final included character.
Invalid substring indexes
Negative indexes, an end beyond length(), or a begin greater than the end cause StringIndexOutOfBoundsException.
indexOf(String)
Returns the index of the first occurrence of the given character sequence.
"banana".indexOf("na")
Returns 2, the starting index of the first "na".
indexOf when not found
Returns -1 when the target does not occur in the String.
Testing whether text occurs
Use s.indexOf(target) >= 0 to test whether target appears anywhere in s.
indexOf search start
indexOf can locate a substring, not merely one character, and reports the starting index of the first match.
Finding a later occurrence
After finding index i, search again from a later position with an available overload such as s.indexOf(target, i + 1).
String method call syntax
Use the object, a dot, the method name, and parentheses, such as word.length() or word.substring(1).
Method parameter
A value listed in a method definition that receives an argument when the method is called.