Lecture 5: Java Fundamentals III



Similar documents
Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Some Scanner Class Methods

Install Java Development Kit (JDK) 1.8

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

6.1. Example: A Tip Calculator 6-1

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Introduction to Java. CS 3: Computer Programming in Java

Chapter 2: Elements of Java

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Chapter 3. Input and output. 3.1 The System class

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Introduction to Programming

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I

Object-Oriented Programming in Java

Building Java Programs

Moving from CS 61A Scheme to CS 61B Java

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Java Crash Course Part I

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Building Java Programs

Introduction to Java

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

AP Computer Science Java Subset

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

CS106A, Stanford Handout #38. Strings and Chars

13 File Output and Input

Java Interview Questions and Answers

Java Programming Fundamentals

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Variables, Constants, and Data Types

Java CPD (I) Frans Coenen Department of Computer Science

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

Chapter 2 Introduction to Java programming

Hypercosm. Studio.

Sources: On the Web: Slides will be available on:

Contents. 9-1 Copyright (c) N. Afshartous

COMP 356 Programming Language Structures Notes for Chapter 4 of Concepts of Programming Languages Scanning and Parsing

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Fundamentals of Java Programming

An Overview of Java. overview-1

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Explain the relationship between a class and an object. Which is general and which is specific?

J a v a Quiz (Unit 3, Test 0 Practice)

Programming Languages CIS 443

Pemrograman Dasar. Basic Elements Of Java

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Programmierpraktikum

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Comp 248 Introduction to Programming

PL / SQL Basics. Chapter 3

csce4313 Programming Languages Scanner (pass/fail)

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Illustration 1: Diagram of program function and data flow

Example of a Java program

Chapter 2 Basics of Scanning and Conventional Programming in Java

Continuous Integration Part 2

Introduction to Python

Week 1: Review of Java Programming Basics

VB.NET Programming Fundamentals

Chapter 2 Elementary Programming

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Introduction to Java Applets (Deitel chapter 3)

Java Program Coding Standards Programming for Information Technology

The C Programming Language course syllabus associate level

Introduction to Visual C++.NET Programming. Using.NET Environment

Crash Course in Java

Java Application Developer Certificate Program Competencies

java Features Version April 19, 2013 by Thorsten Kracht

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Using Files as Input/Output in Java 5.0 Applications

Computer Programming I

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

CS 111 Classes I 1. Software Organization View to this point:

2 Getting Started with jgrasp 2.0

LAB4 Making Classes and Objects

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Chapter 1 Java Program Design and Development

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Intro to Web Programming. using PHP, HTTP, CSS, and Javascript Layton Smith CSE 4000

WHAT ARE PACKAGES? A package is a collection of related classes. This is similar to the notion that a class is a collection of related methods.

Notepad++ The COMPSCI 101 Text Editor for Windows. What is a text editor? Install Python 3

Chapter 13 - The Preprocessor

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

CSE 308. Coding Conventions. Reference

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

3.5. cmsg Developer s Guide. Data Acquisition Group JEFFERSON LAB. Version

Programming Project 1: Lexical Analyzer (Scanner)

Transcription:

Lecture 5: Java Fundamentals III School of Science and Technology The University of New England Trimester 2 2015 Lecture 5: Java Fundamentals III - Operators Reading: Finish reading Chapter 2 of the 2nd edition of text OR Finish reading Chapter 1 of 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 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. 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 1

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 types and 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 type char to 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 reference number has not been initialised, so it currently references (points to) null Trimester 2 2015 2 The University of New England

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 " ; String Objects 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 the new keyword) 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. The University of New England 3 Trimester 2 2015

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.java and also StringDemo1.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 use o f new keyword public c l a s s StringDemo { public s t a t i c void main ( S t r i n g [ ] args ) { 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: Trimester 2 2015 4 The University of New England

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 The University of New England 5 Trimester 2 2015

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. length ( ) ; 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. Trimester 2 2015 6 The University of New England

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. 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 create javadoc/index.html and several other documentation 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. The University of New England 7 Trimester 2 2015

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 java. 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 statement at the top of our programs to be able to use it: import java. u t i l. Scanner ; Trimester 2 2015 8 The University of New England

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 See Payroll.java as 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 numbers, 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. The University of New England 9 Trimester 2 2015

The Parse Methods / / S t o r e 1 in bvar. byte bvar = Byte. parsebyte ( "1" ) ; / / S t o r e 2599 in ivar. 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 in svar. short svar = Short. parseshort ( "10" ) ; / / S t o r e 15908 in lvar. long lvar = Long. parselong ( "15908" ) ; / / S t o r e 1 2. 3 in fvar. f l o a t fvar = F l o a t. p a r s e F loat ( "12.3" ) ; / / S t o r e 7945.6 in 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 corresponds to an exit code. this exit code is passed back to the operating system when the program terminates: 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 Trimester 2 2014 10 The University of New England

Things to Do Reading: Finish reading Chapter 2 of the 2nd edition of text OR Finish reading Chapter 1 of the International edition of the text Next Lecture: Software Development The University of New England 11 Trimester 2 2014