Chapter 2 - Data and Expressions Notes
Data and Expressions
Character Strings
String Literals: Enclosed in double quotes. They represent a sequence of characters and are used to display text in Java programs. Examples:
"This is a string literal."
"123 Main Street"
"X"
Escape Sequences: Special characters in strings can be represented using escape sequences, like
\nfor a new line and\tfor a tab character.
String Objects: In Java, all string literals are instances of the String class, which provides various methods for manipulating and querying strings. This means strings are treated as objects, allowing for a rich set of utility functions.
Output Methods
println Method: A method that outputs a string to the console and moves the cursor to the next line after printing. This is useful for displaying messages or program outputs. Example:
System.out.println("Whatever you are, be a good one.");print Method: Similar to the
printlnmethod, but it does not advance to the next line after printing. This can be useful for iterating through items without breaking the display into separate lines. Example:System.out.print("Three... ");
String Concatenation
Operator
+: The plus operator is used to append strings together, making it easy to build complex messages by combining multiple strings. Example: "Peanut butter " + "and jelly" will result in "Peanut butter and jelly".Concatenating Numbers: When a number is combined with a string, the number is automatically converted to a string. For example,
"The total is: " + 100outputs "The total is: 100".Multi-line Strings: String literals cannot span multiple lines unless concatenated using the
+operator, which makes readability for lengthy strings a consideration.
Variables
Definition: A variable is a named memory location for storing data that can change during program execution.
Declaration Example: To declare a variable, type the data type followed by the name. Example:
int total;declares an integer variable named total.Initialization: When a variable is assigned an initial value during declaration, it is called initialization. This step is important to avoid using uninitialized variables that can cause bugs. Example:
int sum = 0;
Variable Assignment
Assignment Statement: This changes the value stored in a variable and follows the syntax:
variableName = newValue;. It is a central operation in programming, as it allows for dynamic changes in data.Value Overwriting: The value of a variable can be overwritten any number of times, but assignments must adhere to data type compatibility; for example, you cannot assign a string to an integer variable.
Constants
Definition: Constants are similar to variables, but once declared, their values cannot be changed throughout the program's lifespan. This provides clarity and prevents accidental changes to key values.
Declaration Example: Constants are declared using the
finalmodifier to ensure immutability. Example:final int MIN_HEIGHT = 69;
Purpose: Their primary purpose is to improve code readability and maintainability by providing meaningful names for values that should remain unchanged, making the code easier to understand.
Primitive Data Types
Overview: Java has eight built-in primitive data types that serve as the foundational data types. They include:
Integer Types: byte (8 bits), short (16 bits), int (32 bits), long (64 bits)
Floating Point Types: float (32 bits), double (64 bits) for storing decimal numbers
Character Type: char (16 bits), used for representing single characters
Boolean Type: boolean, which can hold true or false values
Expressions
Definition: Expressions are combinations of variables, constants, operators, and method calls that evaluate to a value. They are essential for performing calculations and manipulating data in Java.
Arithmetic Operators: The primary arithmetic operators include
+for addition,-for subtraction,*for multiplication,/for division, and%for modulus, which gives the remainder of division.Division Behavior: Be cautious with integer division, as it truncates any decimal remainder. For example,
5 / 2results in2rather than2.5.Operator Precedence: Operators have precedence levels that dictate the order of evaluation; for example, multiplication
*, division/, and modulus%are evaluated before addition+and subtraction-.
Data Conversion
Widening Conversion: This is a safer process where a smaller data type is converted to a larger type without risk of data loss (e.g., short to int).
Narrowing Conversion: This conversion carries risks, as it involves converting from a larger type to a smaller type, potentially leading to data loss (e.g., int to byte).
Casting: In Java, when narrowing conversion is needed, casting is explicitly used to indicate the programmer's intent. For example,
(int) 9.99converts a double value to an integer, resulting in9.
User Input with Scanner Class
Setup: To read user input in Java, the Scanner class must be imported from
java.util, and an instance is created withScanner scan = new Scanner(System.in);. This sets up the program to capture user input effectively.Input Methods: Various methods are available to read different types of input:
nextLine(): Reads an entire line as a string. Example:String message = scan.nextLine();nextInt(): Reads the next input as an integer, causing aInputMismatchExceptionif the input isn't an integer.nextDouble(): Reads the next input as a double.
Summary of Chapter 2 Concepts
This chapter reviewed crucial programming concepts including character strings, the distinctions between string literals and string objects, primitive data types, variable declarations and assignments, string concatenation, expressions, operator precedence, data conversion techniques, and methods for handling user input. The comprehensive nature of these concepts forms the foundational knowledge for Java programming as the learner progresses through more complex topics.