360 likes | 365 Vues
COP 3330. Topics. Java Basics How to write & call your own method Math methods (static methods) String methods (instance methods) Errors Classes Objects. Writing your own methods. main() is a method you ’ ve all already used public static void main(String[] args)
E N D
Topics • Java Basics • How to write & call your own method • Math methods (static methods) • String methods (instance methods) • Errors • Classes • Objects
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. }
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
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.
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
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
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
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
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.
Errors • Compilation Errors • Runtime Errors • Logic Errors
Compilation Errors • A compilation error can occur when the grammar of the language is broken • Common examples • Missing semicolon • Unmatched curly brace • Misspelled keyword
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
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)
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
Logical Errors • Sources of logical errors • Typo • Programmer didn’t notice special cases • Programmer didn’t understand problem
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!
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
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
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
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)
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;
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
Constructor • Example public class Complex { private double realPart; private double imagPart; public Complex() { realPart = imagPart = 0; } ... }
Constructor • Constructors are called by using the new keyword • Example: Complex foo = new Complex();
Garbage Collection • In Java, when an object is no longer referenced, its memory is reclaimed automatically • This is a big difference from C
Book Example • Store information about a Book • Title • Publisher • ISBN • Number of pages • Number of chapters • The text of the book • Others?
Book • Write a class to store this data and create a constructor for the class
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
Methods • The return type of a method can be any type • If the method does not return anything, the return type is void
Methods • Variables accessible from within a method • Instance variables • Formal parameters • Local variables
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
.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!
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)
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
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