Podcast
Questions and Answers
Which of the following best describes the purpose of a variable in Java?
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?
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?
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?
How do class types differ from primitive types in Java?
Which of the following naming conventions is generally followed for class types in Java?
Which of the following naming conventions is generally followed for class types in Java?
Which of the following is NOT a valid component of a Java identifier?
Which of the following is NOT a valid component of a Java identifier?
What is the significance of keywords in Java?
What is the significance of keywords in Java?
Which of the following is NOT a primitive data type in Java?
Which of the following is NOT a primitive data type in Java?
Which primitive type is most commonly used for integer values in java?
Which primitive type is most commonly used for integer values in java?
What is the primary function of an assignment statement in Java?
What is the primary function of an assignment statement in Java?
In Java, which side of the assignment operator =
is evaluated first?
In Java, which side of the assignment operator =
is evaluated first?
What operation does the +=
operator perform in Java?
What operation does the +=
operator perform in Java?
Given the following Java code, what will be the output?
int count = 10;
System.out.println("The count is " + count);
Given the following Java code, what will be the output?
int count = 10;
System.out.println("The count is " + count);
What is concatenation in Java, in the context of strings?
What is concatenation in Java, in the context of strings?
To enable keyboard input in a Java program, which of the following import statement is required?
To enable keyboard input in a Java program, which of the following import statement is required?
What is the purpose of the Scanner
class in Java?
What is the purpose of the Scanner
class in Java?
In Java, what is a literal constant?
In Java, what is a literal constant?
Which of the following is a proper way to write 8,650,000,000 in scientific notation in Java?
Which of the following is a proper way to write 8,650,000,000 in scientific notation in Java?
What does it mean for Java to be a strongly typed language?
What does it mean for Java to be a strongly typed language?
What is type casting in Java?
What is type casting in Java?
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?
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?
Which character set does Java use?
Which character set does Java use?
What is the significance of escape sequences in Java strings?
What is the significance of escape sequences in Java strings?
What is the term for a variable that has been declared but has not been assigned a value?
What is the term for a variable that has been declared but has not been assigned a value?
What is the recommended practice in Java regarding uninitialized variables?
What is the recommended practice in Java regarding uninitialized variables?
Which of the following is true when performing arithmetic operations with mixed data types (e.g., int
and double
) in Java?
Which of the following is true when performing arithmetic operations with mixed data types (e.g., int
and double
) in Java?
What is the result of integer division when both operands are integers in Java?
What is the result of integer division when both operands are integers in Java?
What operation does the mod operator (%) perform?
What operation does the mod operator (%) perform?
In Java, what does the term precedence refer to in the context of operators?
In Java, what does the term precedence refer to in the context of operators?
Which of the following has the highest precedence in Java?
Which of the following has the highest precedence in Java?
When unary operators have equal precedence, how is operator precedence determined?
When unary operators have equal precedence, how is operator precedence determined?
Which of the following is the correct way to declare a String
variable named message
and assign it the value Hello, world!
?
Which of the following is the correct way to declare a String
variable named message
and assign it the value Hello, world!
?
What is the index of the first character in a String in Java?
What is the index of the first character in a String in Java?
What is the purpose of the length()
method when used with a String
object in Java?
What is the purpose of the length()
method when used with a String
object in Java?
What does the following Java code output?
System.out.println("abc\\def");
What does the following Java code output?
System.out.println("abc\\def");
What package contains the Scanner
class used for keyboard input in Java?
What package contains the Scanner
class used for keyboard input in Java?
What is the purpose of including comments in Java code?
What is the purpose of including comments in Java code?
What is the difference between //
and /* ... */
comments in Java?
What is the difference between //
and /* ... */
comments in Java?
How is javadoc comment declared?
How is javadoc comment declared?
Why indent Java code?
Why indent Java code?
What is the significance of naming constants in Java?
What is the significance of naming constants in Java?
By convention, how are constants generally named in Java?
By convention, how are constants generally named in Java?
Flashcards
What are Variables?
What are Variables?
Variables store data (numbers, letters). Implemented as memory locations. Can have their value changed.
Declaring a Variable
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
Primitive Type
A simple, nondecomposable value (number or character). Examples: int, double, char.
Primitive Types Convention
Primitive Types Convention
Signup and view all the flashcards
Java Identifier
Java Identifier
Signup and view all the flashcards
Java Keywords
Java Keywords
Signup and view all the flashcards
Integer Types
Integer Types
Signup and view all the flashcards
Floating-point Types
Floating-point Types
Signup and view all the flashcards
char Type
char Type
Signup and view all the flashcards
boolean Type
boolean Type
Signup and view all the flashcards
Assignment Statement
Assignment Statement
Signup and view all the flashcards
Specialized Assignment Operators
Specialized Assignment Operators
Signup and view all the flashcards
String Concatenation
String Concatenation
Signup and view all the flashcards
java.util.*
java.util.*
Signup and view all the flashcards
Scanner Class
Scanner Class
Signup and view all the flashcards
Number Constants
Number Constants
Signup and view all the flashcards
E Notation
E Notation
Signup and view all the flashcards
Type Casting
Type Casting
Signup and view all the flashcards
Characters as Integers
Characters as Integers
Signup and view all the flashcards
Initializing Variables
Initializing Variables
Signup and view all the flashcards
Increment/Decrement Operators
Increment/Decrement Operators
Signup and view all the flashcards
Rules of Precedence
Rules of Precedence
Signup and view all the flashcards
Class
Class
Signup and view all the flashcards
Object
Object
Signup and view all the flashcards
length() Method
length() Method
Signup and view all the flashcards
Escape Sequence
Escape Sequence
Signup and view all the flashcards
String value
String value
Signup and view all the flashcards
nextLine() Method
nextLine() Method
Signup and view all the flashcards
Program Style
Program Style
Signup and view all the flashcards
Input
Input
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
, andtotalEggs
are examples of variables.eggsPerBasket = 6;
andeggsPerBasket = eggsPerBasket - 2;
are examples of assigning values to variables.
Naming and Declaring Variables
- Choose helpful variable names that reflect use, like
count
orspeed
instead of justc
ors
. - 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;
, andchar 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 typeString
.- Primitive types are simple and nondecomposable.
int
,double
, andchar
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
, andSTUFF
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
, andclass
. - Appendix 1 of the Java documentation contains a complete list of keywords.
Primitive Types
- Four integer types include
byte
,short
,int
, andlong
, withint
being the most common. - Two floating-point types,
float
anddouble,
exist, withdouble
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
, and5.0
are floating-point type examples.- Character type examples:
'a'
,'A'
,'#'
. - Boolean type examples:
true
andfalse
.
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;
, andeggsPerBasket = 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;
andeggsPerBasket = eggsPerBasket - 2;
for assignment evaluation.
Specialized Assignment Operators
- Assignment operators combine with arithmetic operators (
-, *, /, %
). - The code
amount = amount + 5;
is equivalent toamount += 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
becomes8.65e8
, and0.000483
is4.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;
anddoubleVariable = intVariable;
are both valid, even ifdoubleVariable
is adouble
.
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 anint
variable.
Type Casting
- Type casting transforms a value into a new type
double distance = 9.0;
followed byint 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, yetdistance
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
andUnicode
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 ofASCII
. - The
Unicode
set includes other-than-English language character alphabets.
Casting a char to an Int
- Casting a
char
to anint
returns itsASCII/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 a
null
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 of00110101
(53 in decimal fromASCII
).
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
is5.43 x 10¹
in scientific notation. - The binary
101.001
is10.1001 x 2¹
or1.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 than1/3
due to bit estimation.- The sum
1.0/3.0 + 1.0/3.0 + 1.0/3.0
may be less than1.
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 returns500.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, equals0
.
The mod Operator
- The modulo operator (%) returns a remainder integer.
- As an example,
14 divided by 4
yields a remainderof 2
; thus,14 % 4
is equal to2
. - 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 to99
. - A coin combination must be derived.
- Take
55 cents
, whose program would yield2
quarters and1
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:
- Read the amount.
- Find the maximum number of quarters in the amount.
- Subtract the value of the quarters from the amount.
- Repeat the last two steps for dimes, nickels, and pennies.
- 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:
- Read the amount.
- Make a copy of the amount.
- Find the maximum number of quarters in the amount.
- Subtract the value of the quarters from the amount.
- Repeat the last two steps for dimes, nickels, and pennies.
- 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
.
- If you have
Implementation Testing, cont.
- Coin denomination should yield
zero values
. - Varying the values may have different outputs in denominations.
- Some values are:
0
,1
,98
, and99
. - Some boundaries are
24
,25
, and26
.
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 to5
before assigning to theresult
, leaving the result's value as15
. - Executing
int m = 4; int result = 3 * (m++)
assigns the m value to theresult
, which leaves12
in the result. Incrementing occurrs only after them-value
was calculated, leavingm
now holding the5
.
Increment and Decrement Operator Examples
- Consider code:
int n = 3; int m = 4; int result;
result = n * ++m;
results inm
being5
andresult
being15
result = n * m++;
results inm
being5
andresult
being12
result = n * --m;
results inm
being3
andresult
being9
result = n * m--;
results inm
being3
andresult
being12
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 byrules 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-++x
yields-11 afterwards
, butx 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 ofcharacter
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()
"` . -
In
String 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 thatJava
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 asJohn 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, whiles1
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.