Writing methods and Java Statements. Java program import package; // comments and /* … */ and /** javadoc here */ public class Name { // instance variables.

Slides:



Advertisements
Similar presentations
DONT PANIC!! Lots of new notions coming in these slides Dont worry if not all of it makes perfect sense Well meet most of this stuff again in detail later.
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Lecture 1: Comments, Variables, Assignment. Definitions The formal (human-readable) instructions that we give to the computer is called source code The.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 2 1 Chapter 2 Primitive.
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.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
11-Jun-15 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand.
CPSC150 JavaDr. L. Lambert CPSC150 Fall 2005 Dr. L Lambert.
CPSC150 Spring 2006 Dr. L Lambert. Week 1/2 intro (and Chapter 1)
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
Objects Interaction and Source Code Week 2. OBJECT ORIENTATION BASICS REVIEW.
Classes with multiple methods Part 1. Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs.
Review. By the end of today you should be able to- Know how to use args Know how to use the JOptionPane Know how to convert a String to a number.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Relational Operators Control structures Decisions using “if” statements  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Understanding class definitions Looking inside classes.
Writing methods. Calling Methods nameOfMethod(parameters) if method returns something, use that value Math.pow(2, 3) returns 8 System.out.println(Math.pow(2,
Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
CPSC150 Spring 2007 Dr. L. Lambert. CPSC150 Overview Syllabus Use Textbook, ask questions, extra thorough, I will post sections covered All information.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Classes CS 21a: Introduction to Computing I First Semester,
1. 2 Reference... Student stu; Reference of Student stu When the reference is created it points to a null value. Before access the reference, objects.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 2 - Introduction to Java Applications Outline 2.1Introduction 2.2A Simple Program: Printing a.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Types CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 4, Horstmann text)
Static Class Methods CSIS 3701: Advanced Object Oriented Programming.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Applications Development
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
Java Basics Variables, Expressions, Statements, etc. CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo.
Data Types, Variables, and Arithmetic Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Elementary Programming.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
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.
Topic: Classes and Objects
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
2.5 Another Java Application: Adding Integers
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2 Edited by JJ Shepherd
Classes, Encapsulation, Methods and Constructors (Continued)
Recap Week 2 and 3.
Tonga Institute of Higher Education
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Java Programming Language
In this class, we will cover:
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Presentation transcript:

Writing methods and Java Statements

Java program import package; // comments and /* … */ and /** javadoc here */ public class Name { // instance variables or fields // constructors. with no parameters is Default // methods }

Methods public/private returntype name ( /* parameter list */ ) { // statements } public void myMethod( ) { // empty body }

Writing our own method: calcVolume public double calcVolume( ) { // NO private in local variables; final for constants final double PI = ; double volume; // or george. call it anything volume = 4 / 3 * PI * radius * radius * radius; return volume; }

Class Details: Methods public double calcVolume( ) { // NO private in local variables; final double PI = ; double volume; volume = 4 / 3 * PI * radius * radius * radius; return volume; } Java statements inside body, e.g., single = assignment return type double first line signature or header (visible in external view also) return statement Local variable and constant stuff inside curly braces is method body

Method vs. InstanceVariable Both have private or public Both have types Both have names instance variables have ‘;’ at end of line/methods do not methods have ( ) (even without parameters); instance variables do not methods have a body; instance variables do not instance variables have memory to hold information; methods do not

instance variable (field) vs. Local variable local variables declare in a method; instance variables outside of all methods local variables have the lifetime of the method call local variables and instance variables have type and ‘;’ local variables do NOT have private/public designation when possible, use local variables

Writing methods: Java statements must be within a method Arithmetic Expressions Compound Assignment System.out.println new dot notation: external method calls return JOptionPane

Arithmetic +, /, *, -, % Be careful about integer division Use codepad (Choose view, then codepad) – int answer=30; answer = answer % 4; System.out.println("Answer is " + answer);

Compound Assignment assignment: –answer = factor1 * factor2; –answer = answer + newsum; compound assignment –answer += newsum; –answer -= diff; –answer *= product; // e.g., factorial –answer /= digit; // getting rid of digits –answer %= digit; single increment –++count OR count++; // does the same as count += 1 –--count OR count--; // does the same as count -=1

Math Problems int x=3; double y=4.0; x + y // this is ok even though different types x / 2 y / 3 x % 2 x % 3 x++ x += 5 x = y; // ok, but truncated x *= 2 // ++, --, +=, etc. work for doubles also

Writing methods: More Java statements Arithmetic Expressions Compound Assignment System.out.println new dot notation: external method calls return JOptionPane

System.out.println( ) To print out messages to a terminal Can print strings or integers Use + to concatenate/append. Be careful with numbers e.g., –System.out.println("Answer is " + answer); –System.out.println(answer + answer); –System.out.println(“answer is” + answer + answer);

Writing methods: More Java statements Arithmetic Expressions Compound Assignment System.out.println new dot notation: external method calls return JOptionPane

new, dot notation public void draw() { wall = new Square( ); wall.moveVertical(80); wall.changeSize(100); wall.makeVisible(); //rest of method from Picture class } To create a new object, use new. calls constructor External method call dot notation

Most important slide of CS150: Objects, new, dot To declare an object: –NameOfType variableName; To create the object, call its constructor with new –variableName = new NameOfType( ); /* often, caps is class & constructor, lowercase is variable/object. 2 different things. caps is type of dog, lowercase, actual dog */ –name = new Name( ); To do something with the object, use variableName dot methodname –variableName.DoSomething( );

New practice on board Declare a variable george of type Picture. Call its constructor. Call george's draw method (use dot notation. to call a method within a class, no dots).

Practice Assume that there is a Fraction class that has a write method which prints the Fraction, and two constructors, one that creates some default Fraction value and one that allows two parameters to be passed (e.g., Fraction(3, 4) would create the fraction 3/4). Write a UseFraction class that has two instance variables, both Fractions. Make one the default value and other 4/7. Print both of them out.

CNU campus Write two classes, one a Building class and one a Campus class. Buildings have names, number of floors, square feet. Write getName, getFloors, getFeet methods. Campuses have 3 buildings and a name, a print method that prints school name and building info Write a Building class; write a Campus class; Create a campus class. Call its print method

Writing methods: More Java statements Arithmetic Expressions Compound Assignment System.out.println new dot notation: external method calls return JOptionPane

return statement public double calcVolume( ) { // NO private in local variables; final for constants final double PI = ; double volume; volume = 4 / 3 * PI * radius * radius * radius; return volume; } type of method is return type to return a value, use ‘return value’; can be calculation

public class TestVolume // note: NO ( )s for class { public static void main(String[ ] args) { Sphere sphere = new Sphere( ); double george; george = sphere.calcVolume( ); System.out.println("value is " + george); } Other most important slide: Understanding method calls, object creation

Trace on board using debugger

return statement public double calcVolume( ) { // NO private in local variables; final for constants final double PI = ; double volume; volume = 4 / 3 * PI * radius * radius * radius; return volume; } type of method is return type to return a value, use ‘return value’; can be calculation What is the fix?

Casting Lesson 1: always test every method Lesson 2: don’t assume answer is correct; check it Fix 1: double volume = 4 / 3; Lesson 3: int / int REALLY is int. Fix 2: volume = (double) 4/3 * PI * radius * radius * radius; Casting should be used when you know the type of the result. int to double ok. double to int, not ok

JOptionPane, Section 1.11 To display a message: import javax.swing.JOptionPane; JOptionPane.showMessageDialog( null, // for now, always null "message: I LOVE cpsc150!!!", "Window Title", JOptionPane.INFORMATION_MESSAGE);

Reading information in JOptionPane, Section 2.11 String answer = JOptionPane.showInputDialog(null, "What is the weather today", "Weather Predictor", JOptionPane.QUESTION_MESSAGE); System.out.println("The weather is " + answer);

Reading information,Section 2.11 converting strings to ints String answer = JOptionPane.showInputDialog(null, "Enter a number", "Window Title", JOptionPane.QUESTION_MESSAGE); System.out.println("Answer is " + answer); // answer*1 error int number = Integer.parseInt(answer); // turns Strings to nbrs System.out.println("Answer is " + number*1);

Source Code Review Terms import comments // and /* … */ and /** javadoc here */ public/private –can't see draw; can see changeColor class class name –case sensitive. convention, start with capital fields/instance variables –always private, outside everything except class –specify data type (can be primitive or object) and name –primitive data types: int, double, boolean, char, a few others lowercase –can be initialized; all other statements must be within a method constructor –can have more than one. each must have different signature –always the name of the class. never has a return value

Review method (definition) Java statements return type (void if nothing returned) parameters local variable assignment –+, -, *, /, % (result is same as operands) –=, ++, --, +=, -=, *=, /= System.out.println method call new dot notation JOptionPane for reading and writing

Accessor Methods Allows outside users to view parts of a class Class has control over what clients see Returns the value being accessed; has no parameters Called getNameOfValueBeingRetrieved public int getNumerator( ) { return numerator; }

Accessor Method on Board Write getX for the Circle class

Mutator Method Allows clients to set a value in a class Class has control over how that is set returns a void. has parameter that is the new value called setNameOfValueBeingSet public void setDenominator(int d) { if (d != 0) denominator = d; }

Mutator Method on Board write setX for Circle Notice not called setXPosition; client shouldn't know name of instance variable