Download presentation
Presentation is loading. Please wait.
1
Chapter 4 Intermediate (part 1)
CSC 238 Object Oriented Programming Chapter 4 Intermediate (part 1)
2
Static Field and Methods Predefined Classes and Wrapper Classes
Topic Outline Static Field and Methods Predefined Classes and Wrapper Classes String Class
3
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
4
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
5
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) {…..}
6
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
7
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.
8
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
9
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;
10
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() + “)”);
11
Static Fields and Methods
Below is the output of the program: return
12
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
13
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 * ; Main method Create a Circle object Define class named Circle Data member Processor method Return the area of this circle
14
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;
15
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;
16
Pre-defined Classes
17
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( ) 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);
18
DecimalFormat Class Use a DecimalFormat object to format the numerical output. Example:
19
Math Class The Math class in the java.lang package contains class methods for commonly used mathematical functions. Example:
20
Math Class Some Math class methods:
21
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:
22
SimpleDateFormat The SimpleDateFormat class allows the Date information to be displayed with various format. Example:
23
GregorianCalendar Class
Use a GregorianCalendar object to manipulate calendar information Example:
24
GregorianCalendar Class
This table shows the class constants for retrieving different pieces of calendar information from Date.
25
GregorianCalendar Class
Sample calendar retrieval:
26
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
27
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);
28
String Class
29
Introduction A sequence of characters separated by double quotes is a String constant. There are close to 50 methods defined in the String class.
30
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:
31
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.
32
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:
33
charAt() Individual characters in a String accessed with the charAt method. Example:
34
equals() Determines whether two String objects contain the same data.
Example:
35
equalsIgnoreCase() Determines whether two String objects contain the same data, ignoring the case of the letters in the String. Example:
36
Other useful String methods:
37
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
38
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));
39
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”);
40
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”);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.