SlideShare a Scribd company logo
1 of 65
© Copyright IBM Corporation 2009
IBM Global Business Services
Course Title
Core Java
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
1
Day 2
IBM Global Business Services
© Copyright IBM Corporation 2009
Agenda
Today we will cover the following two modules:
 Inheritance and Polymorphism
 Classes in Java
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
2
IBM Global Business Services
© Copyright IBM Corporation 2009
Day 2: Objectives
At the end of Day 2, you should be able to:
 Define inheritance and polymorphism
 Identify the classes in Java
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
3
© Copyright IBM Corporation 2009
IBM Global Business Services
Course Title
Core Java
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
4
Day 2
Module 1: Inheritance and Polymorphism
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
5
Module 1: Objectives
After completion of this module, you should be able to:
 Understand inheritance in Java.
 Understand inheriting classes.
 Define overriding methods.
 Explain interfaces and methods.
 Explain abstract classes and methods.
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
6
Inheritance and Polymorphism: Agenda
 Topic 1: Understand Inheritance
 Topic 2: Inheriting classes
 Topic 3: Overriding methods
 Topic 4: Creating Interfaces and Methods
 Topic 5: Creating Abstract Classes and Methods
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
7
Understand inheritance
 The ability of a class of objects to inherit the properties and methods from
another class, called its parent or base class.
 The class that inherits the data members and methods is known as subclass
or child class.
 The class from which the subclass inherits is known as base / parent class.
 In Java, a class can only extend one parent.
No Multiple Inheritance In Java for classes
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
8
Inheriting classes
•A Java class inherits another class using the extends keyword after
the class name followed by the parents class name as below
public class childclassname extends superclassname
The child class inherits all the instance variables and methods of the
parent class
IBM Global Business Services
© Copyright IBM Corporation 2009
Example: Inheriting classes
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
9
public class Person {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Employee extends Person {
private String eid;
public void setEid(String eid) {
this.eid=eid;
}
public String getEid() {
return eid;
}
}
Parent Child
The extends
keyword
indicates
inheritance
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
10
Types of inheritance
1. Single Level Inheritance
Derives a subclass from a single superclass.
Class Person
Class Employee Class Student
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
11
Types of inheritance (continued)
Example
2. Multilevel Inheritance
Inherits the properties of another subclass.
Class Person
Class Employee
Class Regular
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
12
 Method overriding is defined as creating a non-static method in the subclass
that has the same return type and signature as a method defined in the
superclass.
Overriding methods
Signature of a method includes
name number sequence type
of arguments in a method
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
13
Overriding methods (continued)
 You can override (most) methods in a parent class by defining a method with
the same name and parameter list in the child class.
 This is useful for changing the behavior of a class without changing its
interface.
 You cannot override the static and final methods of a superclass.
 A subclass must override the abstract methods of a superclass.
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
14
Example: Overriding methods
public class Person {
private String name;
private String ssn;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getId() {
return ssn;
}
}
getId
method is
overridde
n
public class Employee extends Person
{
private String empId;
public void setId(String empId)
{
this.empId=empId;
}
public String getId() {
return empId;
}
}
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
15
Example: Use of “super” keyword
Allows you to access methods and properties of the parent class
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Employee extends Person {
private String empID;
public Employee(String name) {
super(name); // Calls Person constructor
}
public void setID(String empID){
this.empID=empID;
}
public String getID(){
return empID;
}
}
IBM Global Business Services
© Copyright IBM Corporation 2009
Restricting inheritance using final keyword
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
16
Parent
Child
Restricting
Inherited
capability
Using modifier
with a class will
restrict
the inheritance
capability of that
class
final
IBM Global Business Services
© Copyright IBM Corporation 2009
Final classes: A way for preventing classes being extended
 We can prevent an inheritance of classes by other classes by declaring
them as final classes.
 This is achieved in Java by using the keyword final as follows:
– final class Regular
– { // members
– }
– final class Employee extends Person
– { // members
– }
 Any attempt to inherit these classes will cause an error.
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
17
IBM Global Business Services
© Copyright IBM Corporation 2009
Final members: A way for preventing overriding of members
in subclasses
 All methods and variables can be overridden by default in subclasses.
 This can be prevented by declaring them as final using the keyword “final” as
a modifier. For example:
– final int marks = 100;
– final void display();
 This ensures that functionality defined in this method cannot be altered any.
Similarly, the value of a final variable cannot be altered.
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
18
IBM Global Business Services
© Copyright IBM Corporation 2009
Understanding interfaces
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
19
 A programmer’s tool for specifying certain behaviors that an object must have
in order to be useful for some particular task.
 Interface is a conceptual entity.
 Can contain only constants (final variables) and non-implemented methods
(Non – implemented methods are also known as abstract methods).
IBM Global Business Services
© Copyright IBM Corporation 2009
Example: Understanding interfaces
 For example, you might specify Driver interface as part of a Vehicle object
hierarchy.
– A human can be a Driver, but so can a Robot.
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
20
IBM Global Business Services
© Copyright IBM Corporation 2009
Creating interfaces and methods
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
21
interface InterfaceName
{
// Constant/Final Variable Declaration
// Methods Declaration – only method body
}
public interface Driver
{
void turnWheel (double angle);
void pressBrake (double amount);
} Syntax for Interface
Declaration
Example
IBM Global Business Services
© Copyright IBM Corporation 2009
Creating interfaces and methods (continued)
Interface implementation
 Interfaces are used like super-classes who properties are inherited by
classes. This is achieved by creating a class that implements the give
interface as follows:
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
22
public class BusDriver extends Person implements Driver
{
// include each of the two methods from Driver
}
class ClassName implements Interface1, Interface2,…., InterfaceN
{
// Body of Class
}
Syntax for Interface
Implementation
Example
IBM Global Business Services
© Copyright IBM Corporation 2009
Creating interfaces and methods (continued)
Interface implementation
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
23
speak()
Politician Priest
<<Interface>>
Speaker
speak() speak()
Lecturer
speak()
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
24
Inheriting interfaces
 Like classes, interfaces can also be extended. The new sub-interface will
inherit all the members of the super-interface in the manner similar to
classes.
 This is achieved by using the extends keyword.
interface InterfaceName2 extends InterfaceName1
{
// Body of InterfaceName2
}
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
25
Understanding abstract class
 An Abstract class is a conceptual class.
 An Abstract class cannot be instantiated – objects cannot be created.
 Abstract classes provides a common root for a group of classes, nicely tied
together in a package.
 When we define a class to be “final”, it cannot be extended. In certain
situation, we want properties of classes to be always extended and used.
Such classes are called Abstract Classes.
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
26
Properties of an abstract class
 A class with one or more abstract methods is automatically abstract and it
cannot be instantiated.
 A class declared abstract, even with no abstract methods can not be
instantiated.
 A subclass of an abstract class can be instantiated if it overrides all abstract
methods by implementation them.
 A subclass that does not implement all of the superclass abstract methods is
itself abstract; and it cannot be instantiated.
 We cannot declare abstract constructors or abstract static methods.
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
27
Creating abstract classes and methods
Shape
Circle Rectangle
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
28
Creating abstract classes and methods (continued)
abstract class ClassName
{
...
…
abstract DataType
MethodName1();
…
…
DataType Method2()
{
// method body
}
}
abstract public class Shape
{
public abstract double area();
public void move()
{ // non-abstract method
// implementation
}
}
Syntax
Example
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
29
public Circle extends Shape {
private double r;
private static final double PI =3.1415926535;
public Circle() { r = 1.0; }
public double area() { return PI * r * r; }
…
}
public Rectangle extends Shape {
private double l, b;
public Rectangle() { l = 0.0; b=0.0; }
public double area() { return l * b; }
...
}
Creating abstract classes and methods (continued)
© Copyright IBM Corporation 2009
IBM Global Business Services
Course Title
Core Java
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
30
Day 2
Module 1: Classes in Java
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
31
Module 1: Objectives
After completion of this module, you should be able to:
 Define Object class
 Explain java.Util package and its different components including string class,
date class, calendar class, and string buffer class
 Understand how to use String classes
 Understand how to convert objects to strings
 Understand how to convert strings to numbers
IBM Global Business Services
© Copyright IBM Corporation 2009
Classes in Java: Agenda
 Object class
 Overview of java.util package
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
32
IBM Global Business Services
© Copyright IBM Corporation 2009
Object class
 Every class that we create extends the class Object by default. That is the
Object class is at the highest of the hierarchy. This facilitates to pass an
object of any class to be passed as an argument to methods.
 The methods in this class are:
– equals(Object ref) - returns if both objects are equal
– finalize( ) - method called when an object’s memory is destroyed
– getClass( ) - returns class to which the object belongs
– hashCode( )- returns the hashcode of the class
– notify( ) - method to give message to a synchronized methods
– notifyAll( ) - method to give message to all synchronized methods
– toString() - return the string equivalent of the object name
– wait() - suspends a thread for a while
– wait(...) - suspends a thread for specified time in seconds
–
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
33
IBM Global Business Services
© Copyright IBM Corporation 2009
Classes in Java: Agenda
 Object class
 Overview of java.util package
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
34
IBM Global Business Services
© Copyright IBM Corporation 2009
Overview of java.util package
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
35
Class Description
Class
Supports runtime processing of the class information of an
object.
String Provides functionality for String manipulation.
Integer Provides methods to convert an Integer object to a String object.
Math Provides functions for statistical, exponential operations.
IBM Global Business Services
© Copyright IBM Corporation 2009
Overview of java.util package (continued)
Class Description
Object
All the classes in the java.lang package and classes belongs to other
packages are the subclasses of the Object class.
System
It provides a standard interface to input output and error devices, such
as Keyboard & VDU.
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
36
 The java.lang package provides various classes and interfaces that are
fundamental to Java programming.
 The java.lang package contains various classes that represent primitive
data types, such as int, char, long, and double.
 Classes provided by the java.lang package:
IBM Global Business Services
© Copyright IBM Corporation 2009
String class
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
37
Method Name Description
public int length() Returns the length of a String object.
public String toUpperCase()
Converts all the characters in the string object in
uppercase.
public String toLowerCase()
Converts all the characters in the string object in
lowercase.
public String toString() Returns the String representation of the object.
IBM Global Business Services
© Copyright IBM Corporation 2009
String class (continued)
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
38
Method Name Description
public boolean equals (Object ob)
Compares two strings and return true, if both the
strings are equal else return false.
public int compareTo (String str2)
Compares current String object with another String
object. If the Strings are same the return value is 0 else
the return value is non zero.
If str1 > str2 then return value is a positive number
If str1<str2 then return value is a negative number
IBM Global Business Services
© Copyright IBM Corporation 2009
String class (continued)
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
39
Method Name Description
public int indexOf (String str)
public int indexOf (String str, int startindex)
searches for the first occurrence of a
character or a substring in the invoking
String and returns the position if found else
return -1.
public int lastIndexOf(String str)
public int lastIndexOf(String str, int startindex)
searches for the last occurrence of a
character or a substring in the invoking
String and returns the position if found else
return -1.
IBM Global Business Services
© Copyright IBM Corporation 2009
String class (continued)
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
40
Method Name Description
public String trim()
Returns a copy of the string, with leading
and trailing whitespace omitted.
public char charAt( int index)
Returns the char value at the specified
index.
public String concat(String str)
Concatenates the specified String to the
end of the String.
public String subString(int startInd)
public String subString(int startInd, int endInd)
Returns a new String that is a substring of
a String.
IBM Global Business Services
© Copyright IBM Corporation 2009
String class (continued)
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
41
Method Name Description
public boolean startsWith(String prefix)
Tests if the String starts with the
specified prefix.
public boolean endsWith(int suffix)
Tests if the String end with the
specified suffix.
public char[] toCharArray()
Converts this String to a new
character array.
public void getChars(int scrBegin,int srcEnd,char[]
destination,int dstBegin)
Copies characters from this string
into the destination character
array.
IBM Global Business Services
© Copyright IBM Corporation 2009
Overview of java.util package (continued)
 The java.util package provides various utility classes and interfaces that
support date and calendar operations, String manipulations and Collections
manipulations. Classes provided by the java.util package
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
42
Class Description
Date Encapsulates date and time information.
Calendar Provides support for date conversion.
GregorianCalendar
It is a subclass of Calendar class, provides
support for standard calendar used
worldwide.
IBM Global Business Services
© Copyright IBM Corporation 2009
Date class
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
43
Date: Date class represent date and time. There are several constructors for Date objects.
Constructors :
Date() : produces the current date and time.
Date(int year, int month, ind dayofmonth)
Date(int year, int month, ind dayofmonth,int hours, int mins)
Date(int year, int month, ind dayofmonth,int hours, int mins,int secs)
Date(long milliseconds) : no of milliseconds from January 1, 1970
midnight
Date(String strdate) : Converts the string representation of date
into a Date object.
Methods
boolean after(Date pdate) - returns true if the current date is after pdate.
boolean before(Date pdate) - returns true if the current date is before pdate.
boolena eqauls(Date pdate) - returns true if the current date same as pdate.
int getDay()
int getMonth()
int getYear()
void setDay(int dayno)
void setMonth(int monthno)
void setYear(int year)
IBM Global Business Services
© Copyright IBM Corporation 2009
Date class (continued)
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
44
Example : Usage of Date class. SourceFile : datetest.java
import java.io.*;
import java.util.*;
public class datetest{
public static void main(String args[])
{
Date today = new Date();
System.out.println("Today's date is "+today.toString());
System.out.println("Current time is "+today.getTime());
Date aday = new Date(1998,10,9);
Date bday = new Date(1998,11,10);
Date cday = new Date(1998,9,23);
Date tday = new Date(1998,9,23,12,20);
System.out.println("A day is "+aday.toString());
System.out.println("B day is "+bday.toString());
System.out.println("C day is "+cday.toString());
System.out.println("T day with time is "+tday.toString());
if (aday.before(bday))
System.out.println(" a is before b");
if (cday.after(bday))
System.out.println(" c is after b");
System.out.println("Time of aday is "+aday.getTime());
System.out.println("Time of tday is "+tday.getTime());
Date today1 = new Date();
if (today1.equals(today))
System.out.println(" today is same as today1");
}
IBM Global Business Services
© Copyright IBM Corporation 2009
Calendar class
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
45
import java.util.Calendar;
class CalendarDemo
{
public static void main(String args[])
{
String months[]= {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
Calendar cal = Calendar.getInstance();
System.out.println("The Date is: ");
System.out.print(months[cal.get(Calendar.MONTH)]);
System.out.print(" " + cal.get(Calendar.DATE) + " ");
System.out.println(cal.get(Calendar.YEAR));
// Setting Time
cal.set(Calendar.HOUR, 10);
cal.set(Calendar.MINUTE, 27);
cal.set(Calendar.SECOND, 0);
System.out.print("Time is: ");
System.out.print(cal.get(Calendar.HOUR) + ":");
System.out.print(cal.get(Calendar.MINUTE) + ":");
System.out.print(cal.get(Calendar.SECOND));
}
}
IBM Global Business Services
© Copyright IBM Corporation 2009
Calendar class (continued)
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
46
import java.util.*;
public class GregorianCalendarDemo
{
public static void main(String args[])
{
Calendar calendar = new GregorianCalendar();
System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.MONTH+1));
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
}
}
IBM Global Business Services
© Copyright IBM Corporation 2009
StringBuffer Class
 Class StringBuffer
– Used for creating and manipulating dynamic string data
 i.e., modifiable Strings
– Can store characters based on capacity
 Capacity expands dynamically to handle additional characters
– CANNOT use operators + and += for string concatenation
– Fewer utility methods (e.g. no substring, trim, ....)
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
47
IBM Global Business Services
© Copyright IBM Corporation 2009
StringBuffer Class (continued)
 Three StringBuffer constructors
– public StringBuffer();
 empty content, initial capacity of 16 characters
– public StringBuffer(int length);
 empty content, initial capacity of length characters
– public StringBuffer(String str);
 contain the characters of str, capacity is the number of characters in str plus 16
– Use capacity() method to get the capacity.
– If the internal buffer overflows, the capacity is automatically made larger.
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
48
IBM Global Business Services
© Copyright IBM Corporation 2009
StringBuffer Methods (continued)
 Method length
– Return StringBuffer length (the actual number of characters stored).
 Method capacity
– Return StringBuffer capacity (the number of characters can be stored without
expansion)
 Method setLength
– Increase or decrease StringBuffer length. If the new length is less than the current
length of the string buffer, the string buffer is truncated.
 Method ensureCapacity
– Set StringBuffer capacity
– The new capacity is the larger of the minimumCapacity argument or twice the old
capacity, plus 2.
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
49
IBM Global Business Services
© Copyright IBM Corporation 2009
Manipulating StringBuffer characters
 Method charAt
– Return StringBuffer character at specified index
 Method setCharAt
– Set StringBuffer character at specified index
 Method reverse
– Reverse StringBuffer contents
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
50
IBM Global Business Services
© Copyright IBM Corporation 2009
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
51
StringBuffer Methods (continued)
 Method append
– Allow data-type values to be added to StringBuffer
– Should NOT use + and += for StringBuffer
– Overloaded methods to append primitive data type values, String, char array and
the String representation of any Objects.
 Method insert
– Similar to append and can specify where to insert
 Methods delete and deleteCharAt
– Allow characters to be removed from StringBuffer
– delete : delete a range of characters, from start to end-1
– deleteCharAt : delete a character at a specified location
IBM Global Business Services
© Copyright IBM Corporation 2009
StringBuffer class
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
52
 public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb =new StringBuffer("Hello");
System.out.println("buffer= " +sb);
System.out.println("length= " +sb.length());
System.out.println("capacity= " +sb.capacity());
//appending and inserting into StringBuffer.
String s;
int a = 42;
StringBuffer sb1= new StringBuffer(40);
s= sb1.append("a=").append(a).append("!").toString();
System.out.println(s);
StringBuffer sb2 = new StringBuffer("I JAVA!");
sb2.insert(2, "LIKE");
System.out.println(sb2);
}
}
IBM Global Business Services
© Copyright IBM Corporation 2009
Converting object to string
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
53
 Any Java reference type or primitive that appears where a String is expected
will be converted into a string.
– System.out.println("1 + 2 = " + (1 + 2));
 For an reference type (object)
– this is done by inserting code to call String toString() on the reference.
– All reference types inherit this method from java.lang.Object and override this
method to produce a string that represents the data in a form suitable for printing.
 To provide this service for Java's primitive types, the compiler must wrap the
type in a so-called wrapper class, and call the wrapper class's toString
method.
– String arg1 = new Integer(1 + 2).toString();
IBM Global Business Services
© Copyright IBM Corporation 2009
Converting object to string (continued)
 For user defined classes they will inherit the standard Object.toString() which
produces something like "ClassName@123456" (where the number is the
hashcode representation of the object).
 To have something meaningful the classes have to provide a method with the
signature public String toString().
public class Car()
{
----
---
String toString()
{
return brand + ” : ” + color + ” : ”+wheels+” : “+ speed;
}
}
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
54
IBM Global Business Services
© Copyright IBM Corporation 2009
Converting string to numbers
 Many data type wrapper classes provide the valueOf(String s) method which
converts the given string into a numeric value.
 The syntax is straightforward. It requires using the static Integer.valueOf(String s)
and intValue() methods from the java.lang.Integer class.
 To convert the String "22" into the int 22 you would write
– int i = Integer.valueOf("22").intValue();
 Doubles, floats and longs are converted similarly. To convert a String like "22" into
the long value 22 you would write
– long l = Long.valueOf("22").longValue();
 To convert "22.5" into a float or a double you would write:
– double x = Double.valueOf("22.5").doubleValue(); float y =
Float.valueOf("22.5").floatValue();
 If the passed value is non-numeric like “Four," it will throw a
NumberFormatException.
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
55
IBM Global Business Services
© Copyright IBM Corporation 2009
Example: Converting string to numbers
class Energy
{
public static void main (String args[])
{
double c = 2.998E8; // meters/second
double mass = Double.valueOf(args[0]).doubleValue();
double E = mass * c * c; System.out.println(E + " Joules");
}
}
Here's the output:
$ javac Energy.java $ java Energy 0.0456 4.09853e+15 Joules
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
56
IBM Global Business Services
© Copyright IBM Corporation 2009
Regular expression
 Regular expressions are a way to describe a set of strings based on common
characteristics shared by each string in the set. They can be used to search,
edit, or manipulate text and data.
 The regular expression syntax supported by the java.util.regex API
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
57
IBM Global Business Services
© Copyright IBM Corporation 2009
Regular expression (continued)
 The java.util.regex package primarily consists of three classes: Pattern,
Matcher, and PatternSyntaxException.
 A Pattern object is a compiled representation of a regular expression.
 The Pattern class provides no public constructors.
– To create a pattern, you must first invoke one of its public static compile methods,
which will then return a Pattern object.
– These methods accept a regular expression as the first argument; the first few
lessons of this trail will teach you the required syntax.
 A Matcher object is the engine that interprets the pattern and performs match
operations against an input string.
– Like the Pattern class, Matcher defines no public constructors. You obtain a
Matcher object by invoking the matcher method on a Pattern object.
 A PatternSyntaxException object is an unchecked exception that indicates a
syntax error in a regular expression pattern.
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
58
IBM Global Business Services
© Copyright IBM Corporation 2009
Regular expression (continued)
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
59
import java.io.Console;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegexTestHarness {
public static void main(String[] args){
Console console = System.console();
if (console == null) {
System.err.println("No console.");
System.exit(1);
}
IBM Global Business Services
© Copyright IBM Corporation 2009
Regular expression (continued)
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
60
while (true) {
Pattern pattern =
Pattern.compile(console.readLine("%nEnter your regex: "));
Matcher matcher =
pattern.matcher(console.readLine("Enter input string to search: "));
boolean found = false;
while (matcher.find()) {
console.format("I found the text "%s" starting at " +
"index %d and ending at index %d.%n",
matcher.group(), matcher.start(), matcher.end());
found = true;
}
if(!found){
console.format("No match found.%n");
}
}
}
}
Compile the
REGEX pattern
Get matcher
from static
method on
Pattern class
Seed the matcher
with the string that
you want to find
matches
Find parts of
the string that
match the
REGEXP
Find the group ofchars that
matched (as a String) and
where those chars started
and ended in the string to be
matched
IBM Global Business Services
© Copyright IBM Corporation 2009
Regular expression (continued)
 Character classes
– Enter your regex: [bcr]at
– Enter input string to search: bat
– I found the text "bat" starting at index 0 and ending at index 3.
 Negation and Ranges
– Enter your regex: [^bcr]at
– Enter input string to search: cat
– No match found.
– Enter your regex: [a-c]
– Enter input string to search: a
– I found the text "a" starting at index 0 and ending at index 1.
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
61
IBM Global Business Services
© Copyright IBM Corporation 2009
Regular expression: Predefined character classes
Any character (may or may not match the terminators
 d A digit: [0-9]
 D A non-digit: [^0-9]
 s A whitespace character: [ tnx0Bfr]
 S A non-whitespace character: [^s]
 w A word character: [a-zA-Z_0-9]
 W A non-word character: [^w]
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
62
IBM Global Business Services
© Copyright IBM Corporation 2009
Regular expression: Matcher methods
 A matcher is created from a pattern by invoking the pattern's matcher method.
Once created, a matcher can be used to perform three different kinds of
match operations:
– The matches method attempts to match the entire input sequence against the
pattern.
– The looking at method attempts to match the input sequence, starting at the
beginning, against the pattern.
– The find method scans the input sequence looking for the next subsequence that
matches the pattern
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
63
IBM Global Business Services
© Copyright IBM Corporation 2009
Rational Tools Overview | IBM Internal Use | Document ID | 8 June 2009
64
Questions
IBM Global Business Services
© Copyright IBM Corporation 2009
Day 2 Summary
At the end of Day 2, we see that you are now able to:
 Define inheritance and polymorphism
 Identify the classes in Java
Core Java | IBM Internal Use | Day 1 | 16-Jun-09
65

More Related Content

Similar to Core JAVA Training.ppt

Introducing java oop concepts
Introducing java oop conceptsIntroducing java oop concepts
Introducing java oop conceptsIvelin Yanev
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++Mohamed Essam
 
Net Interview-Questions 1 - 16.pdf
Net Interview-Questions 1 - 16.pdfNet Interview-Questions 1 - 16.pdf
Net Interview-Questions 1 - 16.pdfPavanNarne1
 
2. oop with c++ get 410 day 2
2. oop with c++ get 410   day 22. oop with c++ get 410   day 2
2. oop with c++ get 410 day 2Mukul kumar Neal
 
9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot missMark Papis
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using ReflectionGanesh Samarthyam
 
Introduction to Java -unit-1
Introduction to Java -unit-1Introduction to Java -unit-1
Introduction to Java -unit-1RubaNagarajan
 
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxINDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxIndu65
 
C#.net, C Sharp.Net Online Training Course Content
C#.net, C Sharp.Net Online Training Course ContentC#.net, C Sharp.Net Online Training Course Content
C#.net, C Sharp.Net Online Training Course ContentSVRTechnologies
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.pptrani marri
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
Core java-introduction
Core java-introductionCore java-introduction
Core java-introductionRamlal Pawar
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examplesbindur87
 

Similar to Core JAVA Training.ppt (20)

Lecture 12
Lecture 12Lecture 12
Lecture 12
 
Introducing java oop concepts
Introducing java oop conceptsIntroducing java oop concepts
Introducing java oop concepts
 
Ganesh groups
Ganesh groupsGanesh groups
Ganesh groups
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
Net Interview-Questions 1 - 16.pdf
Net Interview-Questions 1 - 16.pdfNet Interview-Questions 1 - 16.pdf
Net Interview-Questions 1 - 16.pdf
 
2. oop with c++ get 410 day 2
2. oop with c++ get 410   day 22. oop with c++ get 410   day 2
2. oop with c++ get 410 day 2
 
9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss
 
Understanding And Using Reflection
Understanding And Using ReflectionUnderstanding And Using Reflection
Understanding And Using Reflection
 
Introduction to Java -unit-1
Introduction to Java -unit-1Introduction to Java -unit-1
Introduction to Java -unit-1
 
Opps
OppsOpps
Opps
 
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptxINDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
INDUMATHY- UNIT 1 cs3391 oops introduction to oop and java.pptx
 
C#.net, C Sharp.Net Online Training Course Content
C#.net, C Sharp.Net Online Training Course ContentC#.net, C Sharp.Net Online Training Course Content
C#.net, C Sharp.Net Online Training Course Content
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
lecture3.pptx
lecture3.pptxlecture3.pptx
lecture3.pptx
 
Java oop concepts
Java oop conceptsJava oop concepts
Java oop concepts
 
Core java-introduction
Core java-introductionCore java-introduction
Core java-introduction
 
OOP and C++Classes
OOP and C++ClassesOOP and C++Classes
OOP and C++Classes
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 

Recently uploaded

Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...EduSkills OECD
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesPooky Knightsmith
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17Celine George
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...Nguyen Thanh Tu Collection
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024Borja Sotomayor
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFVivekanand Anglo Vedic Academy
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxMarlene Maheu
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi RajagopalEADTU
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSean M. Fox
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文中 央社
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................MirzaAbrarBaig5
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesAmanpreetKaur157993
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppCeline George
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxAdelaideRefugio
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptxPoojaSen20
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnershipsexpandedwebsite
 

Recently uploaded (20)

Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical Principles
 
How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17How To Create Editable Tree View in Odoo 17
How To Create Editable Tree View in Odoo 17
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
The Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDFThe Story of Village Palampur Class 9 Free Study Material PDF
The Story of Village Palampur Class 9 Free Study Material PDF
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptx
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading RoomSternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
Sternal Fractures & Dislocations - EMGuidewire Radiology Reading Room
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 

Core JAVA Training.ppt

  • 1. © Copyright IBM Corporation 2009 IBM Global Business Services Course Title Core Java Core Java | IBM Internal Use | Day 1 | 16-Jun-09 1 Day 2
  • 2. IBM Global Business Services © Copyright IBM Corporation 2009 Agenda Today we will cover the following two modules:  Inheritance and Polymorphism  Classes in Java Core Java | IBM Internal Use | Day 1 | 16-Jun-09 2
  • 3. IBM Global Business Services © Copyright IBM Corporation 2009 Day 2: Objectives At the end of Day 2, you should be able to:  Define inheritance and polymorphism  Identify the classes in Java Core Java | IBM Internal Use | Day 1 | 16-Jun-09 3
  • 4. © Copyright IBM Corporation 2009 IBM Global Business Services Course Title Core Java Core Java | IBM Internal Use | Day 1 | 16-Jun-09 4 Day 2 Module 1: Inheritance and Polymorphism
  • 5. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 5 Module 1: Objectives After completion of this module, you should be able to:  Understand inheritance in Java.  Understand inheriting classes.  Define overriding methods.  Explain interfaces and methods.  Explain abstract classes and methods.
  • 6. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 6 Inheritance and Polymorphism: Agenda  Topic 1: Understand Inheritance  Topic 2: Inheriting classes  Topic 3: Overriding methods  Topic 4: Creating Interfaces and Methods  Topic 5: Creating Abstract Classes and Methods
  • 7. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 7 Understand inheritance  The ability of a class of objects to inherit the properties and methods from another class, called its parent or base class.  The class that inherits the data members and methods is known as subclass or child class.  The class from which the subclass inherits is known as base / parent class.  In Java, a class can only extend one parent. No Multiple Inheritance In Java for classes
  • 8. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 8 Inheriting classes •A Java class inherits another class using the extends keyword after the class name followed by the parents class name as below public class childclassname extends superclassname The child class inherits all the instance variables and methods of the parent class
  • 9. IBM Global Business Services © Copyright IBM Corporation 2009 Example: Inheriting classes Core Java | IBM Internal Use | Day 1 | 16-Jun-09 9 public class Person { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } } public class Employee extends Person { private String eid; public void setEid(String eid) { this.eid=eid; } public String getEid() { return eid; } } Parent Child The extends keyword indicates inheritance
  • 10. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 10 Types of inheritance 1. Single Level Inheritance Derives a subclass from a single superclass. Class Person Class Employee Class Student
  • 11. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 11 Types of inheritance (continued) Example 2. Multilevel Inheritance Inherits the properties of another subclass. Class Person Class Employee Class Regular
  • 12. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 12  Method overriding is defined as creating a non-static method in the subclass that has the same return type and signature as a method defined in the superclass. Overriding methods Signature of a method includes name number sequence type of arguments in a method
  • 13. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 13 Overriding methods (continued)  You can override (most) methods in a parent class by defining a method with the same name and parameter list in the child class.  This is useful for changing the behavior of a class without changing its interface.  You cannot override the static and final methods of a superclass.  A subclass must override the abstract methods of a superclass.
  • 14. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 14 Example: Overriding methods public class Person { private String name; private String ssn; public void setName(String name) { this.name = name; } public String getName() { return name; } public String getId() { return ssn; } } getId method is overridde n public class Employee extends Person { private String empId; public void setId(String empId) { this.empId=empId; } public String getId() { return empId; } }
  • 15. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 15 Example: Use of “super” keyword Allows you to access methods and properties of the parent class public class Person { private String name; public Person(String name) { this.name = name; } public String getName() { return name; } } public class Employee extends Person { private String empID; public Employee(String name) { super(name); // Calls Person constructor } public void setID(String empID){ this.empID=empID; } public String getID(){ return empID; } }
  • 16. IBM Global Business Services © Copyright IBM Corporation 2009 Restricting inheritance using final keyword Core Java | IBM Internal Use | Day 1 | 16-Jun-09 16 Parent Child Restricting Inherited capability Using modifier with a class will restrict the inheritance capability of that class final
  • 17. IBM Global Business Services © Copyright IBM Corporation 2009 Final classes: A way for preventing classes being extended  We can prevent an inheritance of classes by other classes by declaring them as final classes.  This is achieved in Java by using the keyword final as follows: – final class Regular – { // members – } – final class Employee extends Person – { // members – }  Any attempt to inherit these classes will cause an error. Core Java | IBM Internal Use | Day 1 | 16-Jun-09 17
  • 18. IBM Global Business Services © Copyright IBM Corporation 2009 Final members: A way for preventing overriding of members in subclasses  All methods and variables can be overridden by default in subclasses.  This can be prevented by declaring them as final using the keyword “final” as a modifier. For example: – final int marks = 100; – final void display();  This ensures that functionality defined in this method cannot be altered any. Similarly, the value of a final variable cannot be altered. Core Java | IBM Internal Use | Day 1 | 16-Jun-09 18
  • 19. IBM Global Business Services © Copyright IBM Corporation 2009 Understanding interfaces Core Java | IBM Internal Use | Day 1 | 16-Jun-09 19  A programmer’s tool for specifying certain behaviors that an object must have in order to be useful for some particular task.  Interface is a conceptual entity.  Can contain only constants (final variables) and non-implemented methods (Non – implemented methods are also known as abstract methods).
  • 20. IBM Global Business Services © Copyright IBM Corporation 2009 Example: Understanding interfaces  For example, you might specify Driver interface as part of a Vehicle object hierarchy. – A human can be a Driver, but so can a Robot. Core Java | IBM Internal Use | Day 1 | 16-Jun-09 20
  • 21. IBM Global Business Services © Copyright IBM Corporation 2009 Creating interfaces and methods Core Java | IBM Internal Use | Day 1 | 16-Jun-09 21 interface InterfaceName { // Constant/Final Variable Declaration // Methods Declaration – only method body } public interface Driver { void turnWheel (double angle); void pressBrake (double amount); } Syntax for Interface Declaration Example
  • 22. IBM Global Business Services © Copyright IBM Corporation 2009 Creating interfaces and methods (continued) Interface implementation  Interfaces are used like super-classes who properties are inherited by classes. This is achieved by creating a class that implements the give interface as follows: Core Java | IBM Internal Use | Day 1 | 16-Jun-09 22 public class BusDriver extends Person implements Driver { // include each of the two methods from Driver } class ClassName implements Interface1, Interface2,…., InterfaceN { // Body of Class } Syntax for Interface Implementation Example
  • 23. IBM Global Business Services © Copyright IBM Corporation 2009 Creating interfaces and methods (continued) Interface implementation Core Java | IBM Internal Use | Day 1 | 16-Jun-09 23 speak() Politician Priest <<Interface>> Speaker speak() speak() Lecturer speak()
  • 24. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 24 Inheriting interfaces  Like classes, interfaces can also be extended. The new sub-interface will inherit all the members of the super-interface in the manner similar to classes.  This is achieved by using the extends keyword. interface InterfaceName2 extends InterfaceName1 { // Body of InterfaceName2 }
  • 25. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 25 Understanding abstract class  An Abstract class is a conceptual class.  An Abstract class cannot be instantiated – objects cannot be created.  Abstract classes provides a common root for a group of classes, nicely tied together in a package.  When we define a class to be “final”, it cannot be extended. In certain situation, we want properties of classes to be always extended and used. Such classes are called Abstract Classes.
  • 26. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 26 Properties of an abstract class  A class with one or more abstract methods is automatically abstract and it cannot be instantiated.  A class declared abstract, even with no abstract methods can not be instantiated.  A subclass of an abstract class can be instantiated if it overrides all abstract methods by implementation them.  A subclass that does not implement all of the superclass abstract methods is itself abstract; and it cannot be instantiated.  We cannot declare abstract constructors or abstract static methods.
  • 27. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 27 Creating abstract classes and methods Shape Circle Rectangle
  • 28. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 28 Creating abstract classes and methods (continued) abstract class ClassName { ... … abstract DataType MethodName1(); … … DataType Method2() { // method body } } abstract public class Shape { public abstract double area(); public void move() { // non-abstract method // implementation } } Syntax Example
  • 29. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 29 public Circle extends Shape { private double r; private static final double PI =3.1415926535; public Circle() { r = 1.0; } public double area() { return PI * r * r; } … } public Rectangle extends Shape { private double l, b; public Rectangle() { l = 0.0; b=0.0; } public double area() { return l * b; } ... } Creating abstract classes and methods (continued)
  • 30. © Copyright IBM Corporation 2009 IBM Global Business Services Course Title Core Java Core Java | IBM Internal Use | Day 1 | 16-Jun-09 30 Day 2 Module 1: Classes in Java
  • 31. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 31 Module 1: Objectives After completion of this module, you should be able to:  Define Object class  Explain java.Util package and its different components including string class, date class, calendar class, and string buffer class  Understand how to use String classes  Understand how to convert objects to strings  Understand how to convert strings to numbers
  • 32. IBM Global Business Services © Copyright IBM Corporation 2009 Classes in Java: Agenda  Object class  Overview of java.util package Core Java | IBM Internal Use | Day 1 | 16-Jun-09 32
  • 33. IBM Global Business Services © Copyright IBM Corporation 2009 Object class  Every class that we create extends the class Object by default. That is the Object class is at the highest of the hierarchy. This facilitates to pass an object of any class to be passed as an argument to methods.  The methods in this class are: – equals(Object ref) - returns if both objects are equal – finalize( ) - method called when an object’s memory is destroyed – getClass( ) - returns class to which the object belongs – hashCode( )- returns the hashcode of the class – notify( ) - method to give message to a synchronized methods – notifyAll( ) - method to give message to all synchronized methods – toString() - return the string equivalent of the object name – wait() - suspends a thread for a while – wait(...) - suspends a thread for specified time in seconds – Core Java | IBM Internal Use | Day 1 | 16-Jun-09 33
  • 34. IBM Global Business Services © Copyright IBM Corporation 2009 Classes in Java: Agenda  Object class  Overview of java.util package Core Java | IBM Internal Use | Day 1 | 16-Jun-09 34
  • 35. IBM Global Business Services © Copyright IBM Corporation 2009 Overview of java.util package Core Java | IBM Internal Use | Day 1 | 16-Jun-09 35 Class Description Class Supports runtime processing of the class information of an object. String Provides functionality for String manipulation. Integer Provides methods to convert an Integer object to a String object. Math Provides functions for statistical, exponential operations.
  • 36. IBM Global Business Services © Copyright IBM Corporation 2009 Overview of java.util package (continued) Class Description Object All the classes in the java.lang package and classes belongs to other packages are the subclasses of the Object class. System It provides a standard interface to input output and error devices, such as Keyboard & VDU. Core Java | IBM Internal Use | Day 1 | 16-Jun-09 36  The java.lang package provides various classes and interfaces that are fundamental to Java programming.  The java.lang package contains various classes that represent primitive data types, such as int, char, long, and double.  Classes provided by the java.lang package:
  • 37. IBM Global Business Services © Copyright IBM Corporation 2009 String class Core Java | IBM Internal Use | Day 1 | 16-Jun-09 37 Method Name Description public int length() Returns the length of a String object. public String toUpperCase() Converts all the characters in the string object in uppercase. public String toLowerCase() Converts all the characters in the string object in lowercase. public String toString() Returns the String representation of the object.
  • 38. IBM Global Business Services © Copyright IBM Corporation 2009 String class (continued) Core Java | IBM Internal Use | Day 1 | 16-Jun-09 38 Method Name Description public boolean equals (Object ob) Compares two strings and return true, if both the strings are equal else return false. public int compareTo (String str2) Compares current String object with another String object. If the Strings are same the return value is 0 else the return value is non zero. If str1 > str2 then return value is a positive number If str1<str2 then return value is a negative number
  • 39. IBM Global Business Services © Copyright IBM Corporation 2009 String class (continued) Core Java | IBM Internal Use | Day 1 | 16-Jun-09 39 Method Name Description public int indexOf (String str) public int indexOf (String str, int startindex) searches for the first occurrence of a character or a substring in the invoking String and returns the position if found else return -1. public int lastIndexOf(String str) public int lastIndexOf(String str, int startindex) searches for the last occurrence of a character or a substring in the invoking String and returns the position if found else return -1.
  • 40. IBM Global Business Services © Copyright IBM Corporation 2009 String class (continued) Core Java | IBM Internal Use | Day 1 | 16-Jun-09 40 Method Name Description public String trim() Returns a copy of the string, with leading and trailing whitespace omitted. public char charAt( int index) Returns the char value at the specified index. public String concat(String str) Concatenates the specified String to the end of the String. public String subString(int startInd) public String subString(int startInd, int endInd) Returns a new String that is a substring of a String.
  • 41. IBM Global Business Services © Copyright IBM Corporation 2009 String class (continued) Core Java | IBM Internal Use | Day 1 | 16-Jun-09 41 Method Name Description public boolean startsWith(String prefix) Tests if the String starts with the specified prefix. public boolean endsWith(int suffix) Tests if the String end with the specified suffix. public char[] toCharArray() Converts this String to a new character array. public void getChars(int scrBegin,int srcEnd,char[] destination,int dstBegin) Copies characters from this string into the destination character array.
  • 42. IBM Global Business Services © Copyright IBM Corporation 2009 Overview of java.util package (continued)  The java.util package provides various utility classes and interfaces that support date and calendar operations, String manipulations and Collections manipulations. Classes provided by the java.util package Core Java | IBM Internal Use | Day 1 | 16-Jun-09 42 Class Description Date Encapsulates date and time information. Calendar Provides support for date conversion. GregorianCalendar It is a subclass of Calendar class, provides support for standard calendar used worldwide.
  • 43. IBM Global Business Services © Copyright IBM Corporation 2009 Date class Core Java | IBM Internal Use | Day 1 | 16-Jun-09 43 Date: Date class represent date and time. There are several constructors for Date objects. Constructors : Date() : produces the current date and time. Date(int year, int month, ind dayofmonth) Date(int year, int month, ind dayofmonth,int hours, int mins) Date(int year, int month, ind dayofmonth,int hours, int mins,int secs) Date(long milliseconds) : no of milliseconds from January 1, 1970 midnight Date(String strdate) : Converts the string representation of date into a Date object. Methods boolean after(Date pdate) - returns true if the current date is after pdate. boolean before(Date pdate) - returns true if the current date is before pdate. boolena eqauls(Date pdate) - returns true if the current date same as pdate. int getDay() int getMonth() int getYear() void setDay(int dayno) void setMonth(int monthno) void setYear(int year)
  • 44. IBM Global Business Services © Copyright IBM Corporation 2009 Date class (continued) Core Java | IBM Internal Use | Day 1 | 16-Jun-09 44 Example : Usage of Date class. SourceFile : datetest.java import java.io.*; import java.util.*; public class datetest{ public static void main(String args[]) { Date today = new Date(); System.out.println("Today's date is "+today.toString()); System.out.println("Current time is "+today.getTime()); Date aday = new Date(1998,10,9); Date bday = new Date(1998,11,10); Date cday = new Date(1998,9,23); Date tday = new Date(1998,9,23,12,20); System.out.println("A day is "+aday.toString()); System.out.println("B day is "+bday.toString()); System.out.println("C day is "+cday.toString()); System.out.println("T day with time is "+tday.toString()); if (aday.before(bday)) System.out.println(" a is before b"); if (cday.after(bday)) System.out.println(" c is after b"); System.out.println("Time of aday is "+aday.getTime()); System.out.println("Time of tday is "+tday.getTime()); Date today1 = new Date(); if (today1.equals(today)) System.out.println(" today is same as today1"); }
  • 45. IBM Global Business Services © Copyright IBM Corporation 2009 Calendar class Core Java | IBM Internal Use | Day 1 | 16-Jun-09 45 import java.util.Calendar; class CalendarDemo { public static void main(String args[]) { String months[]= {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; Calendar cal = Calendar.getInstance(); System.out.println("The Date is: "); System.out.print(months[cal.get(Calendar.MONTH)]); System.out.print(" " + cal.get(Calendar.DATE) + " "); System.out.println(cal.get(Calendar.YEAR)); // Setting Time cal.set(Calendar.HOUR, 10); cal.set(Calendar.MINUTE, 27); cal.set(Calendar.SECOND, 0); System.out.print("Time is: "); System.out.print(cal.get(Calendar.HOUR) + ":"); System.out.print(cal.get(Calendar.MINUTE) + ":"); System.out.print(cal.get(Calendar.SECOND)); } }
  • 46. IBM Global Business Services © Copyright IBM Corporation 2009 Calendar class (continued) Core Java | IBM Internal Use | Day 1 | 16-Jun-09 46 import java.util.*; public class GregorianCalendarDemo { public static void main(String args[]) { Calendar calendar = new GregorianCalendar(); System.out.println(calendar.get(Calendar.YEAR)); System.out.println(calendar.get(Calendar.MONTH+1)); System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); } }
  • 47. IBM Global Business Services © Copyright IBM Corporation 2009 StringBuffer Class  Class StringBuffer – Used for creating and manipulating dynamic string data  i.e., modifiable Strings – Can store characters based on capacity  Capacity expands dynamically to handle additional characters – CANNOT use operators + and += for string concatenation – Fewer utility methods (e.g. no substring, trim, ....) Core Java | IBM Internal Use | Day 1 | 16-Jun-09 47
  • 48. IBM Global Business Services © Copyright IBM Corporation 2009 StringBuffer Class (continued)  Three StringBuffer constructors – public StringBuffer();  empty content, initial capacity of 16 characters – public StringBuffer(int length);  empty content, initial capacity of length characters – public StringBuffer(String str);  contain the characters of str, capacity is the number of characters in str plus 16 – Use capacity() method to get the capacity. – If the internal buffer overflows, the capacity is automatically made larger. Core Java | IBM Internal Use | Day 1 | 16-Jun-09 48
  • 49. IBM Global Business Services © Copyright IBM Corporation 2009 StringBuffer Methods (continued)  Method length – Return StringBuffer length (the actual number of characters stored).  Method capacity – Return StringBuffer capacity (the number of characters can be stored without expansion)  Method setLength – Increase or decrease StringBuffer length. If the new length is less than the current length of the string buffer, the string buffer is truncated.  Method ensureCapacity – Set StringBuffer capacity – The new capacity is the larger of the minimumCapacity argument or twice the old capacity, plus 2. Core Java | IBM Internal Use | Day 1 | 16-Jun-09 49
  • 50. IBM Global Business Services © Copyright IBM Corporation 2009 Manipulating StringBuffer characters  Method charAt – Return StringBuffer character at specified index  Method setCharAt – Set StringBuffer character at specified index  Method reverse – Reverse StringBuffer contents Core Java | IBM Internal Use | Day 1 | 16-Jun-09 50
  • 51. IBM Global Business Services © Copyright IBM Corporation 2009 Core Java | IBM Internal Use | Day 1 | 16-Jun-09 51 StringBuffer Methods (continued)  Method append – Allow data-type values to be added to StringBuffer – Should NOT use + and += for StringBuffer – Overloaded methods to append primitive data type values, String, char array and the String representation of any Objects.  Method insert – Similar to append and can specify where to insert  Methods delete and deleteCharAt – Allow characters to be removed from StringBuffer – delete : delete a range of characters, from start to end-1 – deleteCharAt : delete a character at a specified location
  • 52. IBM Global Business Services © Copyright IBM Corporation 2009 StringBuffer class Core Java | IBM Internal Use | Day 1 | 16-Jun-09 52  public class StringBufferDemo { public static void main(String[] args) { StringBuffer sb =new StringBuffer("Hello"); System.out.println("buffer= " +sb); System.out.println("length= " +sb.length()); System.out.println("capacity= " +sb.capacity()); //appending and inserting into StringBuffer. String s; int a = 42; StringBuffer sb1= new StringBuffer(40); s= sb1.append("a=").append(a).append("!").toString(); System.out.println(s); StringBuffer sb2 = new StringBuffer("I JAVA!"); sb2.insert(2, "LIKE"); System.out.println(sb2); } }
  • 53. IBM Global Business Services © Copyright IBM Corporation 2009 Converting object to string Core Java | IBM Internal Use | Day 1 | 16-Jun-09 53  Any Java reference type or primitive that appears where a String is expected will be converted into a string. – System.out.println("1 + 2 = " + (1 + 2));  For an reference type (object) – this is done by inserting code to call String toString() on the reference. – All reference types inherit this method from java.lang.Object and override this method to produce a string that represents the data in a form suitable for printing.  To provide this service for Java's primitive types, the compiler must wrap the type in a so-called wrapper class, and call the wrapper class's toString method. – String arg1 = new Integer(1 + 2).toString();
  • 54. IBM Global Business Services © Copyright IBM Corporation 2009 Converting object to string (continued)  For user defined classes they will inherit the standard Object.toString() which produces something like "ClassName@123456" (where the number is the hashcode representation of the object).  To have something meaningful the classes have to provide a method with the signature public String toString(). public class Car() { ---- --- String toString() { return brand + ” : ” + color + ” : ”+wheels+” : “+ speed; } } Core Java | IBM Internal Use | Day 1 | 16-Jun-09 54
  • 55. IBM Global Business Services © Copyright IBM Corporation 2009 Converting string to numbers  Many data type wrapper classes provide the valueOf(String s) method which converts the given string into a numeric value.  The syntax is straightforward. It requires using the static Integer.valueOf(String s) and intValue() methods from the java.lang.Integer class.  To convert the String "22" into the int 22 you would write – int i = Integer.valueOf("22").intValue();  Doubles, floats and longs are converted similarly. To convert a String like "22" into the long value 22 you would write – long l = Long.valueOf("22").longValue();  To convert "22.5" into a float or a double you would write: – double x = Double.valueOf("22.5").doubleValue(); float y = Float.valueOf("22.5").floatValue();  If the passed value is non-numeric like “Four," it will throw a NumberFormatException. Core Java | IBM Internal Use | Day 1 | 16-Jun-09 55
  • 56. IBM Global Business Services © Copyright IBM Corporation 2009 Example: Converting string to numbers class Energy { public static void main (String args[]) { double c = 2.998E8; // meters/second double mass = Double.valueOf(args[0]).doubleValue(); double E = mass * c * c; System.out.println(E + " Joules"); } } Here's the output: $ javac Energy.java $ java Energy 0.0456 4.09853e+15 Joules Core Java | IBM Internal Use | Day 1 | 16-Jun-09 56
  • 57. IBM Global Business Services © Copyright IBM Corporation 2009 Regular expression  Regular expressions are a way to describe a set of strings based on common characteristics shared by each string in the set. They can be used to search, edit, or manipulate text and data.  The regular expression syntax supported by the java.util.regex API Core Java | IBM Internal Use | Day 1 | 16-Jun-09 57
  • 58. IBM Global Business Services © Copyright IBM Corporation 2009 Regular expression (continued)  The java.util.regex package primarily consists of three classes: Pattern, Matcher, and PatternSyntaxException.  A Pattern object is a compiled representation of a regular expression.  The Pattern class provides no public constructors. – To create a pattern, you must first invoke one of its public static compile methods, which will then return a Pattern object. – These methods accept a regular expression as the first argument; the first few lessons of this trail will teach you the required syntax.  A Matcher object is the engine that interprets the pattern and performs match operations against an input string. – Like the Pattern class, Matcher defines no public constructors. You obtain a Matcher object by invoking the matcher method on a Pattern object.  A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern. Core Java | IBM Internal Use | Day 1 | 16-Jun-09 58
  • 59. IBM Global Business Services © Copyright IBM Corporation 2009 Regular expression (continued) Core Java | IBM Internal Use | Day 1 | 16-Jun-09 59 import java.io.Console; import java.util.regex.Pattern; import java.util.regex.Matcher; public class RegexTestHarness { public static void main(String[] args){ Console console = System.console(); if (console == null) { System.err.println("No console."); System.exit(1); }
  • 60. IBM Global Business Services © Copyright IBM Corporation 2009 Regular expression (continued) Core Java | IBM Internal Use | Day 1 | 16-Jun-09 60 while (true) { Pattern pattern = Pattern.compile(console.readLine("%nEnter your regex: ")); Matcher matcher = pattern.matcher(console.readLine("Enter input string to search: ")); boolean found = false; while (matcher.find()) { console.format("I found the text "%s" starting at " + "index %d and ending at index %d.%n", matcher.group(), matcher.start(), matcher.end()); found = true; } if(!found){ console.format("No match found.%n"); } } } } Compile the REGEX pattern Get matcher from static method on Pattern class Seed the matcher with the string that you want to find matches Find parts of the string that match the REGEXP Find the group ofchars that matched (as a String) and where those chars started and ended in the string to be matched
  • 61. IBM Global Business Services © Copyright IBM Corporation 2009 Regular expression (continued)  Character classes – Enter your regex: [bcr]at – Enter input string to search: bat – I found the text "bat" starting at index 0 and ending at index 3.  Negation and Ranges – Enter your regex: [^bcr]at – Enter input string to search: cat – No match found. – Enter your regex: [a-c] – Enter input string to search: a – I found the text "a" starting at index 0 and ending at index 1. Core Java | IBM Internal Use | Day 1 | 16-Jun-09 61
  • 62. IBM Global Business Services © Copyright IBM Corporation 2009 Regular expression: Predefined character classes Any character (may or may not match the terminators  d A digit: [0-9]  D A non-digit: [^0-9]  s A whitespace character: [ tnx0Bfr]  S A non-whitespace character: [^s]  w A word character: [a-zA-Z_0-9]  W A non-word character: [^w] Core Java | IBM Internal Use | Day 1 | 16-Jun-09 62
  • 63. IBM Global Business Services © Copyright IBM Corporation 2009 Regular expression: Matcher methods  A matcher is created from a pattern by invoking the pattern's matcher method. Once created, a matcher can be used to perform three different kinds of match operations: – The matches method attempts to match the entire input sequence against the pattern. – The looking at method attempts to match the input sequence, starting at the beginning, against the pattern. – The find method scans the input sequence looking for the next subsequence that matches the pattern Core Java | IBM Internal Use | Day 1 | 16-Jun-09 63
  • 64. IBM Global Business Services © Copyright IBM Corporation 2009 Rational Tools Overview | IBM Internal Use | Document ID | 8 June 2009 64 Questions
  • 65. IBM Global Business Services © Copyright IBM Corporation 2009 Day 2 Summary At the end of Day 2, we see that you are now able to:  Define inheritance and polymorphism  Identify the classes in Java Core Java | IBM Internal Use | Day 1 | 16-Jun-09 65

Editor's Notes

  1. © Copyright IBM Corporation 2006
  2. © Copyright IBM Corporation 2006
  3. © Copyright IBM Corporation 2006
  4. © Copyright IBM Corporation 2006
  5. © Copyright IBM Corporation 2006
  6. © Copyright IBM Corporation 2006
  7. © Copyright IBM Corporation 2006
  8. © Copyright IBM Corporation 2006
  9. © Copyright IBM Corporation 2006
  10. © Copyright IBM Corporation 2006
  11. © Copyright IBM Corporation 2006
  12. © Copyright IBM Corporation 2006
  13. © Copyright IBM Corporation 2006
  14. © Copyright IBM Corporation 2006
  15. © Copyright IBM Corporation 2006
  16. © Copyright IBM Corporation 2006
  17. © Copyright IBM Corporation 2006
  18. © Copyright IBM Corporation 2006
  19. © Copyright IBM Corporation 2006
  20. Note to GA
  21. Note to GA
  22. java.lang package is the default package and not needed to be imported when using any of the classes and interfaces from the java.lang package. Like, when using System class, you don’t import java.lang package, by default it is imported.
  23. © Copyright IBM Corporation 2006
  24. No value is assigned that’s why array arr store the default value of int i.e. 0.
  25. Urge the class to ask questions