CSC 212 Object-Oriented Programming and Java Part 2.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Java Syntax Primitive data types Operators Control statements.
Loops – While, Do, For Repetition Statements Introduction to Arrays
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
TODAY’S LECTURE Review Chapter 2 Go over exercises.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
3.1 Documentation & Java Language Elements Purpose of documentation Assist the programmer with developing the program Assist other programers who.
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
CSC 212 Object-Oriented Programming and Java Part 1.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
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.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Expressions An expression is a series of variables, operators, and method calls (constructed according to the syntax of the language) that evaluates to.
 The if statement and the switch statement are types of conditional/decision controls that allow your program.  Java also provides three different looping.
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
Introduction to Java Java Translation Program Structure
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Basic Java Syntax COMP 401, Spring 2014 Lecture 2 1/14/2014.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
1 CS161 Introduction to Computer Science Topic #8.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
ECE122 Feb 10, Unary Operator An operator that takes only a single operand Plus: + Minus: – Cast: (type). E.g. (double)
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
C++ LANGUAGE MULTIPLE CHOICE QUESTION
Information and Computer Sciences University of Hawaii, Manoa
Suppose we want to print out the word MISSISSIPPI in big letters.
Lecture 5: Some more Java!
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
JavaScript: Control Statements.
Arrays, For loop While loop Do while loop
Starting JavaProgramming
Chapter 8 JavaScript: Control Statements, Part 2
Additional Control Structures
CSC215 Lecture Flow Control.
elementary programming
The System.exit() Method
Chapter 2 Programming Basics.
In this class, we will cover:
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
CSC215 Lecture Control Flow.
Looping and Repetition
Presentation transcript:

CSC 212 Object-Oriented Programming and Java Part 2

Announcements The end of the Java refresher is nigh! If you need more of a review, seek assistance immediately. I have a cool office. Please drop by and see so for yourself (and ask me questions while you are there).

Student Class public class Student { // declare the fields // define the constructors // define the methods }

The Student Variables public class Student { protected String name, studentID; protected int years_attended; private float gpa, credits; protected static int total_enrollment; // define the constructors // define the methods } // end of class definition

Constructors for Student Constructors are special methods which create instances. Typically initialize fields values. (They can do more – later) public Student (String sname, long ssn) { name = sname; studentID = Long.toString(ssn); years_attended = 0; gpa = credits = 0; total_enrollment = total_enrollment++; }

Additional Constructors Classes can have several constructors  Must differ in parameter lists (signatures). public Student (String sname, String id) { name = sname; studentID = id; years_attended = 0; gpa = credits = 0; total_enrollment++; } public Student () { name = “J Doe”; studentID = “none”; years_attended = 0; gpa = credits = 0; total_enrollment++; }

The Student Class public class Student { protected String name, studentID; protected int years_attended; private float gpa; protected static int total_enrollment; public Student(String sname, long ssn) { … } public Student(String sname, String id) { … } public Student() { … } // define the methods } // end of class definition

public void setId(String newId) { studentID = newId; } Set and Get Methods Provide set and get methods for each field  Controlling access to fields  Limits errors and problems (or amount of searching when debugging)  Common design pattern public String getId() { return(studentID); }

Rules of Thumb Classes are public Fields are private  Outside access only using “get” and “set” methods Constructors are public Get and set methods (if any) are public Other methods on a case-by-case basis

Naming Conventions Variables start with a lower case letter  When name includes multiple words, combine words and use intermediate caps  int xLoc, yLoc;  char choice; Classes begin with an upper case letter  String strVal;  Car bob; No name can match a Java keyword

Things to Remember { } delimit logical blocks of statements Two ways to define comments  /* up to */ defines a block comment  // defines a single line comment Java is case-sensitive  out, Out, OUt, OUT are all different

Primitive Types NameTypeRangeDefault boolean true or falseFalse charcharactersany character\0 intinteger-2 31 – longlong integer-2 63 – floatreal-3.4E38 – 3.4E doubleextended real-1.7E308 – 1.7E

Java Operators ++unary increment (k++  k = k + 1) --unary decrement (k--  k = k-1) !logical negation (!done) %remainder == !=primitive equality/inequality test &&logical and (done && valid) ||logical or (done || flag) =assignment (x = a && b)

Strings String is used like a primitive, but really is a class For example, one can create a string by: String s = "This is a Java string"; Strings are stored as zero or more Unicode characters.

String Operators Basic string operator is concatenation (+) Concatenation joins two strings together: “Strings ” + “joined”  “Strings joined” Numbers can be converted back and forth with strings:  int x = Integer.parseInt(“32”); x  32 float y = Float.parseFloat(“7.69”); y  7.69

toString() Methods Generates representations of objects  Not required, but really useful debugging tool  For example, the Student class could define: public String toString() { return “[Student ” + name + “; ” + studentID + “; GPA=” + Float.toString(gpa) + “]”; }

Arrays Store fixed number of elements of the same type  “length” field contains size of array Student [] roommates = new Student[3]; roommates[0] = new Student(“Al”,1000); roommates[1] = new Student(“Bob”,1050); roommates[2] = new Student(“Carl”, 2000); String name_list = " "; for (int n=0; n<roommates.length; n++) name_list = name_list + roommates[n].getName ()+ ";"; int[] numbers = {1, 2, 3}; // initialized with length 3; numbers[2] == 3 float[][] reals = new float[8][10]; // reals is an array of float arrays

Static members Methods & fields can be declared static Static field is shared by all class objects  All objects see the same value Static methods and fields can be used without creating an instance of the class with the new command.  E.g., ClassName.staticMethod(); or x = ClassName.staticField;

Static members Static methods cannot refer to non-static members of the same class directly.  Like non-class objects, must specify which instance of the class they are referring. Using non-static method or field inside a static method is a common compiler error:  Error: Can't make static reference to method void print() in class test.

if -- else if -- else if -- … -- else if (a == b) {... } else if (a < b) {... } else {... } Only boolean tests are allowed At most 1 branch followed

while loop while (v != b) { … } Only boolean tests are legal Test occurs before loop is entered Loop continues until while test is false  “while (true) { }” loops forever  “while (false) {}” never executes code in loop

do – while loop do { … } while (b < m); do-while performs test after the loop Guarantees loop executed at least once Block bracing (“{“ & “}”) is required  Why?

while vs. do-while loop What is the advantage of one over the other?

for loop Just a while loop with aspirations Typical use: iterate (loop) over set of instances for (initialization; test; modification) { block of code } Executed before starting loop Examined before every iteration Executed after each pass through loop

switch statements int x = …; switch (x) { case 0: System.out.println(“x is 0”); break; case 1: System.out.println(“x is 1”); break; default: System.out.println(“x is not 0 or 1”); } Execution starts at first matching case  Stops at first break statement

What will this code do? int x = 0; … switch (x) { case 0: System.out.println(“x is 0”); case 1: System.out.println(“x is 1”); break; default: System.out.println(“x is not 0 or 1”); }

Explicit Control of Execution break [ ] Exit from any block Can exit multiple blocks using form Unlabeled - terminate innermost Labeled - terminate the appropriate block

What will this code do? outer: for (int i = 0; i < 10; i++) { inner: for (int j = 0; j < I; j++) { if (j == 5) { System.out.println(“i is ” + Integer.toString(i) + “and j is ” + Integer.toString(j)); break; }

What will this code do? outer: for (int i = 0; i < 10; i++) { inner: for (int j = 0; j < I; j++) { if (j == 5) { System.out.println(“i is ” + Integer.toString(i) + “and j is ” + Integer.toString(j)); break outer; }

Explicit Control of Execution continue [ ] Skip to end of loop body; evaluate loop control conditional Can exit multiple levels using form Only in while, do-while, & for loops Unlabeled - continue innermost loop Labeled - continue to an outer loop

What will this code do? outer: for (int i = 0; i < 10; i++) { inner: for (int j = 0; j < I; j++) { if (j + 2 == i) { if (j == 5) continue inner; else System.out.println(“i is ” + Integer.toString(i) + “and j is ” + Integer.toString(j)); }

Explicit Control of Execution return [ ]; terminate execution and return to invoker It is illegal in Java to have code after a return statement!  But only if the code can only be exected after the return statement

Daily Quiz Do problem R-1.13 from the book (p. 52) Write a Java function that takes an integer n and returns the sum of all odd integers smaller than n.