The life and death of objects, sta2cs. CSCI 136: Fundamentals of Computer Science II Keith Vertanen
|
|
- Eunice Madeleine Heath
- 5 years ago
- Views:
Transcription
1 The life and death of objects, sta2cs CSCI 136: Fundamentals of Computer Science II Keith Vertanen
2 Overview Where Java stores stuff The Heap The Stack Breaking both Java Garbage Collector (GC) CreaAng objects Copy constructors Methods creaang objects StaAc keyword StaAc methods and instance variables 2
3 Stack Stack vs. Heap Where method invocaaons live Where local variables live A chunk of memory Heap Where all objects live Another chunk of memory 3
4 The Stack Methods are stacked You call a method put on top of a call stack A method stays on stack unal it finishes execuang Each stack frame contains: What line it is execuang Values of all the method s local variables This includes parameters to the method 4
5 public void dostuff() boolean b = true; go(4); public void go(int x) int z = x + 24; crazy(); public void crazy() char c = 'a'; 5
6 public void dostuff() boolean b = true; go(4); public void go(int b) int c = b + 24; crazy(); public void crazy() char c = 'a'; 1 2 dostuff() boolean b true 3 What if we have variables in different methods that have the same name? crazy() char c 'a' go() int b 4 int c 28 go() int b 4 int c 28 dostuff() boolean b true 4 go() int b 4 int c 28 dostuff() boolean b true dostuff() boolean b true 6
7 CompuAng a factorial recursively public class Factorial public static long fact(long n) if (n <= 1) return 1; return n * fact(n - 1); public static void main(string [] args) long result = fact(4); System.out.println("4! = " + result); fact(1) n 1 fact(2) n 2 fact(3) n 3 0! = 1 1! = 1 2! = 1 x 2 = 2 3! = 1 x 2 x 3 = 6 4! = 4 x 3 x 2 x 1 = 24 Some example factorials. fact(4) n 4 main() 7
8 CompuAng a factorial recursively public class Factorial public static long fact(long n) if (n <= 1) return 1; return n * fact(n - 1); public static void main(string [] args) long result = fact(4); System.out.println("4! = " + result); 0! = 1 1! = 1 2! = 1 x 2 = 2 3! = 1 x 2 x 3 = 6 4! = 4 x 3 x 2 x 1 = 24 Some example factorials. fact(1) n 1 return 1 fact(2) n 2 return 2 * fact(1) fact(3) n 3 return 3 * fact(2) fact(4) n 4 return 4 * fact(3) main() fact(4) = 24 8
9 Breaking the stack fact(- 2) n - 2 public class Factorial Exception in thread "main" public static long fact(long java.lang.stackoverflowerror n) 0! = 1 1! = 1 2! = 1 x 2 = 2 3! = 1 x 2 x 3 = 6 4! = 4 x 3 x 2 x 1 = 24 Some example factorials. fact(- 1) n - 1 at Factorial.fact(Factorial.java:6) fact(0) at Factorial.fact(Factorial.java:6) n 0 at Factorial.fact(Factorial.java:6) return n * fact(n - 1); at Factorial.fact(Factorial.java:6) fact(1) at Factorial.fact(Factorial.java:6) at Factorial.fact(Factorial.java:6) n 1 public static void main(string at Factorial.fact(Factorial.java:6) [] args) at Factorial.fact(Factorial.java:6) long result = fact(4); fact(2) at Factorial.fact(Factorial.java:6) System.out.println("4! = " + result); n 2 at Factorial.fact(Factorial.java:6) at Factorial.fact(Factorial.java:6) at Factorial.fact(Factorial.java:6) fact(3) at Factorial.fact(Factorial.java:6) n 3 at Factorial.fact(Factorial.java:6) at Factorial.fact(Factorial.java:6) at Factorial.fact(Factorial.java:6) fact(4) at Factorial.fact(Factorial.java:6) n 4 at Factorial.fact(Factorial.java:6) at Factorial.fact(Factorial.java:6)... main() 9
10 Where things live Local variables live on the stack Local variables in a method Parameters passed to a method Reference variables e.g. passing in a int [] array, a Hero object, Only the remote control lives on the stack Objects live on the heap Objects instanaated with new, live on the heap Instance variables of an object Stored as part of the object living on the heap 10
11 The miracle of object creaaon CreaAng an object in 3 easy steps: 1) Declare a reference variable Heap myduck Duck myduck 11
12 The miracle of object creaaon CreaAng an object in 3 easy steps: 1) Declare a reference variable 2) Create an object Heap myduck new Duck(); 12
13 The miracle of object creaaon CreaAng an object in 3 easy steps: 1) Declare a reference variable 2) Create an object 3) Link the object and the reference You have now consumed memory on the heap based on how much state a Duck requires (i.e. the number and type of its instance variables). myduck Heap Duck myduck = new Duck(); 13
14 Java Garbage Collector Java tracks # of variables referring to an object As soon as nobody refers to an object, its memory can be freed Java's automaac Garbage Collector (GC) periodically handles this for you Exactly when is up to the JVM Enjoy it (while it lasts) You're so going to have to this yourself in data structures. 14
15 Object- killer #1 Reference goes out of scope permanently Killing objects public class DuckKiller1 public static void makeduck() Duck d = new Duck(); public static void main(string [] args) makeduck(); while (true) // Do something main() makeduck() main() main() d Heap Heap 15
16 Object- killer #1b Killing objects Variable inside curly braces goes out of scope 00 public class DuckKiller1b public static void main(string [] args) if (args.length >= 0) Duck d = new Duck(); while (true) // Do something main() line 04 line 05 line 06 d Heap 16
17 Object- killer #1b Reference goes out of scope permanently Killing objects 00 public class DuckKiller1b public static void main(string [] args) if (args.length >= 0) Duck d = new Duck(); while (true) // Do something main() line 04 line 05 line 06 line 07 line 08 Heap 17
18 Object- killer #2 Killing objects Assign the reference to another object 00 public class DuckKiller public static void main(string [] args) Duck d = new Duck(); 05 System.out.println("quack!"); 06 d = new Duck(); 07 System.out.println("quack!"); 08 d = new Duck(); 09 System.out.println("quack!"); main() line 04 d Heap 18
19 Object- killer #2 Killing objects Assign the reference to another object 00 public class DuckKiller public static void main(string [] args) Duck d = new Duck(); 05 System.out.println("quack!"); 06 d = new Duck(); 07 System.out.println("quack!"); 08 d = new Duck(); 09 System.out.println("quack!"); main() line 04 line 05 line 06 d Heap A@er execuang line 06, no one is referring to the first Duck object anymore. It is now subject to garbage collecaon. 19
20 Object- killer #2 Killing objects Assign the reference to another object 00 public class DuckKiller public static void main(string [] args) Duck d = new Duck(); 05 System.out.println("quack!"); 06 d = new Duck(); 07 System.out.println("quack!"); 08 d = new Duck(); 09 System.out.println("quack!"); main() line 04 line 05 line 06 line 07 line 08 d Heap A@er execuang line 08, both the first and second Ducks objects can be garbage collected. 20
21 Object- killer #3 Killing objects Set the reference variable to null 00 public class DuckKiller public static void main(string [] args) Duck d = new Duck(); 05 System.out.println("quack!"); 06 d = null; 07 System.out.println("quack!"); main() line 04 d Heap 21
22 Object- killer #3 Killing objects Set the reference variable to null 00 public class DuckKiller public static void main(string [] args) Duck d = new Duck(); 05 System.out.println("quack!"); 06 d = null; 07 System.out.println("quack!"); main() line 04 line 05 line 06 d Heap A@er execuang line 06, no one is referring to the Duck object anymore. The Java garbage collector can now free up the Duck's memory. 22
23 Memory is not infinite Breaking the heap Can't keep new ing forever w/o gemng rid of any You can buy yourself some Ame: Increase memory with JVM flag: - Xmx<num>[k m g] import java.util.*; public class HeapDeath public static void main(string [] args) ArrayList<Duck> list = new ArrayList<Duck>(); while (true) Duck d = new Duck(); list.add(d); While variable d scopes out every loop, the Duck reference persists inside the ArrayList. Memory is never freed! 23
24 Size of variables in Java Type Memory size (bits, 8 bits = byte) byte 8 short 16 int 32 long 64 float 32 double 64 boolean not precisely defined char 16 hqp://righteousit.wordpress.com/tag/tcpip/ NOTE: The size of a reference variable s remote control is JVM dependent. But there is always overhead for the reference variable and for any instance variables inside the data type! 24
25 00 public class HeapPuzzler public static void main(string [] args) Duck d = new Duck(); 05 Duck [] a = new Duck[4]; 06 for (int i = 0; i < a.length; i++) 07 a[i] = new Duck(); 08 System.out.println("quack!"); 09 a[0] = null; 10 a[1] = d; 11 System.out.println("quack!"); ABer execu2ng line # Ducks on the heap Variable(s) that point to a Duck object 04 1 d 05 1 d 08 5 d, a[0], a[1], a[2], a[3] 09 4 d, a[1], a[2], a[3] 10 3 (d, a[1]), a[2], a[3] Two variables that refer to the same Duck 25
26 Copy constructor Copy constructors A special constructor Parameter is another object of the same type Simply copies all the state of the passed in object public class Duck private String name = ""; private double weight = 0.0; A copy constructor! public Duck(Duck other) this.name = other.name; this.weight = other.weight; 26
27 Methods giving birth An instance method can create a new object and return it Hey rabbit, what do you know? My locaaon and my size! Hey rabbit, what can you do? I can draw myself. I can tell if somebody clicks on me. Ohh and um, well you know, I can make them there baby rabbits 27
28 Rabbit class, part 1 public class Rabbit private double x = 0.0; private double y = 0.0; private static final double size = 0.06; public Rabbit(double x, double y) this.x = x; this.y = y; public void draw() StdDraw.picture(x, y, "rabbit.png"); public boolean intersect(double x, double y) double deltax = (this.x - x); double deltay = (this.y - y); return (Math.sqrt(deltaX * deltax + deltay * deltay) < size);... 28
29 Rabbit class, part 2 public Rabbit breed() Rabbit baby = new Rabbit(this.x + (0.2 - Math.random() * 0.4), this.y + (0.2 - Math.random() * 0.4)); return baby; public static void main(string [] args) ArrayList<Rabbit> rabbits = new ArrayList<Rabbit>(); rabbits.add(new Rabbit(0.5, 0.5)); while (true) for (int i = rabbits.size() - 1; i >= 0; i- - ) Rabbit r = rabbits.get(i); r.draw(); if (r.intersect(stddraw.mousex(), StdDraw.mouseY())) rabbits.add(r.breed()); StdDraw.show(100); 29
30 StaAc vs. non- staac methods StaAc methods Forbidden from using instance vars of the class Non- staac methods (instance methods) Allowed to use instance vars A class can have: All staac methods e.g. Math class All non- staac methods A mix of both e.g. Wrapper classes like Double and Integer 30
31 Math.java Method signature public static int round(float a) Descrip2on Round to the nearest integer public static long round(double a) public static int min(int a, int b) Find the minimum of two numbers public static long min(long a, long b) public static float min(float a, float b) public static double min(double a, double b) public static int abs(int a) Return absolute value of a number public static long abs(long a) public static float abs(float a) public static double abs(double a) public static double random() Get a random number in [0.0, 1.0) public static double sqrt(double a) Take the square root of a number A selecaon of the staac methods in Math.java 31
32 Math.java public static final double E = ; public static final double PI = ; Constants in Math.java. /** * Don't let anyone instantiate this class. */ private Math() A private constructor. Makes it impossible to instanaate an object of type Math. All calls via staac method calls, e.g. Math.sqrt(), Math.min() The constructor of the Math class. 32
33 Using Math class int x = Math.round(42.2); int y = Math.min(56, 12); int z = Math.abs(- 343); These methods don't use instance variables, so there is no specific object to call the methods on. Methods called using class name. Math mathobj = new Math(); You can't do this since the constructor is private: Exception in thread "main" java.lang.error: Unresolved compilation problem: The constructor Math() is not visible There is no persistent state in the Math object, so no need to create an object on the heap. 33
34 StaAc methods Limits of staac methods Cannot use non- staac instance variables public class Cow private String name = ""; private double weight = 0.0; public static double getweight() return weight; Cow cow1 = new Cow(); Cow cow2 = new Cow(); System.out.println("weight = ", Cow.getWeight()); Since getweight() is declared staac, any use of a non- staac instance variable results in a compile error: The weight of which cow? Cow.java:8: non- static variable weight cannot be referenced from a static context return weight; ^ 34
35 StaAc methods Limits of staac methods Cannot call non- staac methods public class Cow private String name = ""; private double weight = 0.0; public double getweight() return weight; public static boolean isbig() return (getweight() > 500.0); Since isbig() is declared staac, any use of a non- staac instance method results in a compile error: Cow.java:13: non- static method getweight() cannot be referenced from a static context return (getweight() > 500.0); ^ 35
36 StaAc variables StaAc instance variable One var shared among all instances of a class Why? Commonly used for constants public static final double PI = ; Eliminate repeated variables that are always the same Reduce memory, doesn t keep copies of idenacal objects Track a single value related to a class type e.g. Number of objects created for a paracular class 36
37 Reducing memory usage public class Cow private String name = ""; private double weight = 0.0; Normal instance variables, each Cow object has its own set of these variables. private static AudioFile sound = new AudioFile("cow.wav"); public void makenoise() sound.play(); All Cow objects share the same sound object. Only one AudioFile object is created on the heap, thus saving memory. 37
38 CounAng created objects public class Cow private String name = ""; private double weight = 0.0; private static int numcows = 0; Normal instance variables, each Cow object has its own set of these variables. public Cow() numcows++; public Cow(Cow othercow) this.name = othercow.name; this.weight = othercow.weight; numcows++; public static int getnumcows() return numcows; No maqer how many Cow objects we create, there is only ever one numcows instance variable that has a single value. Methods that only use staac variables can be declared staac (but don't have to be). 38
39 Summary How your data is stored Stack Heap Garbage collector CreaAng new objects Copy constructor Other methods creaang new object instances StaAc keyword For methods For instance variables Heap 39
Sta$cs and forma.ng numbers
Sta$cs and forma.ng numbers CSCI 135: Fundamentals of Computer Science I Keith Vertanen Copyright 2011 Sta,c keyword Overview Sta,c methods Sta,c instance variables Forma9ng numbers prin= style forma9ng
More informationA foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types
Classes and objects A foundation for programming any program you might want to write objects functions and modules build even bigger programs and reuse code http://www.flickr.com/photos/vermegrigio/5923415248/
More informationCLASSES AND OBJECTS. Fundamentals of Computer Science I
CLASSES AND OBJECTS Fundamentals of Computer Science I Outline Primitive types Creating your own data types Classes Objects Instance variables Instance methods Constructors Arrays of objects A Foundation
More informationCLASSES AND OBJECTS. Fundamentals of Computer Science I
CLASSES AND OBJECTS Fundamentals of Computer Science I Outline Primitive types Creating your own data types Classes Objects Instance variables Instance methods Constructors Arrays of objects A Foundation
More informationA Foundation for Programming
2.1 Functions A Foundation for Programming any program you might want to write objects functions and modules build bigger programs and reuse code graphics, sound, and image I/O arrays conditionals and
More informationCSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014
CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014 Name: This exam consists of 5 problems on the following 6 pages. You may use your double- sided hand- written 8 ½ x 11 note sheet
More informationCSC207H: Software Design. Java + OOP. CSC207 Winter 2018
Java + OOP CSC207 Winter 2018 1 Why OOP? Modularity: code can be written and maintained separately, and easily passed around the system Information-hiding: internal representation hidden from the outside
More informationClasses and objects. Chapter 2: Head First Java: 2 nd Edi4on, K. Sierra, B. Bates
Classes and objects Chapter 2: Head First Java: 2 nd Edi4on, K. Sierra, B. Bates Fundamentals of Computer Science Keith Vertanen Copyright 2013 A founda4on for programming any program you might want to
More informationFunctions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)
2.1 Functions Functions Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing) Return one output value Input Arguments x y z f Return Value f (x, y, z)
More informationTo define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,
1 To define methods, invoke methods, and pass arguments to a method ( 5.2-5.5). To develop reusable code that is modular, easy-toread, easy-to-debug, and easy-to-maintain. ( 5.6). To use method overloading
More informationRecursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011
Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011 Recursion A method calling itself Overview A new way of thinking about a problem Divide and conquer A powerful programming
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationC10: Garbage Collection and Constructors
CISC 3120 C10: Garbage Collection and Constructors Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/5/2018 CUNY Brooklyn College 1 Outline Recap OOP in Java: composition &
More informationCS110: PROGRAMMING LANGUAGE I
CS110: PROGRAMMING LANGUAGE I Computer Science Department Lecture 8: Methods Lecture Contents: 2 Introduction Program modules in java Defining Methods Calling Methods Scope of local variables Passing Parameters
More informationC11: Garbage Collection and Constructors
CISC 3120 C11: Garbage Collection and Constructors Hui Chen Department of Computer & Information Science CUNY Brooklyn College 10/5/2017 CUNY Brooklyn College 1 Outline Recap Project progress and lessons
More informationCSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014
CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014 Name: This exam consists of 8 problems on the following 8 pages. You may use your two- sided hand- written 8 ½ x 11 note sheet during the exam.
More informationIntroduction to Computer Science Unit 2. Notes
Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and
More informationAP CS Unit 3: Control Structures Notes
AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts
More informationChapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
Chapter 5 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i
More informationCSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013
CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013 Name: This exam consists of 6 problems on the following 6 pages. You may use your two-sided hand-written 8 ½ x 11 note sheet during the exam.
More informationCSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013
CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013 Name: This exam consists of 6 problems on the following 6 pages. You may use your two-sided hand-written 8 ½ x 11 note sheet during the exam.
More informationOutline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring
Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,
More informationJava Review. Fundamentals of Computer Science
Java Review Fundamentals of Computer Science Link to Head First pdf File https://zimslifeintcs.files.wordpress.com/2011/12/h ead-first-java-2nd-edition.pdf Outline Data Types Arrays Boolean Expressions
More informationi.e.: n! = n (n 1)
Recursion and Java Recursion is an extremely powerful problemsolving technique. Problems that at first appear difficult often have simple recursive solutions. Recursion breaks a problems into several smaller
More informationRecursion. Fundamentals of Computer Science
Recursion Fundamentals of Computer Science Outline Recursion A method calling itself All good recursion must come to an end A powerful tool in computer science Allows writing elegant and easy to understand
More informationCOMP-202: Foundations of Programming. Lecture 4: Methods Jackie Cheung, Winter 2016
COMP-202: Foundations of Programming Lecture 4: Methods Jackie Cheung, Winter 2016 Announcements Quiz 1 postponed: Due Jan 26 at 11:59pm Assignment 1 postponed: Due on Feb 1 at 11:59pm 2 Review What is
More informationInheritance and objects
Inheritance and objects CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2013 Inheritance Overview Sharing code between related classes Pu8ng similar objects in the same bucket Extremely
More information1 Shyam sir JAVA Notes
1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write
More information1 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
Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(
More informationCOMP 250 Winter 2011 Reading: Java background January 5, 2011
Almost all of you have taken COMP 202 or equivalent, so I am assuming that you are familiar with the basic techniques and definitions of Java covered in that course. Those of you who have not taken a COMP
More informationCSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2013
CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2013 Name: This exam consists of 5 problems on the following 6 pages. You may use your double-sided hand-written 8 ½ x 11 note sheet
More informationMichele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring
Michele Van Dyne Museum 204B mvandyne@mtech.edu http://katie.mtech.edu/classes/csci136 CSCI 136: Fundamentals of Computer Science II, Spring 2016 1 Review of Java Basics Data Types Arrays NEW: multidimensional
More informationConditionals, Loops, and Style
Conditionals, Loops, and Style yes x > y? no max = x; max = y; http://xkcd.com/292/ Fundamentals of Computer Science Keith Vertanen Copyright 2013 Control flow thus far public class ArgsExample public
More informationCSCI 135 Final Fall Problem Points Score Total 100
CSCI 135 Final Fall 2011 Name: This exams consists of 11 problems on the following 14 pages. You may use your two- sided hand- written 8 ½ x 11 note sheet during the exam. No calculators, computers, or
More informationPrimitive Data Types: Intro
Primitive Data Types: Intro Primitive data types represent single values and are built into a language Java primitive numeric data types: 1. Integral types (a) byte (b) int (c) short (d) long 2. Real types
More informationProgramming Language Concepts: Lecture 2
Programming Language Concepts: Lecture 2 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in http://www.cmi.ac.in/~madhavan/courses/pl2011 PLC 2011, Lecture 2, 6 January 2011 Classes and
More informationCS 231 Data Structures and Algorithms, Fall 2016
CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard
More informationMore on inheritance CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014
More on inheritance CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014 Object hierarchies Overview Several classes inheriting from same base class Concrete versus abstract classes
More informationKey Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent
Programming 2 Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent information Input can receive information
More informationArray. Prepared By - Rifat Shahriyar
Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types
More informationChapter 5 Methods / Functions
Chapter 5 Methods / Functions 1 Motivations A method is a construct for grouping statements together to perform a function. Using a method, you can write the code once for performing the function in a
More informationIntroduction to Java
Introduction to Java Module 1: Getting started, Java Basics 22/01/2010 Prepared by Chris Panayiotou for EPL 233 1 Lab Objectives o Objective: Learn how to write, compile and execute HelloWorld.java Learn
More informationChapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }
Chapter 5 Methods 5.1 Introduction A method is a collection of statements that are grouped together to perform an operation. You will learn how to: o create your own mthods with or without return values,
More informationConditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression
Conditionals, Loops, and Style Control flow thus far yes no x > y? max = x; max = y; public class ArgsExample time 0 String product = args[0]; time 1 int qty = Integer.parseInt(args[1]); time 2 double
More informationInheritance and objects
Inheritance and objects CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014 Inheritance Overview Sharing code between related classes Putting similar objects in the same bucket
More informationAdvanced Object Concepts
Understanding Blocks Blocks - Appears within any class or method, the code between a pair of curly braces Outside block- The first block, begins immediately after the method declaration and ends at the
More informationRecursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...
Recursion Recursion Overview A method calling itself A new way of thinking about a problem Divide and conquer A powerful programming paradigm Related to mathematical induction Example applications Factorial
More informationAgenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java
CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda
More informationMidterm Exam CS 251, Intermediate Programming March 12, 2014
Midterm Exam CS 251, Intermediate Programming March 12, 2014 Name: NetID: Answer all questions in the space provided. Write clearly and legibly, you will not get credit for illegible or incomprehensible
More informationClass. A class is an unit of Java programs; that is, Java programs consist only of classes. School. Department. Student. Course.
Classes - Basics Classes Information hiding Method overloading Useful methods: tostring() and equals() Parameter passing: call by reference Final fields Static fields and methods Objects Initialization
More informationInstructions. This exam has 7 questions, worth 10 points each. You have 50 minutes.
COS 126 Written Exam 1 Spring 18 Instructions. This exam has 7 questions, worth 10 points each. You have 50 minutes. Resources. You may reference your optional one-sided 8.5-by-11 handwritten "cheat sheet"
More informationExcep&ons and file I/O
Excep&ons and file I/O Exception in thread "main" java.lang.numberformatexception: For input string: "3.5" at java.lang.numberformatexception.forinputstring(numberformatexception.java:48) at java.lang.integer.parseint(integer.java:458)
More information20 Most Important Java Programming Interview Questions. Powered by
20 Most Important Java Programming Interview Questions Powered by 1. What's the difference between an interface and an abstract class? An abstract class is a class that is only partially implemented by
More informationImportant Java terminology
1 Important Java terminology The information we manage in a Java program is either represented as primitive data or as objects. Primitive data פרימיטיביים) (נתונים include common, fundamental values as
More informationCOMP-202: Foundations of Programming. Lecture 7: Strings and Methods Jackie Cheung, Winter 2015
COMP-202: Foundations of Programming Lecture 7: Strings and Methods Jackie Cheung, Winter 2015 Announcements Quiz 2 due tonight at 11:59pm New grades policy: lowest quiz mark dropped Assignment 2 due in
More informationCOE318 Lecture Notes Week 4 (Sept 26, 2011)
COE318 Software Systems Lecture Notes: Week 4 1 of 11 COE318 Lecture Notes Week 4 (Sept 26, 2011) Topics Announcements Data types (cont.) Pass by value Arrays The + operator Strings Stack and Heap details
More informationCOE318 Lecture Notes Week 3 (Week of Sept 17, 2012)
COE318 Lecture Notes: Week 3 1 of 8 COE318 Lecture Notes Week 3 (Week of Sept 17, 2012) Announcements Quiz (5% of total mark) on Wednesday, September 26, 2012. Covers weeks 1 3. This includes both the
More informationCS121/IS223. Object Reference Variables. Dr Olly Gotel
CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223
More informationVariables and data types
Survivor: CSCI 135 Variables Variables and data types Stores information your program needs Each has a unique name Each has a specific type Java built-in type what it stores example values operations String
More informationCSCI 136: Fundamentals of Computer Science II. Keith Vertanen Museum
CSCI 136: Fundamentals of Computer Science II Keith Vertanen Museum 102 496-4385 kvertanen@mtech.edu http://katie.mtech.edu/classes/csci136 CSCI 136: Fundamentals of Computer Science II Keith Vertanen
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 02: Using Objects MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Using Objects 2 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management
More informationpublic class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {
Scoping, Static Variables, Overloading, Packages In this lecture, we will examine in more detail the notion of scope for variables. We ve already indicated that variables only exist within the block they
More informationChapter 6 Introduction to Defining Classes
Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of
More informationDUBLIN CITY UNIVERSITY
DUBLIN CITY UNIVERSITY REPEAT EXAMINATIONS 2008 MODULE: Object-oriented Programming I - EE219 COURSE: B.Eng. in Electronic Engineering (Year 2 & 3) B.Eng. in Information Telecomms Engineering (Year 2 &
More informationINDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line
A SIMPLE JAVA PROGRAM Class Declaration The Main Line INDEX The Line Contains Three Keywords The Output Line COMMENTS Single Line Comment Multiline Comment Documentation Comment TYPE CASTING Implicit Type
More informationJava Identifiers, Data Types & Variables
Java Identifiers, Data Types & Variables 1. Java Identifiers: Identifiers are name given to a class, variable or a method. public class TestingShastra { //TestingShastra is an identifier for class char
More informationCOMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading
COMP 202 CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading More on OO COMP 202 Objects 3 1 Static member variables So far: Member variables
More informationLecture Static Methods and Variables. Static Methods
Lecture 15.1 Static Methods and Variables Static Methods In Java it is possible to declare methods and variables to belong to a class rather than an object. This is done by declaring them to be static.
More informationJump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.
Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:
More informationAPCS Semester #1 Final Exam Practice Problems
Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester
More informationArray. Array Declaration:
Array Arrays are continuous memory locations having fixed size. Where we require storing multiple data elements under single name, there we can use arrays. Arrays are homogenous in nature. It means and
More informationDUBLIN CITY UNIVERSITY
DUBLIN CITY UNIVERSITY SEMESTER ONE EXAMINATIONS 2007 MODULE: Object Oriented Programming I - EE219 COURSE: B.Eng. in Electronic Engineering B.Eng. in Information Telecommunications Engineering B.Eng.
More informationUsing Java Classes Fall 2018 Margaret Reid-Miller
Using Java Classes 15-121 Fall 2018 Margaret Reid-Miller Today Strings I/O (using Scanner) Loops, Conditionals, Scope Math Class (random) Fall 2018 15-121 (Reid-Miller) 2 The Math Class The Math class
More informationCOMP 202 Java in one week
COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of
More informationAdministrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments
CMSC433, Spring 2004 Programming Language Technology and Paradigms Java Review Jeff Foster Feburary 3, 2004 Administrivia Reading: Liskov, ch 4, optional Eckel, ch 8, 9 Project 1 posted Part 2 was revised
More informationCSC207H: Software Design. Java + OOP. CSC207 Winter 2018
Java + OOP CSC207 Winter 2018 1 Why OOP? Modularity: code can be written and maintained separately, and easily passed around the system Information-hiding: internal representation hidden from the outside
More informationLecture 6: While Loops and the Math Class
Lecture 6: While Loops and the Math Class Building Java Programs: A Back to Basic Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved. while loops 2 Categories of loops
More informationPrimitive vs Reference
Primitive vs Reference Primitive types store values Reference types store addresses This is the fundamental difference between the 2 Why is that important? Because a reference type stores an address, you
More informationChapter 6 Methods. Dr. Hikmat Jaber
Chapter 6 Methods Dr. Hikmat Jaber 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i
More informationBASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I
BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment
More informationReview. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char
Review Primitive Data Types & Variables int, long float, double boolean char String Mathematical operators: + - * / % Comparison: < > = == 1 1.3 Conditionals and Loops Introduction to Programming in
More informationstatic int min(int a, int b) Returns the smaller of two int values. static double pow(double a,
The (Outsource: Supplement) The includes a number of constants and methods you can use to perform common mathematical functions. A commonly used constant found in the Math class is Math.PI which is defined
More informationRules and syntax for inheritance. The boring stuff
Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for
More informationInheritance and Interfaces
Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical
More informationCrash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++
Crash Course in Java Netprog: Java Intro 1 Why Java? Network Programming in Java is very different than in C/C++ much more language support error handling no pointers! (garbage collection) Threads are
More informationLecture Static Methods and Variables. Static Methods
Lecture 15.1 Static Methods and Variables Static Methods In Java it is possible to declare methods and variables to belong to a class rather than an object. This is done by declaring them to be static.
More informationCS260 Intro to Java & Android 03.Java Language Basics
03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance
More informationCOMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015
COMP-202: Foundations of Programming Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015 Announcements Assignment 2 posted and due on 30 th of May (23:30). Extra class tomorrow
More informationIntroduction to Computer Science Unit 2. Notes
Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and
More informationEECS1710. Announcements. Labtests have been returned Term Test #01 marking is in progress. Next Labtest: Thu Oct 23/Fri Oct 24
EECS1710 Click to edit Master Week text 05, styles Lecture 10 Second level Third level Fourth level Fifth level Fall 2014! Thursday, Oct 09, 2014 1 Announcements Labtests have been returned Term Test #01
More informationThe Math Class (Outsource: Math Class Supplement) Random Numbers. Lab 06 Math Class
The (Outsource: Supplement) The includes a number of constants and methods you can use to perform common mathematical functions. A commonly used constant found in the Math class is Math.PI which is defined
More informationCS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)
CS/B.TECH/CSE(New)/SEM-5/CS-504D/2013-14 2013 OBJECT ORIENTED PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give their answers
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationint a; int b = 3; for (a = 0; a < 8 b < 20; a++) {a = a + b; b = b + a;}
1. What does mystery(3) return? public int mystery (int n) { int m = 0; while (n > 1) {if (n % 2 == 0) n = n / 2; else n = 3 * n + 1; m = m + 1;} return m; } (a) 0 (b) 1 (c) 6 (d) (*) 7 (e) 8 2. What are
More informationChapter 1 Getting Started
Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different
More informationChapter 1: Introduction to Computers, Programs, and Java
Chapter 1: Introduction to Computers, Programs, and Java 1. Q: When you compile your program, you receive an error as follows: 2. 3. %javac Welcome.java 4. javac not found 5. 6. What is wrong? 7. A: Two
More informationChapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 5 Methods 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Problem int sum = 0; for (int i = 1; i
More informationUnit 5: More on Classes/Objects Notes
Unit 5: More on Classes/Objects Notes AP CS A The Difference between Primitive and Object/Reference Data Types First, remember the definition of a variable. A variable is a. So, an obvious question is:
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 02: Using Objects MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Using Objects 2 Introduction to Object Oriented Programming Paradigm Objects and References Memory Management
More information