1 / 36

COP 3330

Learn how to write and call your own Java methods while understanding common math and string methods. Explore compilation, runtime, and logical errors with examples. Get insights into class basics and good design principles.

Download Presentation

COP 3330

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COP 3330

  2. Topics • Java Basics • How to write & call your own method • Math methods (static methods) • String methods (instance methods) • Errors • Classes • Objects

  3. Writing your own methods • main() is a method you’ve all already used • public static void main(String[] args) • To write your own methods, use the same syntax public static void myMethod() { // Do something here. } public static int myIntMethod() { // Do something here and return an int. }

  4. Writing your own methods • Order of methods doesn’t matter (Difference from C) • Don’t forget static keyword or you’ll receive error “Cannot make a static reference to the non-static method” • Write code showing method calls

  5. Math Methods • These are static methods. That means they are called on the Math class • abs(): Takes in an int and returns its absolute value • sin(), cos(), tan(): Take in doubles and perform trigonometry. These functions use radians, not degrees • PI: A static final variable that is closer to πthan any other double.

  6. Math Methods • More Math methods • pow(): Takes in two doubles and returns the first raised to the power of the second • random(): Takes in no parameters and returns a random double in the range from 0.0 to 1.0, including 0, but excluding 1. • sqrt(): Takes in a double and returns its square root • Show example Math code

  7. String Methods • Java Strings are immutable. That means that once they're created, they can't be altered • Calling methods on Strings will return new Strings, but leave the original intact

  8. String Methods • These are instance methods (that means they're called on String objects) • concat(): Takes in a String and returns a new String. Equivalent to + • replace(): Takes in two chars and returns a new String. The first char is the character to be replaced, and the second char is the character to replace it with

  9. String Methods • More methods • substring(): Takes in two ints and returns a new String. The first int is the beginning index and the second int is the ending index of the substring • length(): Takes in no parameters. Returns the length of the String • charAt(): Takes in an int and returns the character at that index

  10. Simple grep Program • Write a program that reads in a paragraph of text from a file called “text.in” and searches for all instances of a given word (pattern) input by the user from standard input, ignoring the case of the text or pattern. • Print the line number and index (both 0-based) of each occurrence of the pattern, or print that the pattern was not found in the text. • Use either the substring() method or the indexOf() method to search for the pattern.

  11. Errors • Compilation Errors • Runtime Errors • Logic Errors

  12. Compilation Errors • A compilation error can occur when the grammar of the language is broken • Common examples • Missing semicolon • Unmatched curly brace • Misspelled keyword

  13. Compilation Errors • A compilation error can also occur when the syntax is basically valid, but a statement has an invalid meaning • Examples • Using undeclared/out-of-scope variables • Not casting when casting is necessary • Using a double to index an array

  14. Runtime Errors • A runtime error is when the program crashes • In Java, usually an unhandled exception • NullPointerException • ArithmeticException • ArrayIndexOutOfBoundsException • And much, much more… • Also, virtual machine errors (e.g. out of memory)

  15. Logical Errors • Say what you mean, and mean what you say • Logical errors are when the computer understands and can do what you’ve told it, but you’ve told it the wrong thing • Logical errors are notoriously difficult to track down

  16. Logical Errors • Sources of logical errors • Typo • Programmer didn’t notice special cases • Programmer didn’t understand problem

  17. Quiz #1 Returned • Please come to the front of class to claim your Quiz #1 • If you think you deserve more points, please see me during office hours • You must have a clear and valid reason to earn more points. “I need to get a better grade on this quiz” is not a valid reason!

  18. A Good Design … features Encapsulation • This is a key aspect of object-oriented design • Encapsulation means grouping together related data and operations on that data into a unit

  19. Class Basics • A class defines a new data type • A class is a blueprint for objects • Classes are mostly made up of three basic components (members) • Instance variables (fields) • Constructors • Methods

  20. A Good Design … features Information Hiding • This is a key aspect of object-oriented design • Information hiding means concealing unnecessary details • This allows those using a system to more easily understand the big picture • This makes it much more difficult to use the system in incorrect ways

  21. Class Basics • All members have access modifiers • The most common are • public • private • The other two will be discussed at a later point • protected • Default access (package)

  22. Instance Variables • Instance variables persist throughout the life of the object • They can be of the same types as any other variables • Example • private double realPart; • private double imaginaryPart;

  23. Constructor • A constructor is a method, but it is so important that it needs separate consideration • A constructor creates, initializes, and returns a reference to a new object • Creation and return are handled automatically • The constructor always bears the name of its class

  24. Constructor • Example public class Complex { private double realPart; private double imagPart; public Complex() { realPart = imagPart = 0; } ... }

  25. Constructor • Constructors are called by using the new keyword • Example: Complex foo = new Complex();

  26. Garbage Collection • In Java, when an object is no longer referenced, its memory is reclaimed automatically • This is a big difference from C

  27. Book Example • Store information about a Book • Title • Publisher • ISBN • Number of pages • Number of chapters • The text of the book • Others?

  28. Book • Write a class to store this data and create a constructor for the class

  29. Methods • Non-static methods act on objects • A method is laid out as follows: modifiers return-type identifier(parameters) { body } • A method is essentially the same thing as a function in C

  30. Methods • The return type of a method can be any type • If the method does not return anything, the return type is void

  31. Methods • Variables accessible from within a method • Instance variables • Formal parameters • Local variables

  32. Methods • Use object.methodName(parameters) to call the method on an object • Example: number = stdin.nextInt(); • Add a method to the Book class to add a chapter

  33. .toString() • Java uses the toString method on objects to represent it as a string for purposes of string concatenation and such • The toString method has the following signature: • public String toString() • If you want to be able to print objects of your class to be able to be printed in a meaningful way, write this method in your class!

  34. Overloading • Multiple methods (and constructors) with the same name can exist in the same class • The formal parameters MUST be different • Why do this? • Use different types of information to construct an object (e.g. Scanner constructors) • Perform similar operations (e.g. print() method in PrintStream)

  35. Static • Ordinarily, methods and fields are associated with objects • The static modifier makes them associate with the class • Example • See the class Math in java.lang

  36. Static • To access a static member, use the class name instead of the object name • Example: number = Integer.parseInt(“5”); • Add a static method to the Book class to generate a new ISBN for a new book

More Related