• Tidak ada hasil yang ditemukan

Semicolons and other delimiters in Java

N/A
N/A
Protected

Academic year: 2023

Membagikan "Semicolons and other delimiters in Java"

Copied!
21
0
0

Teks penuh

(1)

Lecture 5: Some more Java!

CompSci 230

Software Construction

(2)

Agenda & Reading

COMPSCI 230: OOD2 2

Topics:

Java inside classes

(3)

Semicolons and other delimiters in Java

COMPSCI 230: OOD2 3

You’ve probably worked out by now that we use a semicolon at the end of each statement

We need this because whitespace does not terminate a statement

Strings are delimited by double quotes: "This is a string"

Double quotes inside strings must be escaped with a backslash:

"She said \"Hello\" when she entered the room“

Note that a String in Java is always an object.

Internally, strings are terminated by a null character.

Individual characters are delimited by single quotes:

char c = 'a';

Note that char is a primitive type.

(4)

Numerical types

COMPSCI 230: OOD2 4

int: signed four-byte integer, can store numbers between -231 and +231-1.

There are no unsigned versions of integers in Java (unlike in, e.g., C/C+

+)

long: a signed eight-byte integer, can store numbers between -263 and +263-1.

float: four-byte floating point number

double: eight-byte floating point number

char: technically a two-byte integer, interpreted as a Unicode character

boolean: technically a one-bit integer, implemented as a one-byte integer, with possible values true and false.

This is only a selection

(5)

Arrays in Java

COMPSCI 230: OOD2 5

are objects, but the syntax differs a little from the usual object notation.

All elements in an array must be of the same type.

A reference x to an array object with elements of type myType is declared as: myType[] x;

When we instantiate an array, we must specify its size, which we cannot change later. We can specify the size either as an integer variable or number. Using the declaration above, we can instantiate the array with 42 elements as: x = new myType[42];

Java arrays are zero-myType[41]based: The first element of this array is myType[0] and the last is

If we want to know the length of an array, we can read its length property: x.length

Note that we cannot set this property, and note that it is not a method. This is because the array’s length is known from instantiation and does not change.

We can write to, or read, the i-th element of the array as myType[i]

(6)

ArrayList in Java

COMPSCI 230: OOD2 6

The ArrayList<E> class provides a more flexible array-like interface

The E stands for the type of elements that the ArrayList will store

E.g., ArrayList<double> is an ArrayList that stores elements of type double

We access elements of an ArrayList not via the square bracket notation, but via methods such as get(), set(), add() and others.

The big advantage of an ArrayList is that it resizes automatically as we add or remove elements

Note: the length of the list can be computed via its size() method

(7)

Strings in Java

COMPSCI 230: OOD2 7

Java strings are objects, with methods:

public class StringDemo {

public static void main(String[] args) {

String s = "COMPSCI230 really is like a walk in the park";

System.out.println("The string is \"" + s + "\"");

System.out.println("It has " + s.length() + " characters.");

System.out.println("In lower case: \"" + s.toUpperCase() +

"\"");

} }

(8)

Strings in Java

COMPSCI 230: OOD2 8

This has

consequences:

String s1 = "COMPSCI230 really is like a walk in the park";

String s2 = "COMPSCI230 really is like a walk in the park";

System.out.println("s1: " + s1);

System.out.println("s2: " + s2);

if (s1 == s2) {

System.out.println("Hooray! Our strings s1 and s2 match!");

} else {

System.out.println("Something is fishy with s1 and s2!");

}

String s3 = "COMPSCI230 really is like a walk in the park";

String s4 = "COMPSCI230 really is like ";

s4 += "a walk in the park";

System.out.println("s3: " + s3);

System.out.println("s4: " + s4);

if (s3 == s4) {

System.out.println("Hooray! Our strings s3 and s4 match!");

} else {

System.out.println("Something is fishy with s3 and s4!");

}

(9)

Strings in Java

COMPSCI 230: OOD2 9

This has

consequences:

Why?

String s1 = "COMPSCI230 really is like a walk in the park";

String s2 = "COMPSCI230 really is like a walk in the park";

System.out.println("s1: " + s1);

System.out.println("s2: " + s2);

if (s1 == s2) {

System.out.println("Hooray! Our strings s1 and s2 match!");

} else {

System.out.println("Something is fishy with s1 and s2!");

}

String s3 = "COMPSCI230 really is like a walk in the park";

String s4 = "COMPSCI230 really is like ";

s4 += "a walk in the park";

System.out.println("s3: " + s3);

System.out.println("s4: " + s4);

if (s3 == s4) {

System.out.println("Hooray! Our strings s3 and s4 match!");

} else {

System.out.println("Something is fishy with s3 and s4!");

}

s1: COMPSCI230 really is like a walk in the park s2: COMPSCI230 really is like a walk in the park Hooray! Our strings s1 and s2 match!

s3: COMPSCI230 really is like a walk in the park s4: COMPSCI230 really is like a walk in the park Something is fishy with s3 and s4!

Console output:

(10)

String comparison in Java

COMPSCI 230: OOD2 10

When we use the == operator with Java strings, Java checks whether the String objects are in the same

location in memory

If two strings are in different locations, == evaluates to false even if the strings have the same content!

String constants are often economically stored in the same location by the compiler, so s1 and s2 appear to be equal here.

For real equality testing, we need the equals() method of the String object: s1.equals(s2)

evaluates to true if s1 and s2 have the same content, even if they are stored in different locations.

(11)

Variable scope and local variables in Java

COMPSCI 230: OOD2 11

Any variable in Java is visible to code in the {}-block in which it is declared, from the moment it is declared.

With the exception of public class and instance variables, it is not visible to code outside.

If we have an (“outer”) {}-block that contains another

(“inner”) {}-block, then any variable declared in the inner block conflicts with any variable of the same name

declared in the outer block before the inner block.

If a variable of the same name is declared in the outer block after the inner block, it’s OK:

public static void main(String[] args) { if (true) {

int i = 2; // inner block (if-statement)

System.out.println("Inside the if-statement: i=" + i);

}

int i = 1; // outer block (main() method)

System.out.println("After the if-statement: i=" + i);

}

(12)

The this reference

COMPSCI 230: OOD2 12

Note that so far, we have treated instance variables inside methods as if they were local variables in the class.

What if our local variables have the same name as instance variables?

What do getsv1() and

getsv2() return here?

public class SomeClass { private String s;

public SomeClass() {

s = "This is the content of the instance variable.";

}

public String getsv1() { return s;

}

public String getsv2() {

String s = "This is the content of a local variable.";

return s;

} }

(13)

The this reference

COMPSCI 230: OOD2 13

Note that so far, we have treated instance variables inside methods as if they were local variables in the class.

What if our local variables have the same name as instance variables?

What do getsv1() and

getsv2() return here?

public class SomeClass { private String s;

public SomeClass() {

s = "This is the content of the instance variable.";

}

public String getsv1() { return s;

}

public String getsv2() {

String s = "This is the content of a local variable.";

return s;

} }

getsv1(): This is the content of the instance variable.

getsv2(): This is the content of a local variable.

(14)

The this reference

COMPSCI 230: OOD2 14

The same happens even if the instance variables / methods are class variables / methods

Conclusion: local variables in methods “eclipse”

instance and class variables

OK, so we could use a different name for the local variable. But sometimes, we really want to use the same name. This is in particular the case when the

“local variable” is a constructor parameter:

Wouldn’t it be nice if we could use counterValue as the parameter name as well?

public SimpleInitialisableCounter(int initialValue) {

counterValue = initialValue;

}

(15)

The this reference

COMPSCI 230: OOD2 15

Good news: Even though local variables eclipse instance and class variables, we can still get at the instance or class variables by

putting a this. in front of the instance variable name. Like so:

The this reference is a reference to the object instance on which the method (or constructor) is being executed.

Note that this also lets you access class methods or variables.

BTW: The same trick allows you to access methods if there is a

local method of the same name (a method declared inside another method)

public SimpleInitialisableCounter(int counterValue) {

this.counterValue = counterValue;

}

(16)

if-statements in Java

COMPSCI 230: OOD2 16

We have already seen examples of Java if-statements

Two general forms, following C/C++ syntax

Simple form: if (condition) statement;

Example: if (x > y) System.out.println(x);

We use this form if we do not need an else branch and the if branch contains a single statement only

Full form:

if (condition) { statements-if-true } else { statements-if- false }

As usual, the curly braces denote blocks of code to be carried out if the condition is true or false.

Note that there is no colon in an if-statement – this is not Python!

(17)

for-loops in Java

COMPSCI 230: OOD2 17

For-loops in Java follow the C/C++ syntax:

for (initialisation; loop_condition; loop_end_action) loop_body;

The initialisation usually consists of declaring a loop variable and setting it to an initial value

The loop condition is a condition like those used in if-statements (usually involving the loop variable). It is evaluated before the loop body executes

The loop end action is the action that is performed after the loop body has executed, e.g., increment the loop variable

The loop body is usually a {}-block

Initialisation and loop end action may contain multiple statements separated by commas

(18)

while-loops in Java

COMPSCI 230: OOD2 18

while-loops also follow the C/C++ convention:

while (condition) loop_body;

The condition is evaluated before the execution enters the loop body

The loop body is usually a {}-block

(19)

Loop examples

COMPSCI 230: OOD2 19

System.out.print("Counting to three:

");

for (int i=1; i<4; i++) {

System.out.print(i + " ");

}

System.out.println();

System.out.print("Counting down: ");

int i=10;

while (i > 0) { i--;

System.out.print(i + " ");

}

System.out.println();

(20)

Returning values from methods

COMPSCI 230: OOD2 20

If a Java method is not declared as void, it must return a value of the specified type

Note that the compiler cannot second-guess what happens in your algorithm – it wants an appropriate return statement at every exit point:

public int returnDemo() { int a, i;

for (i = 0; i<100; i++) { a = i*i;

if (a > 25) return i;

}

return i; // need this line even if we never get here

}

(21)

Review questions

COMPSCI 230: OOD2 21

Name six primitive Java data types and two data types that are not primitive

How does determining the length of a Java array differ from determining the length of a Java string?

How would you declare an ArrayList with String elements?

What do you need to do if you want to extend a Java array by one element?

How do you check whether two Java String objects contain the same string of characters?

Where does a local variable in Java go out of scope?

What is this used for?

What are the three sections in the round parentheses of a Java for-loop?

What obligation does the declaration of a method return type place on the programmer?

Referensi

Dokumen terkait

The result of this study found that there were six categories of grammatical cohesive and three Lexical Cohesion used as follows: personal reference, demonstrative reference,

Creating a community around your brand is another great strategy that can help build brand awareness, increase traffic to your website and ultimately increase sales during