Anda di halaman 1dari 40

CSC 238

Object Oriented Programming


StaticField and Methods
Predefined Classes and
Wrapper Classes
String Class
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
3
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


public class Rectangle Object 1 Object 2
{
private int width,length; Width: 3 Width: 2
private static int counter; Both objects
} Length: Length: (Object 1 & Object 2
5 4 shares the same
value of Counter
Counter
:2
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)
{..}
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
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.
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.

obj1 x 30 obj2 x 100

y 0
Example: Circle.java (Static Fields and /**Return radius*/
Methods)
public double getRadius() {
public class Circle { return radius;
/** The radius of the circle */ }
private double radius;
/**Set a new radius*/
/**The number of the objects created */
public void setRadius(double
private static int numberOfObjects
= 0; newRadius) { radius =
newRadius;
/**Construct a circle with radius 1 */ }
public Circle() {
radius = 1.0; /**Return numberOfObjects*/
numberOfObjects++;
public static int
}
getNumberOfObjects() {
/**Construct a circle with specified return numberOfObjects;
radius*/ }
public Circle(double newRadius) {
radius = newRadius; /**Return the area of this circle*/
numberOfObjects++;
} public double findArea() {
return radius * radius * Math.PI;
}
} 9
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 : );
printCircle(circle1);
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() + ));
}
} 10
Below is the output of the program:

return
11
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
public class TestCircle
{
public static void main(String[] args) Main method
{
Circle myCircle = new Circle(); Create a Circle object
System.out.println(The area of circle is +
myCircle.findArea());
}
}

class Circle Define class named Circle


{
double radius = 1.0; Data member

double findArea() Processor method


{
return radius * radius * 3.14159; Return the area of this circle
}
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;
}
}
Usage Package Method Example

Dialog Box javax.swing showInputDialog(String) String w =


JOptionPane.showInputDialog(
null, Enter name);

showMessageDialog(null,
showMessageDialog(String) Good Morning!);

Format java.text DecimalFormat n = new


output format(String) DecimalFormat(00.00)
class name =
DecimalFormat To display decimal placeholder
n.format(364565.1454)

Mathematical java.lang abs(n) int x = Math.pow(4,2);


Methods pow(n1, n2)
Static methods sqrt(n1)
in class Math round(n)
are used. min(x, y)
Use a DecimalFormat object to format the
numerical output.
Example:
The Math class in the java.lang
package contains class methods for
commonly used mathematical
functions.
Example:
Some Math class methods:
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:
The SimpleDateFormat class allows
the Date information to be displayed
with various format.
Example:
Use a GregorianCalendar object to
manipulate calendar information
Example:
This table shows the class constants for
retrieving different pieces of calendar
information from Date.
Sample calendar retrieval:
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 Method Description Example
Class
Integer parseInt(String) Converts a string to int int x = Integer.parseInt(s);

Integer toString(x) Converts an int to string String s = Integer.toString(x);

Long parseLong(string) Converts a string to long Long x = Long.parseLong(s);


int
Long toString(x) Converts a long int to String s = Long.toString(x);
string
Float parseFloat(s) Converts a string to float float x = Float.parseFloat(s);

Float toString(x) Converts a float to string String s = Float.toString(x);

Double parseDouble(s) Converts a string to double x =


double Double.parseDouble(s);
Double toString(x) Converts a double to String s = Double.toString(x);
string
A sequence of characters separated by double
quotes is a String constant.
There are close to 50 methods defined in the
String class.
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:
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.
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:
Individual characters in a String accessed
with the charAt method.
Example:
Determines whether two String objects
contain the same data.
Example:
Determines whether two String objects
contain the same data, ignoring the
case of the letters in the String.
Example:
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());
What is the output produced by the
following?
a) 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));
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);
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);

Anda mungkin juga menyukai