• No results found

Lecture 5: Java Fundamentals III

N/A
N/A
Protected

Academic year: 2021

Share "Lecture 5: Java Fundamentals III"

Copied!
11
0
0

Loading.... (view fulltext now)

Full text

(1)

School of Science and Technology The University of New England

Trimester 2 2015

Lecture 5: Java Fundamentals III - Operators

• Reading:

Finish readingChapter 2of the 2nd edition of text OR

Finish readingChapter 1of the International edition of the text

• Assignment:

Check the first assignment requirements Collect materials for the first assignment

Creating Constants

• Many programs have data that does not need to be changed.

• Littering programs with literal values can make the program hard do read and main- tain.

• 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.

Creating Constants

• 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.

based on T. Gaddis “Starting Out with Java: From Control Structures through Data Structures”

(2)

• Constants need not be initialized when declared; however, they must be initialized before they are used or a compiler error will be generated.

Creating Constants

• 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.

f i n a l double CAL SALES TAX = 0 . 7 2 5 ;

The String Class

• As stated in the last lecture, Java types can be divided into groups 1. primitive typesand

2. reference types

• Java Strings are an example of a reference type

• Java has no primitive data type that holds a series of characters.

it does have the primitive typecharto hold a single character

• The String class from the Java standard library is used for this purpose.

• In order to be useful, the a variable must be created to reference a String object.

S t r i n g number ;

this can be depicted by the following figure:

• The above statement only creates a reference of type String (not the actual String object)

• the String referencenumber has not been initialised, so it currently references (points to)null

(3)

• Notice the ‘S’ in String is upper case.

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

Primitive vs. Reference Variables

• Primitive variables actually contain the value that they have been assigned.

i n t numValue = 2 5 ;

• The value 25 will be stored in the memory location associated with the variable numValue

• Objects are not stored in variables, however.

+

Note: Objects are referenced by variables.

Primitive vs. Reference Variables

• 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.

S t r i n g cityName = "Charleston " ;

StringObjects

• A variable can be assigned a String literal.

S t r i n g value = "Hello" ;

Strings are the only objects that can be created in this way.

(i.e., without the use of thenewkeyword)

• Usually, an instance of an object is created by using the new keyword.

S t r i n g value ;

value = new S t r i n g ( "Hello" ) ;

1. The first statement creates a reference of type String named value (it currently references (points to)null

2. The second statement creates the actual String object, initialises it with the string Hello and sets the String reference value to point to it.

(4)

these 2 statements can be combined into 1 statement S t r i n g value = new S t r i n g ( "Hello" ) ;

this can be depicted by the following figure:

• the String reference value, references the String object, which contains the Hello string literal.

The use of the new keyword is the method that all other objects must use when they are created.

See examples:StringDemo.javaand alsoStringDemo1.java

The program StringDemo:

/ / A s i m p l e program d e m o n s t r a t i n g S t r i n g o b j e c t s .

/ / n o t e we a r e c r e a t i n g S t r i n g o b j e c t s WITHOUT t h e u s e o f ”new” k e y w o r d public c l a s s StringDemo

{

public s t a t i c void main ( S t r i n g [ ] a r g s ) {

S t r i n g g r e e t i n g = "Good morning " ; S t r i n g name = "Herman" ;

System . out . p r i n t l n ( g r e e t i n g + name ) ; }

}

can be depicted graphically being executed by the following figure:

(5)

• here 2 different String references (greeting and name) point to 2 different String objects (one contains the literal string ”Good morning” and the other ”Herman”)

The String Methods

• Since String is a class, objects that are instances of it have methods.

• One of those methods is the length() method. this can be depicted by the following figure:

• Note: objects in general contain data and methods

(6)

the data (in this case) being the literal string Hello one of the methods being the length() method.

• to invoke the length() method of a String object, you specify the variable name followed by a dot followed by the method name, e.g.,

value . l e n g t h ( ) ;

• This statement invokes the length method on the object pointed to by the value variable.

See example:StringLength.java

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

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.)

Commenting Code

• Java provides three methods for commenting code.

(7)

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 com- ment 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 com- piler. This comment type cannot be nested.

Commenting Code

• 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, for example:

javadoc Comment3.java

Ï

• The javadoc program will createjavadoc/index.htmland several other documenta- tion files in the same directory as the input file.

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

Indentation

• Programs should use proper indentation.

• Each block of code should be indented a few spaces from its surrounding block.

(8)

• 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

The Scanner Class

• So far we have only seen how to output something to the console using System.out e.g., the Java statement:

System . out . p r i n t l n ( "HelloWorld" ) ;

• We also need to be able to read input into our program.

• To read input from the keyboard we can use the Scanner class.

the Scanner class is a predefined class that is part of the Java API.

(Just like the String class is a predefined class that is part of the Java API)

Importing Packages

• All of the standard Java classes in included with Java are stored in a package called java

• the basic language functions are stored in a package inside of the java package called java.lang

• normally you would have to import every package or class that you want to use, but since Java is useless without mych of the functionability in java.lang , it is imported implicitly by the compiler for all Java programs.

this is equivalent to having the following line placed at the beginning of every Java source code file:

import j a v a . lang . ∗ ;

so instead of having to have this line in every Java program, the designers of the language loading java.lang by default

• The Scanner class is defined in java.util, so we will to enter the following state- ment at the top of our programs to be able to use it:

import j a v a . u t i l . Scanner ;

(9)

The Scanner Class

• Scanner objects work with System.in to enable it to get input from the keyboard.

• To create such a Scanner object, we can use the following statement:

Scanner keyboard = new Scanner ( System . i n ) ;

the System.in part connects our Scanner object to standard input i.e., the keyboard

• Scanner class methods are listed in the text, and in the Java API SeePayroll.javaas an example of how they are used

Converting String Input to Numbers

• From time to time we may need a way to convert a “string” that is composed of num- bers, into a numeric type

(e.g., to be able to use it in a calculation)

User entry via graphical dialog boxes is treated as a string in Java it is up to the programmer to convert it to the required type

• Each of the numeric wrapper classes, (covered later in the next trimester) has a method that converts a string to a number

(assuming that the string contains only numbers)

The Integer class has a method that converts a string to an int, The Double class has a method that converts a string to a double.

• These methods are known as parse methods because their names begin with the word

“parse”.

(10)

The Parse Methods

/ / S t o r e 1 i n bVar .

byte bVar = Byte . p a r s e B y t e ( "1" ) ; / / S t o r e 2599 i n i V a r .

i n t iVar = I n t e g e r . p a r s e I n t ( "2599" ) ; / / S t o r e 10 i n sVar .

s h o r t sVar = S h o r t . p a r s e S h o r t ( "10" ) ; / / S t o r e 15908 i n l V a r .

long lVar = Long . parseLong ( "15908" ) ; / / S t o r e 1 2 . 3 i n f V a r .

f l o a t fVar = F l o a t . p a r s e F l o a t ( "12.3" ) ; / / S t o r e 7 9 4 5 . 6 i n dVar .

double dVar = Double . parseDouble ( "7945.6" ) ;

The System.exit( ) method

• normally a Java program stops executing when the end of the main method is reached.

there are times where this does not happen

e.g., with non-consol programs → graphical programs

there are also times when you would like a Java program to terminate before the end of the main method is reached.

• the System.exit( exit code ) method can be used in these instances to terminate program execution

this method needs to have an argument supplied to it when it is invoked.

the argument required for the System.exit method is an integer value that corre- sponds to an exit code.

this exit code is passed back to the operating system when the program termi- nates:

for example, the statement:

System . e x i t ( 0 ) ;

terminates the program and sends an error code (integer value) of 0 back to the operating system.

an exit code value of 0 is traditionally used to indicate that the program ended successfully

(11)

Things to Do

Reading: Finish readingChapter 2of the 2nd edition of text OR

Finish readingChapter 1of the International edition of the text Next Lecture: “Software Development”

References

Related documents

Argentina, Bolivia, Brazil, Colom- bia, Costa Rica, Cuba, Guatemala, Mexico, Panama, Paraguay, Peru, Puerto Rico, Surinam, Trinidad, and Venezuela.. Megistopoda

Java class in this output statement example below displays all such a string with java programs output string examples pdf or a string objects in java.. JAVA for Beginners Search

The string object that perform mathematical operations like numbers, if we can access instance data type and initialization using this tutorial will learn about a colon between

I capacity() – returns the current allocated size of the string object (allocation might be larger than current usage, which is the length). I resize(X, CH) – changes the

As a service provider of credit grantors and larger market participant collection agencies, we know the following compliance requirements have been required of agencies and debt

10’ & 20’ Alumalite Displays: Classic, Lineare, Zero - Dye-sub fabric & Counters 8’, 10’ Pop-Ups – All Fabric Panels (Quick Ship Colors: Coal, Silver, Imperial).

[r]

Proportion of diabetes type 2 (T2DM) care trajectory (CT) patients with > = 3 HbA1c measures around CT start, in comparison with T2DM patients on a diabetes convention 3A