13 X 11 Java Lecture 3 CS 1311 Structure 13 X 11.

Slides:



Advertisements
Similar presentations
wwwcsif.cs.ucdavis.edu/~jacksoni
Advertisements

Designing a Program & the Java Programming Language
Classes And Objects II. Recall the LightSwitch Class class LightSwitch { boolean on = true; boolean isOn() { return on; } void switch() { on = !on; }
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.
1 Classes and Objects in Java Basics of Classes in Java.
1 Classes and Objects in Java Parameter Passing, Delegation, Visibility Control, and Object Cleanup.
Lecture 10 Methods COMP1681 / SE15 Introduction to Programming.
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.
1. In Java everything is an object or a class (or a piece of one or a collection of several). Objects send messages to each other by calling methods.
Understanding class definitions Looking inside classes 5.0.
Introduction to Computer Science Robert Sedgewick and Kevin Wayne Recursive Factorial Demo pubic class Factorial {
1.A computer game is an example of A.system software; B.a compiler; C.application software; D.hardware; E.none of the above. 2.JVM stands for: A.Java Virtual.
13 X 11 Java Lecture 1 CS 1311 Introduction 13 X 11.
Java Lecture 4 CS 1311X Have a Coke! 13 X 11. Take the Survey!
Simple Programs Simple Strings Writing some programs Only in Parameters? I/O Gadget.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
Yoshi
1 pritisajja.info Unlocking the World of Java Programming….. Priti Srinivas Sajja February, 2014 Visit pritisajja.info for detail Future Technology for.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Client Side Programming Using Java Applet Outcomes: You will be expected to know: – Java Applets and HTML file; –bytecode and platform independent programs;
1 Java Basics. 2 Compiling A “compiler” is a program that translates from one language to another Typically from easy-to-read to fast-to-run e.g. from.
Objects and Classes First Programming Concepts. 14/10/2004Lecture 1a: Introduction 2 Fundamental Concepts object class method parameter data type.
References and Objects Weiss ch. 2. Objects Are structured regions of memory –Reside in heap Each object is an instance of a type –e.g. String, File,
Introduction to Java CS 331. Introduction Present the syntax of Java Introduce the Java API Demonstrate how to build –stand-alone Java programs –Java.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Applying OO Concepts Using Java. In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The.
Introduction to Methods
Programming in Java; Instructor:Moorthy Introduction, Objects, Classes, Libraries1 Programming in Java Introduction.
OOP Languages: Java vs C++
Hello AP Computer Science!. What are some of the things that you have used computers for?
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Introduction to Programming Writing Java Beginning Java Programs.
The Java Programming Language
OOP (Java): Simple/ OOP (Java) Objectives – –give some simple examples of Java applications and one applet 2. Simple Java Programs Semester.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
CHAPTER 3 GC Java Fundamentals. 2 BASICS OF JAVA ENVIRONMENT  The environment  The language  Java applications programming Interface API  Various.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 15: More-Advanced Concepts.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Fall 2015CISC124 - Prof. McLeod1 CISC124 Have you filled out the lab section survey? (As of last night 54 left to fill out the survey.) TA names have been.
Programs and Classes A program is made up from classes Classes may be grouped into packages A class has two parts static parts exist independently Non-static.
Introduction to Programming Writing Java Beginning Java Programs.
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
Classes. Student class We are tasked with creating a class for objects that store data about students. We first want to consider what is needed for the.
Hello Computer Science!. Below is an example of a Hello World program in JAVA. While it is only three lines of code, there are many things that are happening.
Static?. Static Not dynamic class Widget { static int s; int d; // dynamic // or instance // variable }
Programming Languages and Paradigms Activation Records in Java.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Bank Account Example public class BankAccount { private double balance; public static int totalAccounts = 0; public BankAccount() { balance = 0; totalAccounts++;
Today… “Hello World” ritual. Brief History of Java & How Java Works. Introduction to Java class structure. But first, next slide shows Java is No. 1 programming.
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
OOP Basics Classes & Methods (c) IDMS/SQL News
CSH Intro. to Java. The Big Ideas in Computer Science Beyond programming Solving tough problems Creating extensible solutions Teams of “Computational.
Chapter 1 Object Orientation: Objects and Classes.
INTRODUCTION Java is a true OO language the underlying structure of all Java programs is classes. Everything must be encapsulated in a class that defines.
Java 5 Class Anatomy. User Defined Classes To this point we’ve been using classes that have been defined in the Java standard class library. Creating.
Object Lifetime and Pointers
Chapter 5: Enhancing Classes
Chapter 3 GC 101 Java Fundamentals.
Programming Language Concepts (CIS 635)
Classes, Encapsulation, Methods and Constructors (Continued)
Object Oriented Programming
Programs and Classes A program is made up from classes
A Methodical Approach to Methods
Presentation transcript:

13 X 11 Java Lecture 3 CS 1311 Structure 13 X 11

Types of Java Programs Applications –Stand alone –Requires JVM (java.exe, etc.) on your machine Applets –JVM built in to web browser runs program –Can be downloaded from network or files can be on your machine –Susceptible to browser problems! Servlets –Like an applet but code runs on server when a particular web page is browsed

13 X 11 A View of Memory Class Pool (What you wrote) Stack (Static Area) (Store stuff here) Heap (Dynamic Area) (Store stuff here)

13 X 11 class CokeMachine { int numCans = 3; void vend() { if(numCans > 0) { System.out.println("Have a Coke!"); numCans = numCans - 1; } else { System.out.println("Sorry!"); } void load(int n) { numCans = numCans + 1; System.out.println("Ready to vend!"); } public static void main(String args[]) { CokeMachine cc; cc = new CokeMachine(); cc.vend(); cc.load(); cc.vend(); }

13 X 11 Two Views External CokeMachine cc; cc = new CokeMachine(); cc.vend(); cc.load(5); class CokeMachine { int numCans = 3; void vend() { if(numCans > 0) { System.out.println ("Have a Coke!"); numCans = numCans - 1; } else { System.out.println ("Sorry!"); } void load(int n) { numCans = numCans + 1; System.out.println ("Ready to vend!"); }

13 X 11 javac *.java java Driver Could write... class Driver { public static void main(String args[]) { CokeMachine cc; cc = new CokeMachine(); cc.vend(); cc.load(5); } // main } // Simulation

13 X 11 What happened? java Driver Driver main Class Pool Stack Heap

13 X 11 What happened? Java searches for (and finds) static main method Class Pool Stack Heap Driver main

13 X 11 What happened? Java searches for (and finds) static main method Class Pool Stack Heap Driver main

13 X 11 What happened? CokeMachine cc; Class Pool Stack Heap Driver main CokeMachine numCans vend() load()

13 X 11 What happened? CokeMachine cc; Class Pool Stack Heap Driver main main cc (CokeMachine) CokeMachine numCans vend() load()

13 X 11 What happened? cc = new CokeMachine(); Class Pool Stack Heap Driver main main cc (CokeMachine) CokeMachine numCans vend() load() Obj: CokeMachine numCans vend() load() 3

13 X 11 What happened? cc.vend(); Class Pool Stack Heap Driver main main cc (CokeMachine) CokeMachine numCans vend() load() Obj: CokeMachine numCans vend() load() 2 Have a Coke!

13 X 11 What happened? cc.vend(); Class Pool Stack Heap Driver main main cc (CokeMachine) CokeMachine numCans vend() load() Obj: CokeMachine numCans vend() load() 1 Have a Coke!

13 X 11 What happened? cc.vend(); Class Pool Stack Heap Driver main main cc (CokeMachine) CokeMachine numCans vend() load() Obj: CokeMachine numCans vend() load() 0 Have a Coke!

13 X 11 What happened? cc.vend(); Class Pool Stack Heap Driver main main cc (CokeMachine) CokeMachine numCans vend() load() Obj: CokeMachine numCans vend() load() 0 Have a Coke! Sorry!

13 X 11 As a convenience... We don't really need the driver class We can put a static main in the CokeMachine But the operation is essentially the same! In fact, you should always put a static main in every class you write Use it to test the class for correct operation Will Java get confused?

13 X 11 No Way, Jose! class A main() class B main() class C main() class D main() class E main() class F main() Why?

13 X 11 Because! class A main() class B main() class C main() class D main() class E main() class F main() javac *.java java F

13 X 11 Questions?

13 X 11 Fields Sometimes called attributes In our CokeMachine: numCans Can be –Primitives –References Access cc.numCans = 42; // Direct access cc.vend(); // Via modifier Is direct access a "GoodThing" ® or a "BadThing" ®

13 X 11 Controlling Access Access to fields (and methods) can be controlled public -- Anyone can access private -- Access is only from within class Recall public static void main(String args[])

13 X 11 Example class CokeMachine { int numCans = 3; double cash = 0.0; static final double PRICE = 0.65; void vend() { if(numCans > 0) { numCans--; cash += PRICE; System.out.println("Have a coke!"); } else { System.out.println("Sorry, no Cokes"); }

13 X 11 Let's Test It! class Tester { public static void main(String args[]) { CokeMachine cm;// Make reference cm = new CokeMachine(); // Make a machine cm.numCans--;// Steal a Coke System.out.println("Cash = " + cm.cash); } Where's my money?!?!?!

13 X 11 Let's add some protection class CokeMachine { private int numCans = 3; private double cash = 0.0; private static final double PRICE = 0.65; public void vend() { if(numCans > 0) { numCans--; cash += PRICE; System.out.println("Have a coke!"); } else { System.out.println("Sorry, no Cokes"); }

13 X 11 Warning about Testing class CokeMachine { private int numCans = 3; private double cash = 0.0; private static final double PRICE = 0.65; public void vend() { if(numCans > 0) { numCans--; cash += PRICE; System.out.println("Have a coke!"); } else { System.out.println("Sorry, no Cokes"); } class Tester { public static void main(String a[]) { CokeMachine cm = new CokeMachine(); cm.numCans--; } class CokeMachine { private int numCans = 3; private double cash = 0.0; private static final double PRICE = 0.65; public void vend() { if(numCans > 0) { numCans--; cash += PRICE; System.out.println("Have a coke!"); } else { System.out.println("Sorry, no Cokes"); } public static void main(String a[]) { CokeMachine cm = new CokeMachine(); cm.numCans--; }

13 X 11 Demo

13 X 11 Details Methods –Module defined in a class which effectively becomes a message that an object of that class can understand cc.vend(); –Send a " vend() " message to the object referenced by cc –Almost all code executed in Java will be executed in methods

13 X 11 Anatomy of a method ( ) { } Examples: public static void main(String args[]) { System.out.println("Hello World!"); } void vend(){ /* code goes here */ } private int addEmUp(int a, int b, int c) { return a + b + c; }

13 X 11 Parts is parts public private –There are others we won't discuss static nothing which implies dynamic or instance

13 X 11 Parts is parts –Methods may optionally return a value –May be any valid type Class name Primitive void indicates no return value –If you promise to return something Java will expect you to keep your promise –If you promise to not return anything Java will break your kneecaps with a Louisville Slugger ® if you don't keep your promise

13 X 11 A Promise is a Promise public int max(int a, int b) { if(a >= b) { return a; } if(a < b) { return b; }

13 X 11 A Promise is a Promise public int max(int a, int b) { if(a >= b) { return a; } if(b < a) { return b; } Classname.java: : Return required at end of int max(int, int). public int max(int a, int b)

13 X 11 Method Name... –Method name follows normal identifier rules –Style note: Start method names with a lower case letter but capitalize multiword names: enqueue vend vendACoke load loadCokes

13 X 11 Parameter List –Declare each parameter individually –i.e. int a, float f, CokeMachine cm –Java only supports pass by value (in) parameters. public void swap(int a, int b) { /* This method is worthless! */ int t = a; a = b; b = t; }

13 X 11 Parameter List public static void testMachine(int n, CokeMachine cm) { for(int i=0; i < n; i++) { cm.vend(); } n = 0; // Just to be mean cm = null; // and nasty! } What is the effect on the outside world? Could this be considered (just maybe) a side effect?

13 X 11 Pass by Value class Demo { /* Code for testMachine here*/ public static void Main(String args[]) { int i = 3; CokeMachine cm; cm = new CokeMachine(); testMachine(i, cm); } i: cm: 3 Object: CokeMachine numCans = 3 Object: CokeMachine numCans = 3 main:

13 X 11 Pass by Value class Demo { /* Code for testMachine here*/ public static void Main(String args[]) { int i = 3; CokeMachine cm; cm = new CokeMachine(); testMachine(i, cm); } i: cm: 3 Object: CokeMachine numCans = 3 Object: CokeMachine numCans = 3 main: testMachine: n: cm: 3

13 X 11 Pass by Value class Demo { /* Code for testMachine here*/ public static void Main(String args[]) { int i = 3; CokeMachine cm; cm = new CokeMachine(); exerciseMachine(i, cm); } i: cm: 3 Object: CokeMachine numCans = 3 Object: CokeMachine numCans = 3 main: testMachine: n: cm: 3 public static void testMachine (int n, CokeMachine cm) { for(int i=0; i < n; i++) { cm.vend(); } n = 0; // Just to be mean cm = null; // and nasty! }

13 X 11 Pass by Value class Demo { /* Code for testMachine here*/ public static void Main(String args[]) { int i = 3; CokeMachine cm; cm = new CokeMachine(); exerciseMachine(i, cm); } i: cm: 3 Object: CokeMachine numCans = 0 Object: CokeMachine numCans = 0 main: testMachine: n: cm: 3 public static void testMachine (int n, CokeMachine cm) { for(int i=0; i < n; i++) { cm.vend(); } n = 0; // Just to be mean cm = null; // and nasty! }

13 X 11 Pass by Value class Demo { /* Code for testMachine here*/ public static void Main(String args[]) { int i = 3; CokeMachine cm; cm = new CokeMachine(); exerciseMachine(i, cm); } i: cm: 3 Object: CokeMachine numCans = 0 Object: CokeMachine numCans = 0 main: testMachine: n: cm: 0 public static void testMachine (int n, CokeMachine cm) { for(int i=0; i < n; i++) { cm.vend(); } n = 0; // Just to be mean cm = null; // and nasty! }

13 X 11 Pass by Value class Demo { /* Code for testMachine here*/ public static void Main(String args[]) { int i = 3; CokeMachine cm; cm = new CokeMachine(); exerciseMachine(i, cm); } i: cm: 3 Object: CokeMachine numCans = 0 Object: CokeMachine numCans = 0 main: testMachine: n: cm: 0 public static void testMachine (int n, CokeMachine cm) { for(int i=0; i < n; i++) { cm.vend(); } n = 0; // Just to be mean cm = null; // and nasty! }

13 X 11 Pass by Value class Demo { /* Code for testMachine here*/ public static void Main(String args[]) { int i = 3; CokeMachine cm; cm = new CokeMachine(); exerciseMachine(i, cm); } i: cm: 3 Object: CokeMachine numCans = 0 Object: CokeMachine numCans = 0 main:

13 X 11 Questions?

13 X 11 Sidebar on Methods Factorial (Yes, again) class FactDemo { public static void main(String args[]) { int n = 10; int i; int answer = 1; for(i = 1; i <= n; i++) { answer *= i; } // for System.out.println(n + "! = " + answer); } // main } // factDemo

13 X 11 Sidebar on Methods Make it a method public static void fact(int n) { int i; int answer = 1; for(i = 1; i <= n; i++) { answer *= i; } // for System.out.println(n + "! = " + answer); } // fact

13 X 11 Sidebar on Methods Make it smaller and more efficient? public static void fact(int n) { int i, ans; for(i = 1, ans = 1; i <= n; ans *= i++); System.out.println(n + "! = " + ans); } // fact

13 X 11 Sidebar on Methods Make it more readable? public static void fact(int n) { int i; int ans = 1; for(i = 1; i <= n; i++) ans *= i; System.out.println(n + "! = " + ans); } // fact

13 X 11 Sidebar on Methods Make it more useful? public static int fact(int n) { int i; int ans = 1; for(i = 1; i <= n; i++) ans *= i; return ans; } // fact

13 X 11 Sidebar on Methods Make it more useful? class FactDemo { public static int fact(int n) { int i; int ans = 1; for(i = 1; i <= n; i++) ans *= i; return ans; } // fact public static void main(String args[]) { System.out.println("10! = " + fact(10)); }

13 X 11 Sidebar on Methods Do it recursively! class FactDemo { public static int fact(int n) { if(n == 0) return 1; else return n * fact(n - 1); } // fact public static void main(String args[]) { System.out.println("10! = " + fact(10)); }

13 X 11 Sidebar on Methods Do it recursively! class FactDemo { public static int fact(int n) { if(n == 0) return 1; else return n * fact(n - 1); } // fact public static void main(String args[]) { for(int i = 1; i < 18; i++) System.out.println(i + "! = " + fact(i)); }

13 X 11 Shaky Results 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = ! = ! = ! = ! = ! = ! = ! = ! = ! = ! = Correct value: n! = 6,227,020,800 > ?

13 X 11 Primitive Data Type Ranges TypeSizeMinDefault booleanfalse Max 1false*true* char'\u0000' (null)16 byte(byte) short(short) ,76832,767 int032 -2,147,483,6482,147,483,647 long0L64 -9,223,372,036,854,775,8089,223,372,036,854,775,807 float0.0F32 Approx ±3.4E+38 with 7 significant digits double0.0D64 Approx ±1.7E+308 with 15 significant digits void * Not truly min and max.

13 X 11 Notice! Notice how Java gave you a helpful warning message to help keep you spacecraft from plunging into the Sun NOT.

13 X 11 Sidebar on Methods Fix the problem (forever?)! class FactDemo { public static long fact(long n) { if(n == 0) return 1; else return n * fact(n - 1); } // fact public static void main(String args[]) { for(int i = 1; i < 18; i++) System.out.println(i + "! = " + fact(i)); }

13 X 11 Pop Quiz class Widget { int a, b; public int sum() { return a + b; } public static void main(String a[]) { a = 5; b = 10; System.out.println(sum()); }

13 X 11 Pop Quiz class Widget { int a, b; public int sum() { return a + b; } public static void main(String a[]) { Widget w; w = new Widget(); w.a = 5; w.b = 10; System.out.println(w.sum()); }

13 X 11 Questions?

13 X 11 Final Thought Just what is a class? class declarations initialization modules* methods

13 X 11 Questions?