Variables: Storage, Naming, and Declaration

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

Which of the following best describes the purpose of a variable in Java?

  • A named storage location in memory that can hold a value. (correct)
  • A type of operator used in arithmetic operations.
  • A keyword with a predefined meaning in Java.
  • A method for printing output to the console.

When declaring a variable, what crucial information must be provided?

  • The variable's initial value and scope.
  • The variable's access modifiers and default methods.
  • The variable's name and data type. (correct)
  • The variable's name and the algorithm it will use.

Which of the following is a primitive type in Java?

  • `Scanner`
  • `int` (correct)
  • `ArrayList`
  • `String`

How do class types differ from primitive types in Java?

<p>Class types are user-defined, whereas primitive types are predefined. (B)</p>
Signup and view all the answers

Which of the following naming conventions is generally followed for class types in Java?

<p>Begin with an uppercase letter. (C)</p>
Signup and view all the answers

Which of the following is NOT a valid component of a Java identifier?

<p>Spaces (D)</p>
Signup and view all the answers

What is the significance of keywords in Java?

<p>They are predefined words with special meanings that cannot be used as identifiers. (A)</p>
Signup and view all the answers

Which of the following is NOT a primitive data type in Java?

<p><code>integer</code> (D)</p>
Signup and view all the answers

Which primitive type is most commonly used for integer values in java?

<p><code>int</code> (C)</p>
Signup and view all the answers

What is the primary function of an assignment statement in Java?

<p>To assign a value to a variable. (A)</p>
Signup and view all the answers

In Java, which side of the assignment operator = is evaluated first?

<p>The right-hand side. (B)</p>
Signup and view all the answers

What operation does the += operator perform in Java?

<p>It adds the right operand to the left operand and assigns the result to the left operand. (D)</p>
Signup and view all the answers

Given the following Java code, what will be the output? int count = 10; System.out.println("The count is " + count);

<p><code>The count is 10</code> (B)</p>
Signup and view all the answers

What is concatenation in Java, in the context of strings?

<p>The process of joining two or more strings together. (C)</p>
Signup and view all the answers

To enable keyboard input in a Java program, which of the following import statement is required?

<p><code>import java.util.*;</code> (B)</p>
Signup and view all the answers

What is the purpose of the Scanner class in Java?

<p>To read input from the keyboard. (A)</p>
Signup and view all the answers

In Java, what is a literal constant?

<p>An explicit data value, like a number or a character. (A)</p>
Signup and view all the answers

Which of the following is a proper way to write 8,650,000,000 in scientific notation in Java?

<p><code>8.65e9</code> (C)</p>
Signup and view all the answers

What does it mean for Java to be a strongly typed language?

<p>Every variable must have a declared type, and type mismatches are not allowed. (D)</p>
Signup and view all the answers

What is type casting in Java?

<p>Explicitly converting a value from one data type to another. (D)</p>
Signup and view all the answers

In type casting, what happens to any nonzero value to the right of the decimal point when casting a floating-point number to an integer?

<p>It is truncated. (A)</p>
Signup and view all the answers

Which character set does Java use?

<p>Unicode (C)</p>
Signup and view all the answers

What is the significance of escape sequences in Java strings?

<p>They are used to insert special characters into strings. (C)</p>
Signup and view all the answers

What is the term for a variable that has been declared but has not been assigned a value?

<p>Uninitialized (B)</p>
Signup and view all the answers

What is the recommended practice in Java regarding uninitialized variables?

<p>Assign a value at the time of declaration to avoid potential issues. (C)</p>
Signup and view all the answers

Which of the following is true when performing arithmetic operations with mixed data types (e.g., int and double) in Java?

<p>The result is always a floating-point type. (A)</p>
Signup and view all the answers

What is the result of integer division when both operands are integers in Java?

<p>The result is truncated. (A)</p>
Signup and view all the answers

What operation does the mod operator (%) perform?

<p>Division, returning the remainder. (B)</p>
Signup and view all the answers

In Java, what does the term precedence refer to in the context of operators?

<p>The order in which operators are evaluated in an expression (B)</p>
Signup and view all the answers

Which of the following has the highest precedence in Java?

<p>Unary Operators (C)</p>
Signup and view all the answers

When unary operators have equal precedence, how is operator precedence determined?

<p>the operator on the right has higher precedence than the operation(s) on the left (D)</p>
Signup and view all the answers

Which of the following is the correct way to declare a String variable named message and assign it the value Hello, world!?

<p><code>String message = &quot;Hello, world!&quot;;</code> (C)</p>
Signup and view all the answers

What is the index of the first character in a String in Java?

<p>0 (D)</p>
Signup and view all the answers

What is the purpose of the length() method when used with a String object in Java?

<p>Returns the length of the String object. (A)</p>
Signup and view all the answers

What does the following Java code output? System.out.println("abc\\def");

<p><code>abc\def</code> (C)</p>
Signup and view all the answers

What package contains the Scanner class used for keyboard input in Java?

<p><code>java.util</code> (C)</p>
Signup and view all the answers

What is the purpose of including comments in Java code?

<p>To provide explanations and documentation for human readers. (A)</p>
Signup and view all the answers

What is the difference between // and /* ... */ comments in Java?

<p><code>//</code> is for single-line comments, and <code>/* ... */</code> is for multi-line comments. (C)</p>
Signup and view all the answers

How is javadoc comment declared?

<p><code>/** javadoc comment */</code> (C)</p>
Signup and view all the answers

Why indent Java code?

<p>Indentation should communicate nesting clearly. (C)</p>
Signup and view all the answers

What is the significance of naming constants in Java?

<p>To avoid confusion and improve readability. (A)</p>
Signup and view all the answers

By convention, how are constants generally named in Java?

<p>Only uppercase letters. (D)</p>
Signup and view all the answers

Flashcards

What are Variables?

Variables store data (numbers, letters). Implemented as memory locations. Can have their value changed.

Declaring a Variable

Before use, a variable's name and type must be declared. The type determines what kind of values it can hold.

Primitive Type

A simple, nondecomposable value (number or character). Examples: int, double, char.

Primitive Types Convention

Begin with a lowercase letter (e.g., int).

Signup and view all the flashcards

Java Identifier

A name for a variable. May contain letters, digits, underscores (_), and dollar signs ($), but cannot start with a digit.

Signup and view all the flashcards

Java Keywords

If , public or class. Keywords cannot be used as identifiers.

Signup and view all the flashcards

Integer Types

byte, short, int, long

Signup and view all the flashcards

Floating-point Types

float and double

Signup and view all the flashcards

char Type

Stores a single character (Unicode).

Signup and view all the flashcards

boolean Type

Represents true or false values.

Signup and view all the flashcards

Assignment Statement

Assigns a value to a variable. The equal sign (=) is the assignment operator. The expression on the right is evaluated first.

Signup and view all the flashcards

Specialized Assignment Operators

Combines assignment and arithmetic operators. Example: amount += 5; (same as amount = amount + 5;)

Signup and view all the flashcards

String Concatenation

Connects strings together. If one argument is a string, the + means concatenation.

Signup and view all the flashcards

java.util.*

A package that includes the Scanner class.

Signup and view all the flashcards

Scanner Class

Reads input from the keyboard.

Signup and view all the flashcards

Number Constants

Literal expressions (e.g., 2, 3.7, 'y'). Integers can have + or - signs. Floating-point can have decimals or e notation.

Signup and view all the flashcards

E Notation

Also called scientific or floating-point notation (e.g., 8.65e8).

Signup and view all the flashcards

Type Casting

The explicit conversion of a value from one data type to another. For example: points = (int)distance;

Signup and view all the flashcards

Characters as Integers

Each printable character is assigned a different integer according to a code such as ASCII or Unicode.

Signup and view all the flashcards

Initializing Variables

Protects against an uninitialized variable; assign a value when the variable is declared. For example: int count =0

Signup and view all the flashcards

Increment/Decrement Operators

Increases (or decreases) the value of a variable by 1. Example: count++;

Signup and view all the flashcards

Rules of Precedence

Determines the order in which arithmetic operations are performed.

Signup and view all the flashcards

Class

Used to produce objects. An object stores data and can take actions defined by methods.

Signup and view all the flashcards

Object

An entity that stores data and can take actions defined by methods.

Signup and view all the flashcards

length() Method

Returns the number of characters in the String object.

Signup and view all the flashcards

Escape Sequence

An explicit character within a java string

Signup and view all the flashcards

String value

Represents a sequence of characters enclosed in double quotes (").

Signup and view all the flashcards

nextLine() Method

Method reads the remainder of the current line, even if is empty

Signup and view all the flashcards

Program Style

Good program practice starts with these elements included.

Signup and view all the flashcards

Input

To allow the program have keyboard input. Name of the package (library) that includes the scanner class

Signup and view all the flashcards

Study Notes

Variables and Values

  • Variables store data, such as numbers and letters, functioning as memory locations to hold information.
  • Variables' values, stored in memory, can be changed during program execution.
  • numberOfBaskets, eggsPerBasket, and totalEggs are examples of variables.
  • eggsPerBasket = 6; and eggsPerBasket = eggsPerBasket - 2; are examples of assigning values to variables.

Naming and Declaring Variables

  • Choose helpful variable names that reflect use, like count or speed instead of just c or s.
  • When declaring a variable, its name and type must be specified; for instance, int numberOfBaskets, eggsPerBasket; declares two integer variables.
  • A variable's type (int, double, char) determines what kind of values it can store.
  • Before use, a variable must be declared to allocate memory and define its type.

Syntax and Examples

  • The general syntax for declaring variables is type variable_1, variable_2, …;.
  • int styleChoice, numberOfChecks;, double balance, interestRate;, and char jointOrIndividual; are valid variable declaration examples.

Types in Java

  • Class types have data and methods; String is an example.
  • "Think Whirled Peas" is a value of the class type String.
  • Primitive types are simple and nondecomposable.
  • int, double, and char are primitive types.

Naming Conventions

  • Class types begin with an uppercase letter, such as String.
  • Primitive types start with a lowercase letter, like int.
  • Variable names of both types begin with a lowercase letter, e.g., myName, myBalance.
  • Multiword names use uppercase letters to separate words, such as userName.

Where to Declare Variables

  • Declare variables just before using them, or at the beginning of a program section enclosed in {}.
  • Variables can be declared at the start of the program, before the statements begin.

Java Identifiers

  • An identifier is a name given to a variable or other program element.
  • Identifiers can include letters, numbers (0-9), underscores (_), and the dollar sign ($).
  • The first character of an identifier cannot be a digit.
  • Identifiers cannot contain spaces, dots (.), or asterisks (*).
  • Java identifiers can be arbitrarily long.
  • stuff, Stuff, and STUFF are treated as distinct identifiers due to Java's case sensitivity.

Keywords or Reserved Words

  • Keywords or reserved words, such as if, have special, predefined meanings in Java.
  • Keywords cannot be used as identifiers.
  • Other keywords examples: int, public, and class.
  • Appendix 1 of the Java documentation contains a complete list of keywords.

Primitive Types

  • Four integer types include byte, short, int, and long, with int being the most common.
  • Two floating-point types, float and double, exist, with double being the more widely used.
  • The char stores a single character.
  • The boolean stores a value of true of false.

Examples of Primitive Values

  • Examples of integer types: 0, -1, 365, 12000.
  • 0.99, -22.8, 3.14159, and 5.0 are floating-point type examples.
  • Character type examples: 'a', 'A', '#'.
  • Boolean type examples: true and false.

Assignment Statements

  • Assignment statements assigns a value to a variable, such as answer = 42;.
  • The "equal sign" (=) is the assignment operator.
  • The variable named answer is assigned the value of 42.

Assignment Statements, cont.

  • Syntax for assignment statements comes in the form variable = expression ;.
  • Expression might be another variable, a literal or constant (like a number), or something more complicated combining operators (like + and -).

Assignment Examples

  • amount = 3.99;, firstInitial = ‘W’;;, score = numberOfCards + handicap;, and eggsPerBasket = eggsPerBasket - 2; are all valid examples of assignment.

Assignment Evaluation

  • The right-hand side expression is evaluated before assigning the result to the left-hand side variable.
  • Consider score = numberOfCards + handicap; and eggsPerBasket = eggsPerBasket - 2; for assignment evaluation.

Specialized Assignment Operators

  • Assignment operators combine with arithmetic operators (-, *, /, %).
  • The code amount = amount + 5; is equivalent to amount += 5;.

Simple Screen Output

  • System.out.println(“The count is “ + count); displays the text and the variable's value.
  • The + performs concatenation, which joins strings together.

Simple Input

  • Programs can get data from the user at runtime.
  • Include import java.util.*; to allow keyboard input.

Simple Input, cont.

  • Entering data from the keyboard often involves first stating Scanner keyboard = new Scanner(System.in);.
  • Followed by reading the keyed value, such as eggsPerBasket = keyboard.nextInt();.

Number Constants

  • Literal expressions, such as 2, 3.7, or 'y', are constants.
  • Integer constants may have a + or - sign but not commas.
  • Floating-point constants can have digits after the decimal point or can be in e notation, like scientific notation.

e Notation

  • e notation expresses scientific or floating-point notation.
  • For example, 865000000.0 becomes 8.65e8, and 0.000483 is 4.83e-4.
  • The value in front of e needs no point, like 4e-4.

Assignment Compatibilities

  • Java is considered strongly typed language; attempting to assign a floating-point value to an integer variable is impermissible.
  • Conversions are possible sometimes: assigning an integer to a double variable is possible.
  • doubleVariable = 7; and doubleVariable = intVariable; are both valid, even if doubleVariable is a double.

Assignment Compatibilities, cont.

  • A value of one type can be assigned to a variable of any type further to the right.:
    • byte -> short -> int -> long -> float -> double
  • Assigning a value further to the left is impermissible.
  • Assign a char value to an int variable.

Type Casting

  • Type casting transforms a value into a new type
  • double distance = 9.0; followed by int points = (int)distance; is type casting.
  • points = (int)distance; requires the (int); without fails.

Type Casting, cont.

  • The expression (int)distance has a value of 9, yet distance remains 9.0.
  • The data type of distance is unchanged
  • Any nonzero components to the right of the decimal are dropped, instead of rounded.

Characters as Integers

  • Characters stored as integers correspond to a special code.
  • Codes for each printable character (letter, number, symbol, space, tab) differ.
  • The upper and lowercase versions of equivalent characters have differing codes.
  • ASCII and Unicode are common character code formats.
  • 97 could stand for 'a', whereas 65 could stand foe 'A'.

Unicode Character Set

  • Many programming languages utilize ASCII.
  • Java uses Unicode, inclusive of ASCII.
  • The Unicode set includes other-than-English language character alphabets.

Casting a char to an Int

  • Casting a char to an int returns its ASCII/Unicode value.
  • The following would display 'y' followed by its ASCII value of 121:
    • char answer = 'y';
    • System.out.println(answer);
    • System.out.println((int)answer);

Initializing Variables

  • Declared variables yet to be value-assigned are uninitialized.
  • Uninitialized class variables return anull value.
  • The default value is available to uninitialized primitive variables.
  • Relying on a default value rather than explicitly initializing can lead to unpredictable results

Initializing Variables, cont.

  • It is best practice to protect against an uninitialized variable - assign a value upon declaration.
  • Integer variables assign a zero value, like int count =0;.
  • String variable' default is "".
  • Character variables assign a simple letter or symbol, like char grade = 'A';.

Initializing Variables, cont.

  • The proper expression syntax is of the form type variable_1 = expression_1, variable_2 = expression_2, …;.

Binary Representation

  • Assume an 8-bit type encoding integers, characters, and floating-point numbers.
  • The integer 5 is represented by the binary 00000101.
  • The character ‘5’ has a binary code of 00110101(53 in decimal from ASCII).

Binary Real Numbers

  • 5.5 has a binary equalivant of 101.1.
  • 5.25 in binary = 101.01.
  • 5.125 in binary = 101.001.
  • 5.75 in binary = 101.11.

Eight Bits Only

  • 5.5 is 101.1 -> 000101 10.
  • 5.25 is 101.01 -> 000101 01.
  • 5.125 is 101.001 -> ??.
  • The precision is .25 with only 2 places after the point.

Floating-point Numbers

  • Decimal number 54.3 is 5.43 x 10¹ in scientific notation.
  • The binary 101.001 is 10.1001 x 2¹ or 1.01001 x 2².
  • The most significant bit always precedes any points.

Floating-Point Numbers

  • Floating point numbers adhere to a defined formulaic format: sign 1.mantissa x 2exponent.
  • Only the area to the right of the decimal requires representation.
  • The exponent is represented by the [IEEE standard: “biased exponent"].

Java Floating-point Numbers

  • A single bit represent the sign: "0" for positive values.
  • The "mantissa" has 23 bits for floar, 52 bits for doubles.
  • The exponent has 8 and 11 bit respectively.

Imprecision in Floating-Point Numbers

  • Storing bits with a finite number may only offer approximations.
  • 1.0/3.0 is slightly less than 1/3 due to bit estimation.
  • The sum 1.0/3.0 + 1.0/3.0 + 1.0/3.0 may be less than 1.

Arithmetic Operations

  • Arithmetic expressions use the operators +, -, *, /.
  • Variables or numbers in the equation are operands.
  • If the involved operands are all of the same type, then the result has that data type.
  • In the presence of a floating-point operand, the others are treated as floating-point to return this data type.

Arithmetic Operations, cont.

  • With hoursWorked (40) x double payRate(8.25), the equation produces a double and returns 500.0.

Arithmetic Operations, cont.

  • Multi-operand expressions computes over single steps involving two operands, used in additional steps, such as:
  • balance + (balance * rate).

Operators with Integer and Floating-point Numbers

  • The presence of a floating-point type operand and the rest as integers returns a floating-point type calculation.

The Division Operator

  • If any operand is a floating-point, the standard division applies.
  • If only integers are present, the answer is truncated to the integer, not even rounded.
  • For instance 99/100, an integer division, equals 0.

The mod Operator

  • The modulo operator (%) returns a remainder integer.
  • As an example, 14 divided by 4 yields a remainder of 2; thus, 14 % 4 is equal to 2.
  • The modulo can determine if an integer is even or odd ("divisible by 2?") or if one number is wholly divisible by another.

Vending Machine Change, a Case Study

  • A vending machine program can meet a requirement to accept a single integer from 1 cent to 99.
  • A coin combination must be derived.
  • Take 55 cents, whose program would yield 2 quarters and 1 nickel.

Case Study, cont.

  • If the program receives 87, or 87 cents, in coins, coins given in change should include:
    • 3 quarters
    • 1 dime
    • 0 nickels
    • 2 pennies

Case study Variables

  • In computing vending changes, at least the following variables must be declared:
  • int amount, quarters, dimes, nickels, pennies;

Case Study, cont.

  • The algorithm at the top, calls for one to complete the following pseudocode tasks:
  1. Read the amount.
  2. Find the maximum number of quarters in the amount.
  3. Subtract the value of the quarters from the amount.
  4. Repeat the last two steps for dimes, nickels, and pennies.
  5. Print the original amount and the quantities of each coin.

Case Study,cont.

  • This type of iterative reduction changes a value, rather than calculating using the original total to return a unique set of variable results.
  • This method calls for updating the types as follows:
  • int amount, originalAmount, quarters, dimes, nickels, pennies;
  • which yields a result by using one line, before iterations, so as not to alter the result due to reduction.

Case Study, cont.

  • Improved algorithm:
  1. Read the amount.
  2. Make a copy of the amount.
  3. Find the maximum number of quarters in the amount.
  4. Subtract the value of the quarters from the amount.
  5. Repeat the last two steps for dimes, nickels, and pennies.
  6. Print the original amount and the quantities of each coin.

Case Study, cont.

  • With a pseudocode algorithm written, Java code implements is the next step .

Case Study, cont.

  • To derive the number of quarters in 55 cents but also two in 65 cents, code returns an equivalent function:
  • 55 / 2 = 2 and 65 / 25 = 2.

Case Study, cont.

  • Using the mod operator determines the remainder:
    • If you have "55 % 25 = 5 and 65 % 25 = 15", determine what remains for dimes and nickels by applying with their denominations.
    • The pennies require merely an amount % 5.

Implementation Testing, cont.

  • Coin denomination should yield zero values.
  • Varying the values may have different outputs in denominations.
  • Some values are: 0,1,98, and 99.
  • Some boundaries are 24, 25, and 26.

Increment (and Decrement) Operators

  • Increment/decrement operators increase/decrease the value of the variable by 1.
  • count++ or ++count are equivalent applications..
  • Decremental operations include count-- or --count.

Increment (and Decrement) Operators

  • Increment/Decrement operations provide an equivalent shorthand.
    • count++; ++count; = count = count + 1; are all valid.
  • Decrement operations examples include:
    • count--; --count; = count = count - 1; are all valid.

Increment (and Decrement) Operators in Expressions

  • Executing int m = 4; int result = 3 * (++m) increments m to 5 before assigning to the result, leaving the result's value as 15.
  • Executing int m = 4; int result = 3 * (m++) assigns the m value to the result, which leaves 12 in the result. Incrementing occurrs only after the m-value was calculated, leaving m now holding the 5.

Increment and Decrement Operator Examples

  • Consider code:
    • int n = 3; int m = 4; int result;
      • result = n * ++m; results in m being 5 and result being 15
      • result = n * m++; results in m being 5 and result being 12
      • result = n * --m; results in m being 3 and result being 9
      • result = n * m--; results in m being 3 and result being 12

Summary of Operators

  • List of operators
  • +, -, *,/
  • %
  • ++, --

Parentheses and Precedence

  • Parentheses are communicative to readers by dictating the order of operations.
  • Consider:
(cost + tax) * discount
cost + (tax * discount)
  • Absent of parentheses, Java resolves the expression by rules of precedence.

Precedence Rules

  • In order from highest-to-lowest precedence: -First: Unary operator e.g. +, -, ++, --, and! -Second: binary arithmetic operators e.g. *, /, and % -Third: binary arithmetic operators e.g. + and -

Precedence Rules—Binary Operators

  • Binary arithmetic operators (*, /, %) have the following trait:
    • Lower precedence than the unary set.
    • Higher precedence than the binary set.
  • When binary operators have the same precedence, the left is evaluated before the right.

Precedence Rules—Unary Operators

  • Under same precedence, the operator to the right acts before that to the left, opposite that performed in binary relationships.
  • Code with x is 10 then evaluating -++xyields -11 afterwards, but x is also 11 afterwards.
  • -++x equals -(++x).
  • Code with x is 10 then evaluating -x++ yields -10 , but and X is 11 afterwards
  • -x++ equals -(x++).

Use Parentheses

  • For code readability, use parentheses.
  • It can also help with making code readable, for instance in: -"balance + (interestRate * balance)"
  • In "balance + interestRate*balance", precedence isn’t mandated.

The Class String

  • "Enter a whole number from 1 to 99.”" is an expression of the type "string".
  • Values of a string, String, are items that feature a sequence of character items.

Declaring and Printing Strings

  • For declaring, some examples of initializing the variable include:
String greeting;
greeting = “Hello!”;
  • Or
 String greeting = “Hello!”;
  • Or
String greeting = new String(“Hello!”);
  • Output calls the function:
System.out.println(greeting);

Concatenation of Strings

  • The + concatenates, or joins two characters.
  • The + syntax include:
String greeting = “Hello”;
String sentence;
sentence = greeting + “ officer”;
System.out.println(sentence);
  • Any number may use the function.

Concatenating Strings and Integer

  • The combination function returns both as String.
  • For instance:
String solution;
solution = “The temperature is “ + 72;
System.out.println (solution);
  • The output becomes:
The temperature is 72

Classes

  • A "class" defines objects, such as a list of items as a type.
  • Every object has properties defined by "methods".
  • Methods return data pertaining to a String by returning character data.
  • The length function returns the total amount of characters in a String.

Objects, Methods, and Data

  • While data can vary, objects still follow the same methods pertaining to that class.
  • Values without methods are primitive types of the same kinds or data.

The Method length()

  • The length function returns an "int".
  • It is best practice to utilize "length()" almost ubiquitously.
  • Consider "int count = solution.length();",System.out.println(solution.length()); and "spaces = solution.length() + 3;".

Positions in a String

  • Index positions count up from zero.
  • Counting "Java is fun.”" starts from its character "J".

Positions in a String, cont.

  • Indexing a character references a position.
  • “Java is fun.” references its 'f' at the 9 index number.

Indexing Characters within a String

  • The charAt(position) method gets a "character" at the supplied "position".

  • "substring(start, end)" returns a "string" through excluding end "charAt()"` .

  • InString greeting = "Hi, there!";

    • greeting.charAt(0) Returns "H"
    • greeting.charAt(2) Returns ","
    • greeting.substring(4,7) returns "the"

Using String Class

  • StringDemo is an example utilization of string and integer variables to generate new output based on "substring" calls.

Escape Characters

  • Use "\\" to use them safely within expressions.
  • When evaluating the string “\”Java\” refers to a language.”, the expression would output:
  • "Java" refers to a language.

Escape Characters

  • These characters utilize multiple symbols to act as one code: \" \' \, a backward slash. \n, a New line. Moves to the beginning of the next line. \r, Carriage return. Moves start at the beginning of the current line. \t, Tab. Adds whitespace up to the next tab.

Examples

  • System.out.println(“abc\\def”); prints abc\def.
  • System.out.println(“new\nline”);prints new, then on another line, prints line.
    • char singleQuote = ‘\’’; -System.out.println(singleQuote);
  • is printed.

The Unicode Character Set

  • ASCII was the old method most programming languages used.
  • Unicode, the successor that Java utilizes, includes all ofASCII's characters.
  • Languages with differing alphabets are integrated into Unicode as well (although you may not intend to use them).

Keyboard and Screen I/O: Outline

  • Screen output.
  • Keyboard input.

Screen Output

  • Many examples are available for display.
  • "System.out" makes this doable by returning results.
  • It makes use of "println()" in Java.

Screen Output cont.

  • Multiple line codes utilize the "+" code:
System.out.println(“When everything “ +“does not fit on one line, use the” +“ concatenation operator (\’+\’)”);

  • Note: breaking occurs before, OR after, the addition symbol.

Screen Output, cont.

  • Utilizing System:
System.out.print(“When everything “);
System.out.print(“does not fit on “);
System.out.print(“one line, use the “);
System.out.print(“\”print\” ”);
System.out.println(“statement”);
  • Make sure to "ending with a println().”".

Screen Output cont.

  • The syntax is "System.out.println(output_1 + output_2 +…+ output_n);"
  • For example (“1967”+ “ " +““ Oldsmobile ““+” “” +442);, produces "1967 Oldsmobile 442".

Output Formatting"

  • This is influenced by C.
  • Calls upon functions "printf (formatString, args…)`".
  • Where the format, can use smileyOutStream.printf(…)".
  • And you determine "formatString" as something like: "("%s %d %f%n", name, id, gpa); is determined, including utilization of " " + id + " " + gpa);`

Formatting String

  • "% width conversion" must be adhered to.
  • The output requires width to be known and satisfied.
  • Code follows the format "printf(“%5d”, count).

Conversion Characters

The following table describes the type of character, "Conversion String" : Argument | Description

  • -- | --- d | Decimal interger Float | Decimal float s |String n |New Line c |Character code Unicode e |Decimal Sci Notation/Floating Point d |Octal Integer d |Hexidecimal Integer d |Output%

Floating-point Precision

  • "width.precision conversion" adheres to "printf(“%5.2f”, PI).
  • and adheres to: "ptintf (“%7.4f” , PI).
  • See code for numerical representation .

Left Justified

  • Codes with padded code are added to the right hand side.
  • Code uses"-%" before the "width".
  • When "printf(“%-7s %-4d”, name, age)" is called, a code such as John 20 will populate.
  • Extra spaces can be manually input.

Keyboard Input

  • Starting from version "5.0", it becomes easier to handle "Inputs".
  • The"Scanner" call is defined within "java.util." by setting up a "package".

Using the Scanner Class

  • At program start, code should "import java.util.*".
  • "New Scanner(System.in)" creates an object.
  • Input values are read from an array.

Some Scanner Class Methods

  • Variables syntax:
  Int_Variable = Object_Name.nextInt();
  Double_Variable = Object_Name.nextDouble();
  Float_Variable = Object_Name.nextFloat();
 
  String_Variable = Object_Name.next();
  String_Variable = Object_Name.nextLine();
 
 `Boolean_Variable = Object_Name.nextBoolean();`

  nextByte(), nextShort(), nextLong()`

Some Scanner Class Method, Cont.

  • Variable assignment:
int count = keyboard.nextInt();
double distance = keyboard.nextDouble();
String word = keyboard.next();
String wholeLine = keyboard.nextLine();
  • Prompt user with "System.out.print("Enter an integer:“);"before asking.

Keyboard Input Demonstration

  • ScannerDemo are various demonstration of keyboard inputs.

Caution nextLine() Method

  • Reminder: the "nextLine()" takes inputs from the remaining lines.
  • Including spaces and blanked out items.

nextLint() Method Caution, cont.

  • For instance, in variable setup:
int n;
String s1, s2;
n = keyboard.nextInt();
s1 = keyboard.nextLine();
s2 = keyboard.nextLine();
  • and having an input of
5440
or bust
  • Will return s2 as a blank or "" item, while s1 outputs everything after 5440.

Other Input Delimiters

  • Separating words are characterized by quotations.
  • These defaults to a whitespace in newline, or tab format

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Introduction to Variables in Programming
40 questions
CSC 1060: Data Types and Variables
5 questions
C++ Variables and Data Types
9 questions

C++ Variables and Data Types

FastGrowingRing5358 avatar
FastGrowingRing5358
Use Quizgecko on...
Browser
Browser