Classes Basic Overview

Similar documents
Simple Java Reference

Mr. Monroe s Guide to Mastering Java Syntax

HST 952. Computing for Biomedical Scientists Lecture 8

Introduction to Programming Using Java (98-388)

Java Input/Output. 11 April 2013 OSU CSE 1

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

1. An operation in which an overall value is computed incrementally, often using a loop.

Course Outline. Introduction to java

Pace University. Fundamental Concepts of CS121 1

Full file at

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

CSC 1214: Object-Oriented Programming

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

APPENDIX A: SUMMARY OF IMPORTANT JAVA FEATURES

CS111: PROGRAMMING LANGUAGE II

Lesson 3: Accepting User Input and Using Different Methods for Output

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Today s plan Discuss the Bb quiz 1 Clarify Lab 1 Review basic Java materials Classes, Objects, Interfaces Strings Java IO. Understanding Board

CS111: PROGRAMMING LANGUAGE II

1. Download the JDK 6, from

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Java Basic Programming Constructs

CS313D: ADVANCED PROGRAMMING LANGUAGE

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

Java Primer 1: Types, Classes and Operators

Computational Expression

CS 231 Data Structures and Algorithms, Fall 2016

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Input from Files. Buffered Reader

Today s plan Discuss the Lab 1 Show Lab 2 Review basic Java materials Java API Strings Java IO

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Java Bytecode (binary file)

Principles of Computer Science I

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

Text User Interfaces. Keyboard IO plus

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

Using Java Classes Fall 2018 Margaret Reid-Miller

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

Introduction Unit 4: Input, output and exceptions

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.

MIDTERM REVIEW. midterminformation.htm

Data Structure and Programming Languages

The Java language has a wide variety of modifiers, including the following:

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

Binghamton University. CS-140 Fall Data Types in Java

Lex and Yacc. More Details

Java+- Language Reference Manual

4 WORKING WITH DATA TYPES AND OPERATIONS

Selected Questions from by Nageshwara Rao

Lecture Set 4: More About Methods and More About Operators

COMP200 INPUT/OUTPUT. OOP using Java, based on slides by Shayan Javed

Program Fundamentals

Chapter 9 Lab Text Processing and Wrapper Classes

Simple Java Programming Constructs 4

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CS 161: Object Oriented Problem Solving

CSC Java Programming, Fall Java Data Types and Control Constructs

PROGRAMMING FUNDAMENTALS

Computer Science II (20082) Week 1: Review and Inheritance

CS 170 Java Programming 1. Week 10: Loops and Arrays

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

4 Programming Fundamentals. Introduction to Programming 1 1

Computer Components. Software{ User Programs. Operating System. Hardware

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Chapter 4 Defining Classes I

What did we talk about last time? Examples switch statements

Software Practice 1 Basic Grammar

Object-Oriented Programming

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

A Quick and Dirty Overview of Java and. Java Programming

Programming with Java

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Important Java terminology

Computer Science is...

Lab 5: Java IO 12:00 PM, Feb 21, 2018

F I N A L E X A M I N A T I O N

A sample print out is: is is -11 key entered was: w

Contents Chapter 1 Introduction to Programming and the Java Language

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

The Basic Parts of Java

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

CS163/164 Final Exam Study Session

Language Reference Manual

Transcription:

Final Review!!! Classes and Objects Program Statements (Arithmetic Operations) Program Flow String In-depth java.io (Input/Output) java.util (Utilities) Exceptions

Classes Basic Overview A class is a container for data values (attributes) and actions (methods). It can contain only actions (generally done with static methods only). It can also contain both in which case it usually describes an object either tangible or abstract. This blueprint of an object needs to have a special method that gives initial values to the attributes (constructor). Examples of only action classes: -Integer (contains action to convert String to int) -Math (contains a bunch of math functions: sqrt, cos, arctan,...) Examples of Blueprint classes: -Employee(Attributes: name, position, salary, Actions: getpay) -Board (Attributes: board, Actions: usermove, full)

Classes Basic Overview //import statements here import java.io.*;... public class <classname> { //attributes private <type> <name>; private int x;... //constructors public <classname> (<params>) { public <classname> (int x1) { x = x1;... //methods public <returntype> <methodname> (<params>) { //code to do action //return if returntype is not void public int getx () { return x;...

Classes Attributes An Attribute is a variable that is stored within the class that describes a value that the object the class describes has. These are primarily defined a private since, we do not want anyone explicitly changing the value. They are defined outside any method body, but are within the class, as such any method within the class has access to it as well. This in contrast to local variables that are defined within methods...only the method which the variable is defined in has access. public class Attr { private int x; public Attr () { x = 0; public void localdemo() { int y = 5; System.out.println( X is +x); System.out.println( Y is +y); public void globaldemo() { System.out.println( X is +x); System.out.println( Y is +y); //Ok since x is an attribute //Ok since y is local variable in the current method //Ok since x is an attribute //ERROR! Y only exists within the localdemo method

Classes Attributes Since attributes are variables, but defined in the class scope, they follow the same rules as local variables. They must be defined once and only once, this is done inside the class (refer to slide 3). They must be declared with the keyword private then the data type, common data types are below, they can take on any reference type (i.e. class name, see slides from week 9 (Point attribute in the Circle class)): Common Data Types: -int -double -char -boolean -String

Classes Attributes Attributes can take on array types as well. Arrays are accessed using indexes ranging from [0, size-1] Generic description of Arrays below: Array Declaration: <type> [] <name>; //sets up memory for an array (no size yet) Array Assignment: <name> = new <type> [<size>]; //sets the size of the array Array Initialization <type> [] <name> = new <type> [<size>]; //creates an array of specified size //and type Array Access: <name>[<index>] //gets the value store in the array at index

Classes Constructors A Constructor's job is to set-up an object initially, they should assign starting values to the attributes (e.g. In Point it set the x, y coordinates to 0, 0). Constructors can take parameters just like methods, and use them for the initialization process. Constructors are always defined as public, and have no return type. They also have the EXACT same name as the class, case and all. Then they have parenthesis for any parameters. e.g. If you have a class called Point you could have the two constructors: public Point() { x = 0; y = 0; public Point(int px, int py) { x = px; y = py;

Classes Methods Methods usually begin with the public keyword and are followed by the return type...this is the kind of information (int, double, String,...) that the method passes back to the code that is making the method call (invoking code). These methods behave like queries, (e.g. gameover, getpay,...) Methods that do not return data, behave like commands, doing a specific action (e.g. usermove, displayboard,...), these methods specify their return type as void. Methods can have parameters, which are values that are passed from the invoking code to the method. Example: // takes an integer for the number of hours worked from the invoking code // returns the total pay for the week public double getpay (int hours){ return salary * hours; //assume salary is an attribute

Program Statements Program Statements are commands that perform a specific action, or determine program flow and are what are executed by the program. These appear only within methods. Java begins with the statements found in the main method: public static void main(string [] args) { Statements that perform a specific action always end in semi-colons. Common examples are ones that modify the value of variables, or print to the screen. Statements that control the flow of the program, usually end in braces, as these enclose code for possible paths (e.g. if a condition is true perform the statements within a set of braces)

Statements Method Calling You can call methods, jump to the method's body and execute the statements that are there to perform a series of steps in one line. This is why we have methods: Calling static methods (parseint is static) <classname>.<methodname>( <arguments> ); //executes methodname which is from classname, and is passed //values specified as arguments Calling non-static methods (need an object created) <classname> <objname> = new <classname> ( <constructorargs> ); //creates an object of type classname <objname>.<methodname>( <arguments> ); //executes methodname which is from classname

Statements - Printing Two statements exist for printing: System.out.print( <What is to be printed> ); //this prints out the text specified and sets the cursor on //the same line so that whatever is printed next appears on //the same line System.out.print( <What is to be printed> ); //this prints out the specified text, and sets the cursor //to the next line so that the next set of text to be //printed appears on the following line.

Statements - Arithmetic Numeric Variables (int, double) can be modified using built-in operations: + addition - subtraction * multiplication / division % modulus = Assignment, stores what is on the right side into the left e.g. x = 5 stores the value 5 into the variable x.

Program Flow if, else The if statement uses conditionals to determine what code to run. When the condition evaluates to true then the code following the if-statement is run, using braces specifies a set of statements to run. Using an else in conjunction will result in the code following the else to be run when the condition evaluates to false. The code continues as normal after ifstatement is finished if ( <condition> ) { //code to run when condition is true else { //code to run when condition is false Note: else part is optional

Program Flow Conditions There exists some commands that can be used to compare: == checks to see if variables/values on both sides are equivalent < strictly less than <= less-than or equal > strictly greater than >= greater-than or equal!= not equal combines two conditionals with an OR statement && combines two conditionals with an AND statement

Program Flow Loops Loops repeat a section of code repeatedly until a condition is false (in the case of while and do-while loops), or a specific number of times (forloop). The generic form of the while & do-while are described below: while ( <condition> ) { //code to run, when condition is true, will not //stop until condition is false do { //same as while, except, code run first then //checked. while (<condition> );

Program Flow Loops for loops are loops that typically use counter variables (integer variables that either keep track of the number of times the loop has run, or refers to an index of an array or String). Initialization sets the counter variable to a starting value, condition behaves the same as in all other loops, and update is where you alter the counter variables value in order to progress the loop to a terminating state. for ( <initialization>; <condition>; <update> ){ //code that is repeated while the condition is met

String - Methods The String class is a special type that is built into java. It has several builtin methods. Since it is a class (reference type) you cannot use == to compare two Strings. equals <stringname1>.equals( <stringname2> ); //returns either true if stringname1 matches (case and all) stringname2 substring <stringname1>.substring( <index> ); //returns a new String that contains every letter including and past the letter //at index from the String stringname1 <stringname1>.substring( <index1>, <index2> ); //returns a new String that contains every letter including and past the letter //at index1 up to but not including the letter at index2 from the String //stringname1 charat <stringname1>.charat( <index> ); //returns a char, it is the letter that appears in stringname1 at index

Strings - Converting Any information that is stored as a String can be converted to numeric data using a parse method from either the Integer or Double class. int conversion Integer.parseInt( <stringname> ); //returns an int, the integer represenation of stringname double conversion Double.parseDouble( <stringname> ); //returns an int, the integer represenation of stringname

java.io User Input The following section is devoted to the code that is used when using the import command: import java.io.*; User Input: BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); //creates a BufferedReader object that is linked to the command-line //(System.in) String input = r.readline(); //waits for user input, and reads in what the user types by storing it in //the variable named input...use String conversion to get as an integer.

java.io Reading/Writing File Reading: BufferedReader r = new BufferedReader(new FileReader(< filename >)); //creates a BufferedReader object that is linked to the specified file String input = r.readline(); //reads a line from the file and stores it in the variable named //input...this will have the value null if the end of the file has been //reached File Writing: PrintWriter pw = new PrintWriter(new BufferedWriter( new FileWriter(< filename >); //creates a PrintWriter object that is linked to the specified file pw.println(< text >); //writes a line to the file that is specified by text which is a String //works the same way System.out.println(..) does, only writing to the file //and not the console. Make sure to use either pw.close() or r.close() when finished reading and writing

java.util Random The following section is devoted to the code that is used when using the import command: import java.util.*; Random: Random rand = new Random(); //creates a Random object that is able to generate random numbers int num = rand.nextint(< number >); //generates a random number in the range of 0 to (number-1), and stores it //into the variable num

java.util StringTokenizer StringTokenizer: StringTokenizer st = new StringTokenizer(< fullstring >, < delimiter >); //creates a StringTokenizer object named st that is able to get substrings //of fullstring that separated by all the characters in the delimiter //String String token = st.nexttoken(); //gets the next substring from the tokenizer that has not been extracted //yet, and stores it into the variable named token. boolean isdone = st.hasmoretokens(); //checks to see if there are any tokens in the tokenizer that have not //been examined, if there are some left then true is stored in the //variable isdone, otherwise it is false. Used with loops.

Exceptions Exception: is an error that occurs during run-time. Unlike compiler errors which are problems with syntax, where the computer doesn't understand what the programmer wants, an exception occurs when the computer knows what it needs to do...it just can't due to specific circumstances (due to user input is a good example). Generic Format of a try-catch block: try{ //Code that might cause problems catch (<TypeOfException> e) { //Code to handle the exception

Final Time The final will be next week during lab period, it is designed for an hour period, but you have the full two hours if you need it. It will cover all material from throughout the entire semester, but have a larger focus on methods, and classes.