Chapter 4 Intermediate (part 1)

Slides:



Advertisements
Similar presentations
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
Advertisements

Java Programming Strings Chapter 7.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 2 Getting Started with Java Program development.
Introduction to Objects and Input/Output
Chapter 3 - Java Programming With Supplied Classes1 Chapter 3 Java Programming With Supplied Classes.
Dialogs. Displaying Text in a Dialog Box Windows and dialog boxes –Up to this our output has been to the screen –Many Java applications use these to display.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 2 Getting Started with Java Structure of.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 2 Getting Started with Java Structure of.
Chapter 2 storing numbers and creating objects Pages in Horstmann.
Chapter 2  Using Objects 1 Chapter 2 Using Objects.
Chapter 3b Standard Input and Output Sample Development.
Chapter 3: Introduction to Objects and Input/Output.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Java Programming, Second Edition Chapter Four Advanced Object Concepts.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 3 Introduction to Objects and Input/Output.
Chapter 2 – Continued Basic Elements of Java. Chapter Objectives Type Conversion String Class Commonly Used String Methods Parsing Numeric Strings Commonly.
Chapter 2: Java Fundamentals Type conversion,String.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Java Fundamentals 5. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
Chapter 7: Characters, Strings, and the StringBuilder.
Lecture 2 Objectives Learn about objects and reference variables.
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Java’s String Class.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 3 Introduction to Objects and Input/Output.
Department of Computer Engineering Using Objects Computer Programming for International Engineers.
Java Classes Chapter 1. 2 Chapter Contents Objects and Classes Using Methods in a Java Class References and Aliases Arguments and Parameters Defining.
Outline Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Strings and I/O. Lotsa String Stuff… There are close to 50 methods defined in the String class. We will introduce several of them here: charAt, substring,
Computer Programming 2 Lab (1) I.Fatimah Alzahrani.
C OMMON M ISTAKES CSC Java Program Structure  String Methods.
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Java Fundamentals 4.
More About Objects and Methods
Formatting Output & Enumerated Types & Wrapper Classes
3 Introduction to Classes and Objects.
Outline Creating Objects The String Class Packages Formatting Output
Introduction to Classes and Objects
Static Members and Methods
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II
Object Oriented Systems Lecture 03 Method
Methods.
Primitive Types Vs. Reference Types, Strings, Enumerations
OUTPUT STATEMENTS GC 201.
INPUT STATEMENTS GC 201.
EE422C - Software Design and Implementation II
CMSC 202 Static Methods.
Chapter 8: Collections: Arrays
Chapter 2 Using Objects.
Chapter 3: Introduction to Objects and Input/Output
Classes and Objects 5th Lecture
Chapter 3 Numerical Data
CHAPTER 6 GENERAL-PURPOSE METHODS
Java Classes and Objects 3rd Lecture
Chapter 3: Introduction to Objects and Input/Output
Objects and Classes Creating Objects and Object Reference Variables
Chapter 6 Objects and Classes
Classes and Objects Static Methods
Dr. Sampath Jayarathna Cal Poly Pomona
Outline Creating Objects The String Class The Random and Math Classes
Today in COMP 110 Brief static review The Math Class Wrapper Classes
Chapter 13 Abstract Classes and Interfaces Part 01
Chapter 6 Objects and Classes
Getting Started with Java
Chapter 7 Objects and Classes
Presentation transcript:

Chapter 4 Intermediate (part 1) CSC 238 Object Oriented Programming Chapter 4 Intermediate (part 1)

Static Field and Methods Predefined Classes and Wrapper Classes Topic Outline Static Field and Methods Predefined Classes and Wrapper Classes String Class

Static Fields and Methods Static variables are used so that all the instances of a class can share data. Static variables/field store values for the variables in a common memory location. Because of this common location, all objects of the same class are affected if one object changes the value of a static variable. Static methods can be called without creating an instance of the class

Static field Static field is also known as class field, where data shared by all instances of a class Static data belongs to the entire class not to individual object All objects of the class share the static data Object 2 Width: 2 Length: 4 Object 1 Width: 3 Length: 5 Counter : 2 public class Rectangle { …… private int width,length; private static int counter; } Both objects (Object 1 & Object 2 shares the same value of Counter

Static Method A method that does not operate on an object but receives all of its data as arguments. Independent function If the method has public modifier, it is referred as a general-purpose method which means it is constructed to be used to perform a general purpose task. It uses the keyword static public static void main(String[] args) {…..}

Static members of a class If a method or data is declared with modifier static, it means that the method or data can be invoked by using the name of the class. Example: public class ExampleStatic { private int x; //non-static data private static int y; //static data : public static int showStatic() //static method { return y=5; } } How would you call the static method? ExampleStatic.showStatic(); // the method is static and public How would you call the static data member? ExampleStatic.y = 10; //the data is static and public

Static data members of a class In previous example, you have a non-static data (x) and static data (y). Let say you instantiate objects of class ExampleStatic, only non-static data members of the class become data members of each object. For static data, Java allocates only one memory space. You may access the public static data members outside the class.

Static data members of a class Consider the following objects declarations: ExampleStatic obj1 = new ExampleStatic (30); ExampleStatic obj2 = new ExampleStatic (100); Static data belongs to the entire class not to individual object. obj2 x 100 obj1 x 30 y

Static Fields and Methods Example: Circle.java (Static Fields and Methods) public class Circle { /** The radius of the circle */ private double radius; /**The number of the objects created */ private static int numberOfObjects = 0; /**Construct a circle with radius 1 */ public Circle() { radius = 1.0; numberOfObjects++; } /**Construct a circle with specified radius*/ public Circle(double newRadius) { radius = newRadius; /**Return radius*/ public double getRadius() { return radius; } /**Set a new radius*/ public void setRadius(double newRadius) { radius = newRadius; /**Return numberOfObjects*/ public static int getNumberOfObjects() { return numberOfObjects; /**Return the area of this circle*/ public double findArea() { return radius * radius * Math.PI;

public class TestCircle { public static void main (String[] args) Main method : TestCircle.java public class TestCircle { public static void main (String[] args) Circle circle1 = new Circle(); //Create object named circle1 //Display circle1 BEFORE circle2 is created System.out.println(“Before creating circle2”); System.out.println(“circle1 is : ”); printCircle(circle1); Circle circle2 = new Circle(5); //Create another object named circle2 circle1.setRadius(9); //Change the radius in circle1 //Display circle1 and circle2 AFTER circle2 was created System.out.println(“\nAfter creating circle2 and modifying circle1 radius to 9 “); System.out.println(“circle1 is : “); System.out.println(“circle2 is : “); printCircle(circle2); } public static void printCircle(Circle c) // processor method: print circle information System.out.println(“radius (“ + c.getRadius() + “) and number of Circle objects (“ + Circle.getNumberOfObjects() + “)”);

Static Fields and Methods Below is the output of the program: return

Defining classes in one file You may define 2 classes in one file, but only one class in the file can be a public class The public class must have the same name as the file name The main class contains the main method that creates an object of the class

Example: TestCircle.java public class TestCircle { public static void main(String[] args) Circle myCircle = new Circle(); System.out.println(“The area of circle is “ + myCircle.findArea()); } class Circle double radius = 1.0; double findArea() return radius * radius * 3.14159; Main method Create a Circle object Define class named Circle Data member Processor method Return the area of this circle

Think: What is the output? public class FindMax { public static void main(String[] args) { int i = 5, j = 2, k; k = max (i, j); System.out.println(“The maximum between “ + i + “ and “ + j + “ is “ + k); } public static int max (int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result;

public class App { public static void main(String[] args) { short x=7; aMethod(x); System.out.println(“Variable of x is now ” + x); } public static int aMethod(int a) { System.out.println(“Received an int”); return a + 1; public static double aMethod(double b) { System.out.println(“Received a double”); return b + 1;

Pre-defined Classes

Pre-defined classes Usage Package Method Example Dialog Box javax.swing showInputDialog(String) showMessageDialog(String) String w = JOptionPane.showInputDialog(null, “Enter name”); showMessageDialog(null, “Good Morning!”); Format output java.text class name = DecimalFormat format(String) DecimalFormat n = new DecimalFormat(“00.00”) To display decimal placeholder n.format(364565.1454) Mathematical Methods java.lang Static methods in class Math are used. abs(n) pow(n1, n2) sqrt(n1) round(n) min(x, y) int x = Math.pow(4,2);

DecimalFormat Class Use a DecimalFormat object to format the numerical output. Example:

Math Class The Math class in the java.lang package contains class methods for commonly used mathematical functions. Example:

Math Class Some Math class methods:

Date Class The Date class from the java.util package is used to represent a date. When a Date object is created, it is set to today (the current date set in the computer) The class has toString method that converts the internal format to a string. Example: Output:

SimpleDateFormat The SimpleDateFormat class allows the Date information to be displayed with various format. Example:

GregorianCalendar Class Use a GregorianCalendar object to manipulate calendar information Example:

GregorianCalendar Class This table shows the class constants for retrieving different pieces of calendar information from Date.

GregorianCalendar Class Sample calendar retrieval:

Wrapper Classes Java provides routine for converting String to a primitive data types or vice versa It is called wrapper classes because the classes constructed by wrapping a class structure around the primitive data types

Wrapper Classes Wrapper Class Method Description Example Integer parseInt(String) Converts a string to int int x = Integer.parseInt(s); toString(x) Converts an int to string String s = Integer.toString(x); Long parseLong(string) Converts a string to long int Long x = Long.parseLong(s); Converts a long int to string String s = Long.toString(x); Float parseFloat(s) Converts a string to float float x = Float.parseFloat(s); Converts a float to string String s = Float.toString(x); Double parseDouble(s) Converts a string to double double x = Double.parseDouble(s); Converts a double to string String s = Double.toString(x);

String Class

Introduction A sequence of characters separated by double quotes is a String constant. There are close to 50 methods defined in the String class.

substring() Assume str is a String object and properly initialized to a String. str.substring( i, j ) will return a new string by extracting characters of str from position i to j-1 where 0  i  length of str, 0  j  length of str, and i  j. If str is “programming”, then str.substring(3, 7) will create a new string whose value is “gram” because g is at position 3 and m is at position 6. The original string str remains unchanged. Example:

length() Assume str is a String object and properly initialized to a string. str.length( ) will return the number of characters in str. If str is “programming” , then str.length( ) will return 11 because there are 11 characters in it. The original string str remains unchanged.

indexOf() Assume str and substr are String objects and properly initialized. str.indexOf( substr ) will return the first position substr occurs in str. If str is “programming” and substr is “gram” , then str.indexOf(substr) will return 3 because the position of the first character of substr in str is 3. If substr does not occur in str, then –1 is returned. The search is case-sensitive. Example:

charAt() Individual characters in a String accessed with the charAt method. Example:

equals() Determines whether two String objects contain the same data. Example:

equalsIgnoreCase() Determines whether two String objects contain the same data, ignoring the case of the letters in the String. Example:

Other useful String methods:

Exercise What will be the output for the following codes: String word = “2002 world cup in Japan and Korea”; int k = word.indexOf(‘c’); System.out.println(“Index of c is ” + k); int p = word.lastIndexOf(‘o’); System.out.println(“The last index of o is ” + p); System.out.println(word.substring(p)); System.out.println(word.charAt(7)); System.out.println(word.length()); Index of c is 11 The last index of o is 29 orea r 33

Exercise System.out.println(greeting + “Seven of Nine.”); What is the output produced by the following? String greeting = “How do you do”; System.out.println(greeting + “Seven of Nine.”); b) String test = “abcdefg”; System.out.println(test.length()); System.out.println(test.charAt(1)); System.out.println(test.substring(3));

Exercise c) System.out.println(“abc\ndef”);   d) String test = “Hello John”; test = test.toUpperCase(); System.out.println(test); e) String s1 = “Hello John”; String s2 = “hello john”; if(s1.equals(s2)) System.out.println(“Equal”); System.out.println(“End”);

Exercise f) String s1 = “Hello John”; String s2 = “hello john”; s1 = s1.toUpperCase(); s2 = s2.toUpperCase(); if(s1.equals(s2)) System.out.println(“Equal”); System.out.println(“End”);