Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
41 views

Ch02-Java Fundamentals

Uploaded by

Nurina Johari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Ch02-Java Fundamentals

Uploaded by

Nurina Johari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Starting Out with Java Control Structures

Through Objects
Eighth Edition

Chapter 2

Java Fundamentals

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Chapter Topics (1 of 2)
• Chapter 2 discusses the following main topics:
– The Parts of a Java Program
– The print and println Methods, and the Java API
– Variables and Literals
– Primitive Data Types
– Arithmetic Operators
– Introduction to JShell
– Combined Assignment Operators

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Chapter Topics (2 of 2)
– Creating named constants with final
– The String class
– Scope
– Declaring Local Variables with the var Keyword
– Comments
– Programming style
– Using the Scanner class for input

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Parts of a Java Program (1 of 4)
• A Java source code file contains one or more Java
classes.
• If more than one class is in a source code file, only one
of them may be public.
• The public class and the filename of the source code
file must match.
– ex: A class named Simple must be in a file named
Simple.java
• Each Java class can be separated into parts.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Parts of a Java Program (2 of 4)
• See example: Simple.java
• To compile the example:
– javac Simple.java
▪ Notice the .java file extension is needed.
▪ This will result in a file named Simple.class being
created.
• To run the example:
– java Simple
▪ Notice there is no file extension here.
▪ The java command assumes the extension is .class.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Analyzing The Example (1 of 3)

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Analyzing The Example (2 of 3)

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Analyzing The Example (3 of 3)

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Parts of a Java Program (3 of 4)
• Comments
– The line is ignored by the compiler.
– The comment in the example is a single-line comment.
• Class Header
– The class header tells the compiler things about the class
such as what other classes can use it (public) and that it is
a Java class (class), and the name of that class (Simple).
• Curly Braces
– When associated with the class header, they define the
scope of the class.
– When associated with a method, they define the scope of
the method.
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
Parts of a Java Program (4 of 4)
• The main Method
– This line must be exactly as shown in the example (except
the args variable name can be programmer defined).
– This is the line of code that the java command will run first.
– This method starts the Java program.
– Every Java application must have a main method.
• Java Statements
– When the program runs, the statements within the main
method will be executed.
– Can you see what the line in the example will do?

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Java Statements (1 of 2)
• If we look back at the previous example, we can see that
there is only one line that ends with a semi-colon.
System.out.println("Programming is great
fun!");

• This is because it is the only Java statement in the


program.
• The rest of the code is either a comment or other Java
framework code.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Java Statements (2 of 2)
• Comments are ignored by the Java compiler so they need no
semi-colons.
• Other Java code elements that do not need semi colons
include:
– class headers
▪ Terminated by the code within its curly braces.
– method headers
▪ Terminated by the code within its curly braces.
– curly braces
▪ Part of framework code that needs no semi-colon
termination.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Short Review (1 of 2)
• Java is a case-sensitive language.
• All Java programs must be stored in a file with a .java file
extension.
• Comments are ignored by the compiler.
• A .java file may contain many classes but may only have
one public class.
• If a .java file has a public class, the class must have the
same name as the file.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Short Review (2 of 2)
• Java applications must have a main method.
• For every left brace, or opening brace, there must be a
corresponding right brace, or closing brace.
• Statements are terminated with semicolons.
– Comments, class headers, method headers, and
braces are not considered Java statements.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Special Characters
Marks the beginning of a single line
// double slash
comment.
open and close Used in a method header to mark the
()
parenthesis parameter list.
Encloses a group of statements, such
open and close curly
{} as the contents of a class or a
braces
method.

Encloses a string of characters, such


“” quotation marks as a message that is to be printed on
the screen
Marks the end of a complete
; semi-colon
programming statement

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Console Output (1 of 8)
• Many of the programs that you will write will run in a
console window.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Console Output (2 of 8)
• The console window that starts a Java application is
typically known as the standard output device.
• The standard input device is typically the keyboard.
• Java sends information to the standard output device by
using a Java class stored in the standard Java library.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Console Output (3 of 8)
• Java classes in the standard Java library are
accessed using the Java Applications Programming
Interface (API).
• The standard Java library is commonly referred to
as the Java API.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Console Output (4 of 8)
• The previous example uses the line:
System.out.println("Programming is great fun!");

• This line uses the System class from the standard Java
library.
• The System class contains methods and objects that
perform system level tasks.
• The out object, a member of the System class, contains
the methods print and println.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Console Output (5 of 8)
• The print and println methods actually perform the
task of sending characters to the output device.
• The line:
System.out.println("Programming is great fun!");

is pronounced: System dot out dot print line

• The value inside the parenthesis will be sent to the


output device (in this case, a string).

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Console Output (6 of 8)
• The println method places a newline character at the
end of whatever is being printed out.
• The following lines:
System.out.println("This is being printed out");
System.out.println("on two separate lines.");

Would be printed out on separate lines since the first


statement sends a newline command to the screen.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Console Output (7 of 8)
• The print statement works very similarly to the println statement.
• However, the print statement does not put a newline character at the
end of the output.
• The lines:
System.out.print("These lines will be");
System.out.print("printed on");
System.out.println("the same line.");

Will output:
These lines will beprinted onthe same line.

Notice the odd spacing? Why are some words run together?

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Console Output (8 of 8)
• For all of the previous examples, we have been printing
out strings of characters.
• Later, we will see that much more can be printed.
• There are some special characters that can be put into
the output.
System.out.print("This line will have a newline at the end.\n");

• The \n in the string is an escape sequence that


represents the newline character.
• Escape sequences allow the programmer to print
characters that otherwise would be unprintable.
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
Java Escape Sequences (1 of 2)
Advances the cursor to the next line for
\n newline
subsequent printing
Causes the cursor to skip over to the next
\t tab
tab stop
Causes the cursor to back up, or move left,
\b backspace
one position
Causes the cursor to go to the beginning of
\r carriage return
the current line, not the next line
\\ backslash Causes a backslash to be printed
Causes a single quotation mark to be
\’ single quote
printed
Causes a double quotation mark to be
\” double quote
printed

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Java Escape Sequences (2 of 2)
• Even though the escape sequences are comprised of two characters, they
are treated by the compiler as a single character.
System.out.print("These are our top sellers:\n");
System.out.print("\tComputer games\n\tCoffee\n ");
System.out.println("\tAspirin");

• Would result in the following output:

These are our top seller:


Computer games
Coffee
Asprin

• With these escape sequences, complex text output can be achieved.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Variables and Literals (1 of 2)
• A variable is a named storage location in the computer’s
memory.
• A literal is a value that is written into the code of a
program.
• Programmers determine the number and type of
variables a program will need.
• See example:Variable.java

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Variables and Literals (2 of 2)

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


The + Operator
• The + operator can be used in two ways.
– as a concatenation operator
– as an addition operator
• If either side of the + operator is a string, the result will be a string.

System.out.println("Hello " + "World");


System.out.println("The value is: " + 5);
System.out.println("The value is: " + value);
System.out.println("The value is: " + ‘/n’ + 5);

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


String Concatenation (1 of 3)
• Java commands that have string literals must be treated
with care.
• A string literal value cannot span lines in a Java source
code file.
System.out.println("This line is too long
and now it has spanned more than one line,
which will cause a syntax error to be
generated by the compiler. ");

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


String Concatenation (2 of 3)
• The String concatenation operator can be used to fix this problem.

System.out.println("These lines are " +


"are now ok and will not " +
"cause the error as before.");

• String concatenation can join various data types.

System.out.println("We can join a string to " +


"a number like this: " + 5);

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


String Concatenation (3 of 3)
• The Concatenation operator can be used to format
complex String objects.
System.out.println("The following will be printed " +
"in a tabbed format: " +
\n\tFirst = " + 5 * 6 + ", " +
"\n\tSecond = " (6 + 4) + "," +
"\n\tThird = " + 16.7 + ".");

• Notice that if an addition operation is also needed, it must


be put in parenthesis.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Identifiers (1 of 2)
• Identifiers are programmer-defined names for:
– classes
– variables
– methods
• Identifiers may not be any of the Java reserved
keywords.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Identifiers (2 of 2)
• Identifiers must follow certain rules:
– An identifier may only contain:
▪ letters a–z or A–Z,
▪ the digits 0–9,
▪ underscores (_), or
▪ the dollar sign ($)
– The first character may not be a digit.
– Identifiers are case sensitive.
▪ itemsOrdered is not the same as itemsordered.
– Identifiers cannot include spaces.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Java Reserved Keywords
abstract double instanceof static
assert else int strictfp
boolean enum interface super
break extends long switch
byte false native synchronized
case final new this
catch finally null throw
char float package throws
class for private transient
const goto protected true
continue if public try
default implements return void
do import short volatile
while

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Variable Names
• Variable names should be descriptive.
• Descriptive names allow the code to be more readable;
therefore, the code is more maintainable.
• Which of the following is more descriptive?
double tr = 0.0725;
double salesTaxRate = 0.0725;

• Java programs should be self-documenting.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Java Naming Conventions
• Variable names should begin with a lowercase letter and then
switch to title case thereafter:
Ex: int caTaxRate

• Class names should be all title case.


Ex: public class BigLittle

• More Java naming conventions can be found at:


http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html

• A general rule of thumb about naming variables and classes


are that, with some exceptions, their names tend to be nouns
or noun phrases.
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
Primitive Data Types
• Primitive data types are built into the Java language and
are not derived from classes.
• There are 8 Java primitive data types.
– byte – float
– short – double
– int – boolean
– long – char

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Numeric Data Types
byte 1 byte Integers in the range
−128 to +127
negative 128 to + 127

short 2 bytes Integers in the range of


to + 32,767
negative 32,768 to + 32,767
−32,768
int 4 bytes Integers in the range of
to + 2,147,483,647
negative 2,147,483,648 to + 2,147,483,647
−2,147,483,648
long 8 bytes Integers in the range of
−9,223,372,036,854,775,808 to
negative 9,223,372,036,854,775,808 to + 9,223,372,036,854,775,807

+9,223,372,036,854,775,807
float 4 bytes Floating-point numbers in the range of
± 3.410
+ or 3838toto +±or 3.41038,
−minus
minus 3.410 minus 3.41038, with 7 digits of accuracy
double 8 bytes Floating-point numbers in the range of
± 1.710
+ or − 308
minus 1.710 minus 308 minus 1.710308, with 15 digits of accuracy
toto±+ or1.710308,
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
Variable Declarations
• Variable Declarations take the following form:
– DataType VariableName;
▪ byte inches;
▪ short month;
▪ int speed;
▪ long timeStamp;
▪ float salesCommission;
▪ double distance;

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Integer Data Types
• byte, short, int, and long are all integer data
types.
• They can hold whole numbers such as 5, 10, 23, 89, etc.
• Integer data types cannot hold numbers that have a
decimal point in them.
• Integers embedded into Java source code are called
integer literals.
• See Example: IntegerVariables.java

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Floating Point Data Types
• Data types that allow fractional values are called
floating-point numbers.

– 1.7 and −45.316 are floating-point numbers.


• In Java there are two data types that can represent
floating-point numbers.
– float - also called single precision (7 decimal
points).
– double - also called double precision (15 decimal
points).

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Floating Point Literals (1 of 3)
• When floating point numbers are embedded into Java
source code they are called floating point literals.
• The default type for floating point literals is double.
– 29.75, 1.76, and 31.51 are double data types.
• Java is a strongly-typed language.
• See example: Sale.java

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Floating Point Literals (2 of 3)
• A double value is not compatible with a float variable
because of its size and precision.
– float number;
– number = 23.5; // Error!
• A double can be forced into a float by appending the
letter F or f to the literal.
– float number;
– number = 23.5F; // This will work.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Floating Point Literals (3 of 3)
• Literals cannot contain embedded currency symbols or
commas.
– grossPay = $1,257.00; // ERROR!
– grossPay = 1257.00; // Correct.
• Floating-point literals can be represented in scientific
notation.
– 47,281.97 = = 4.728197 × 10 4.
• Java uses E notation to represent values in scientific
notation.
4
– 4.728197 × 10 =4.728197E4.
=

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Scientific and E Notation
Decimal Notation Scientific Notation E Notation
247.91 2.4791× 102 2.4791E2
2.4791 times 10 squared

0.00072 7.2 × 10 −4 7.2E-4


7.2 times 10 to the negative fourth power

2,900,000 2.9E6
2.9 times 10 to the sixth power

2.9 × 106

See example: SunFacts.java

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


The boolean Data Type
• The Java boolean data type can have two possible
values.
– true
– false
• The value of a boolean variable may only be copied into
a boolean variable.

See example: TrueFalse.java

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


The char Data Type
• The Java char data type provides access to single
characters.
• char literals are enclosed in single quote marks.
– ‘a’, ‘Z’, ‘\n’, ‘1’
• Don’t confuse char literals with string literals.
– char literals are enclosed in single quotes.
– String literals are enclosed in double quotes.

See example: Letters.java

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Unicode (1 of 5)
• Internally, characters are stored as numbers.
• Character data in Java is stored as Unicode characters.
• The Unicode character set can consist of 65536 (216 )
individual characters.
• This means that each character takes up 2 bytes in memory.
• The first 256 characters in the Unicode character set are
compatible with the ASCII* character set.

See example: Letters2.java


*American Standard Code for Information Interchange

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Unicode (2 of 5)

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Unicode (3 of 5)

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Unicode (4 of 5)

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Unicode (5 of 5)

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Variable Assignment and
Initialization (1 of 6)

• In order to store a value in a variable, an assignment


statement must be used.
• The assignment operator is the equal (=) sign.
• The operand on the left side of the assignment operator
must be a variable name.
• The operand on the right side must be either a literal or
expression that evaluates to a type that is compatible
with the type of the variable.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Variable Assignment and
Initialization (2 of 6)
// This program shows variable assignment.
public class Initialize
{
public static void main(String[] args)
{
int month, days;
month = 2;
days = 28;
System.out.println("Month " + month + " has " +
days + " Days.");
}
}

The variables must be declared before they can be used.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Variable Assignment and
Initialization (3 of 6)
// This program shows variable assignment.
public class Initialize
{
public static void main(String[] args)
{
int month, days;
month = 2;
days = 28;
System.out.println("Month " + month + " has " +
days + " Days.");
}
}

Once declared, they can then receive a value (initialization);


however the value must be compatible with the variable’s
declared type.
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
Variable Assignment and
Initialization (4 of 6)
// This program shows variable assignment.
public class Initialize
{
public static void main(String[] args)
{
int month, days;
month = 2;
days = 28;
System.out.println("Month " + month + " has " +
days + " Days.");
}
}

After receiving a value, the variables can then be used in


output statements or in other calculations.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Variable Assignment and
Initialization (5 of 6)
// This program shows variable initialization.

public class Initialize


{
public static void main(String[] args)
{
int month = 2, days = 28;
System.out.println("Month " + month + " has " +
days + " Days.");
}
}

Local variables can be declared and initialized on the


same line.
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
Variable Assignment and
Initialization (6 of 6)
• Variables can only hold one value at a time.
• Local variables do not receive a default value.
• Local variables must have a valid type in order to be used.
public static void main(String [] args)
{
int month, days; // No value given…

System.out.println("Month " + month + " has " +


days + " Days.");
}

Trying to use uninitialized variables will generate a


Syntax Error when the code is compiled.
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
Arithmetic Operators (1 of 2)
• Java has five (5) arithmetic operators.

Operator Meaning Type Example

+ Addition Binary total = cost + tax;

-
Negativ e sym bol.

Subtraction Binary cost = total – tax;

* Multiplication Binary tax = cost * rate;

/ Division Binary salePrice = original / 2;

% Modulus Binary remainder = value % 5;

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Arithmetic Operators (2 of 2)
• The operators are called binary operators because they
must have two operands.
• Each operator must have a left and right operator.

See example: Wages.java

• The arithmetic operators work as one would expect.


• It is an error to try to divide any number by zero.
• When working with two integer operands, the division
operator requires special attention.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Integer Division
• Division can be tricky.
In a Java program, what is the value of 1/ 2?
• You might think the answer is 0.5…
• But, that’s wrong.
• The answer is simply 0.
• Integer division will truncate any decimal remainder.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Operator Precedence
• Mathematical expressions can be very complex.
• There is a set order in which arithmetic operations will be
carried out.

Operator Associativity Example Result


-
Higher Right to left x = −4 + 3; −1
(unary negation)
Negative symbol, unary negation Negative One

Priority

Operator Associativity Example Result


x = −4 + 4 %
Left to right 11
*/% 3 * 13 + 2;
asterisk slash percent symbols

Lower
Priority x = 6 + 3 − 4
Left to right 23
+- + 6 * 3;
+ minus symbols

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Grouping with Parenthesis
• When parenthesis are used in an expression, the inner
most parenthesis are processed first.
• If two sets of parenthesis are at the same level, they are
processed left to right.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Introduction to JShell (1 of 4)
• JShell is an interactive program that lets you enter Java
programming statements and immediately see each
statement’s results.
• To start JShell enter the command jshell at your
system’s command prompt.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Introduction to JShell (2 of 4)
• At the jshell> prompt, enter a Java programming
statement and press Enter.

• The statement will be executed, and its results will be


displayed
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
Introduction to JShell (3 of 4)
• Declaring variables in JShell

• To see a list of all declared variables, use the /vars


command
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
Introduction to JShell (4 of 4)
• To see a list of all the statements you have entered in the
current session, use the /list command

• To exit JShell, use the /exit command

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Combined Assignment Operators (1 of 2)

• Java has some combined assignment operators.


• These operators allow the programmer to perform an
arithmetic operation and assignment with a single
operator.
• Although not required, these operators are popular since
they shorten simple equations.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Combined Assignment Operators (2 of 2)

Operator Example Equivalent Value of variable after operation

+= x += 5; x = x + 5; The old value of x plus 5.

-= y -= 2; y = y – 2; The old value of y minus 2

*= z *= 10; z = z * 10; The old value of z times 10

/= a /= b; a = a / b; The old value of a divided by b.

The remainder of the division of the


%= c %= 3; c = c % 3;
old value of c divided by 3.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Creating Constants with final (1 of 3)

• Many programs have data that does not need to be


changed.
• Littering programs with literal values can make the
program hard do read and maintain.
• Replacing literal values with constants remedies this
problem.
• Constants allow the programmer to use a name rather
than a value throughout the program.
• Constants also give a singular point for changing those
values when needed.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Creating Constants with final (2 of 3)

• Constants keep the program organized and easier to


maintain.
• Constants are identifiers that can hold only a single
value.
• Constants are declared using the keyword final.
• Constants need not be initialized when declared;
however, they must be initialized before they are used or
a compiler error will be generated.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Creating Constants with final (3 of 3)

• Once initialized with a value, constants cannot be


changed programmatically.
• By convention, constants are all upper case and words
are separated by the underscore character.

final int CAL_SALES_TAX = 0.725;

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


The String Class
• Java has no primitive data type that holds a series of
characters.
• The String class from the Java standard library is used
for this purpose.
• In order to be useful, a variable must be created to
reference a String object.
String number;

• Notice the S in String is upper case.


• By convention, class names should always begin with an
uppercase character.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Primitive v s Reference Variables (1 of 2)
ersu

• Primitive variables actually contain the value that they


have been assigned.
number = 25;

• The value 25 will be stored in the memory location


associated with the variable number.
• Objects are not stored in variables, however. Objects are
referenced by variables.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Primitive v s Reference Variables (2 of 2)
ersu

• When a variable references an object, it contains the


memory address of the object’s location.
• Then it is said that the variable references the object.
String cityName = "Charleston";

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


String Objects
• A variable can be assigned a String literal.
String value = "Hello";

• Strings are the only objects that can be created in this


way.
• A variable can be created using the new keyword.
String value = new String("Hello");

• This is the method that all other objects must use when
they are created.
See example: StringDemo.java
Copyright © 2022 Pearson Education, Inc. All Rights Reserved
The String Methods
• Since String is a class, objects that are instances of it
have methods.
• One of those methods is the length method.
stringSize = value.length();

• This statement runs the length method on the object


pointed to by the value variable.

See example: StringLength.java

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


String Methods
• The String class contains many methods that help
with the manipulation of String objects.
• String objects are immutable, meaning that they
cannot be changed.
• Many of the methods of a String object can create
new versions of the object.

See example: StringMethods.java

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Scope
• Scope refers to the part of a program that has access to
a variable’s contents.
• Variables declared inside a method (like the main
method) are called local variables.
• Local variables’ scope begins at the declaration of the
variable and ends at the end of the method in which it
was declared.

See example: Scope.java (This program contains an


intentional error.)

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Declaring Local Variables with var (1 of 3)

• An alternative way to declare local variables


• Use var instead of a data type, and provide an
initialization value
• Example:
var amount = 100;
• The initialization value 100 is an int, so the data type of
the amount variable will be int

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Declaring Local Variables with var (2 of 3)

• Other examples:
var interestRate = 12.0;
var stockCode = "D465U";
var limit = 1000L;
• After this code executes, interestRate will be a
double, stockCode will be a String, and limit
will be a long

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Declaring Local Variables with var (3 of 3)

• Limitations:
– var can be used only to declare local variables
(variables that are declared inside a method)
– You cannot use var to declare multiple variables in
the same statement
– You must provide an initialization value when you
declare a variable with var

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Commenting Code (1 of 3)
• Java provides three methods for commenting code.

Comment Style Description

Single line comment. Anything after the // on the line will be


//
ignored by the compiler.

Block comment. Everything beginning with /* and ending with


/* … */ the first */ will be ignored by the compiler. This comment type
cannot be nested.

Javadoc comment. This is a special version of the previous


block comment that allows comments to be documented by
/** … */ the javadoc utility program. Everything beginning with the /**
and ending with the first */ will be ignored by the compiler.
This comment type cannot be nested.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Commenting Code (2 of 3)
• Javadoc comments can be built into HTML
documentation.
• See example: Comment3.java
• To create the documentation:
– Run the javadoc program with the source file as an
argument
– Ex: javadoc Comment3.java
• The javadoc program will create index.html and
several other documentation files in the same directory
as the input file.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Commenting Code (3 of 3)
• Example index.html:

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Programming Style
• Although Java has a strict syntax, whitespace characters
are ignored by the compiler.
• The Java whitespace characters are:
– space
– tab
– newline
– carriage return
– form feed
See example: Compact.java

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Indentation
• Programs should use proper indentation.
• Each block of code should be indented a few spaces
from its surrounding block.
• Two to four spaces are sufficient.
• Tab characters should be avoided.
– Tabs can vary in size between applications and
devices.
– Most programming text editors allow the user to
replace the tab with spaces.

See example: Readable.java


Copyright © 2022 Pearson Education, Inc. All Rights Reserved
The Scanner Class (1 of 2)
• To read input from the keyboard we can use the
Scanner class.
• The Scanner class is defined in java.util, so we will
use the following statement at the top of our programs:

import java.util.Scanner;

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


The Scanner Class (2 of 2)
• Scanner objects work with System.in
• To create a Scanner object:

Scanner keyboard = new Scanner (System.in);

• Scanner class methods are listed in Table 2-17 in the


text.
• See example: Payroll.java

Copyright © 2022 Pearson Education, Inc. All Rights Reserved


Copyright

This work is protected by United States copyright laws and is


provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.

Copyright © 2022 Pearson Education, Inc. All Rights Reserved

You might also like