Lecture 5: Some more Java!

Slides:



Advertisements
Similar presentations
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Advertisements

10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Variables Pepper. Variable A variable –box –holds a certain type of value –value inside the box can change Example –A = 2B+1 –Slope = change in y / change.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
CMT Programming Software Applications
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
L EC. 02: D ATA T YPES AND O PERATORS (1/2) Fall Java Programming.
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
CPS120: Introduction to Computer Science Decision Making in Programs.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Introduction to Java Java Translation Program Structure
August 6, 2009 Data Types, Variables, and Arrays.
Copyright Curt Hill Variables What are they? Why do we need them?
CSC 212 Object-Oriented Programming and Java Part 2.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
CSE 110: Programming Language I Matin Saad Abdullah UB 1222.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Chapter VII: Arrays.
Information and Computer Sciences University of Hawaii, Manoa
Lecture 4b Repeating With Loops
Chapter 2 Variables.
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
Objects as a programming concept
Yanal Alahmad Java Workshop Yanal Alahmad
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Object Oriented Programming
Chapter 5: Control Structures II
Multiple variables can be created in one declaration
Variables and Primative Types
Chapter 3: Using Methods, Classes, and Objects
CompSci 230 Software Construction
CompSci 230 Software Construction
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Arrays, For loop While loop Do while loop
Chapter 3 Introduction to Classes, Objects Methods and Strings
Java - Data Types, Variables, and Arrays
Variables ICS2O.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
CMSC 202 Java Primer 2.
Defining methods and more arrays
Expressions and Assignment
elementary programming
The System.exit() Method
Chapter 2 Programming Basics.
Arrays in Java.
Introduction to Primitives
Object Oriented Programming in java
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Unit 3: Variables in Java
Chap 2. Identifiers, Keywords, and Types
Chapter 2 Variables.
Comparing Python and Java
Just Enough Java 17-May-19.
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Corresponds with Chapter 5
Presentation transcript:

Lecture 5: Some more Java! CompSci 230 Software Construction Lecture 5: Some more Java!

Agenda & Reading Topics: Java inside classes COMPSCI 230: OOD2

Semicolons and other delimiters in Java 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. COMPSCI 230: OOD2

Numerical types 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 COMPSCI 230: OOD2

Arrays in Java 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] COMPSCI 230: OOD2

ArrayList in Java 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 COMPSCI 230: OOD2

Strings in Java 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() + "\""); } COMPSCI 230: OOD2

Strings in Java 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!"); System.out.println("Something is fishy with s3 and s4!"); This has consequences: COMPSCI 230: OOD2

Strings in Java 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!"); System.out.println("Something is fishy with s3 and s4!"); This has consequences: Why? Console output: 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! COMPSCI 230: OOD2

String comparison in Java 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. COMPSCI 230: OOD2

Variable scope and local variables in Java 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); COMPSCI 230: OOD2

The this reference 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."; COMPSCI 230: OOD2

The this reference 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."; getsv1(): This is the content of the instance variable. getsv2(): This is the content of a local variable. COMPSCI 230: OOD2

The this reference 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; } COMPSCI 230: OOD2

The this reference 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; } COMPSCI 230: OOD2

if-statements in Java 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! COMPSCI 230: OOD2

for-loops in Java 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 COMPSCI 230: OOD2

while-loops in Java 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 COMPSCI 230: OOD2

Loop examples 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--; COMPSCI 230: OOD2

Returning values from methods 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 COMPSCI 230: OOD2

Review questions 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? COMPSCI 230: OOD2