Saturday, February 14, 2009
Table Of Contents-start here
1. Introduction
2. Start studying Java
3. Java Basic Elements
4. Java Operators
5. Control Flow Statements
Now its easy to earn money online, click to know how!!
6. Classes, Objects
7. Access Modifiers
8. Class Constructors
9. Inheritance
10.Abstract classes
11. Interfaces
12.Object typecasting
Now its easy to earn money online, click to know how!!
13.Method Overriding
14.Java Strings
15.String Buffers
16.Exceptions
17.A sample program
Now its easy to earn money online, click to know how!!
One program using all the knowledge!!!!!!
java.util.
Class Date
java.lang.Object
extended by java.util.Date
All Implemented Interfaces:
Cloneable, Comparable, Serializable
Direct Known Subclasses:
Date, Time, Timestamp
public class Date extends Object
implements Serializable, Cloneable, Comparable
The class Date represents a specific instant in time, with millisecond precision.
Java Date Source Code
import java.text.DateFormat;
|
Output
1. Add to a Date Operation
c1.getTime() : Sat Mar 31 10:47:54 IST 2007
c1.get(Calendar.YEAR): 2007
Todays date in Date Format : Sat Mar 31 10:47:54 IST 2007
c1.set(1999,0 ,20) : Wed Jan 20 10:47:54 IST 1999
Date + 20 days is : 09-02-1999
——————————————————-
2. Subtract to a date Operation
Date is : 20-01-1999
Date roll down 1 month : 20-12-1999
Date is : 20-01-1999
Date minus 1 month : 20-12-1998
——————————————————-
3. No of Days between 2 dates
Days Between Wed Jan 20 10:47:54 IST 1999 and Fri Jan 22 10:47:54 IST 1999 is
2
——————————————————-
4. No of Days in a month for a given date
Days in 6th month for year 1999 is 31
——————————————————-
5. Validate a given date
Unparseable date: “20031315″
——————————————————-
6. Comparision of 2 dates
15-03-2000 is less than 15-03-2001
——————————————————-
7. Get the day for a given date
The day for Sat Mar 31 10:47:54 IST 2007 is Saturday
Java Exceptions
Exceptions in java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime. They could be file not found exception, unable to get connection exception and so on. On such conditions java throws an exception object. Java Exceptions are basically Java objects. No Project can never escape a java error exception. Java exception handling is used to handle error conditions in a program systematically by taking the necessary action. Exception handlers can be written to catch a specific exception such as Number Format exception, or an entire group of exceptions by using a generic exception handlers. Any exceptions not specifically handled within a Java program are caught by the Java run time environment
An exception is a subclass of the Exception/Error class, both of which are subclasses of the Throwable class. Java exceptions are raised with the throw keyword and handled within a catch block.
A Program Showing How the JVM throws an Exception at runtime
public static void division(int totalSum, int totalNumber) {
|
An ArithmeticException is thrown at runtime when Line 11 is executed because integer division by 0 is an illegal operation. The “Exit main()” message is never reached in the main method
Output
Computing Division.
java.lang.ArithmeticException: / by zero
Average : 25
Computing Division.
at DivideException.division(DivideException.java:11)
at DivideException.main(DivideException.java:5)
Exception in thread “main”
Exceptions in Java
Throwable Class
The Throwable class provides a String variable that can be set by the subclasses to provide a detail message that provides more information of the exception occurred. All classes of throwables define a one-parameter constructor that takes a string as the detail message.
The class Throwable provides getMessage() function to retrieve an exception. It has a printStackTrace() method to print the stack trace to the standard error stream. Lastly It also has a toString() method to print a short description of the exception. For more information on what is printed when the following messages are invoked, please refer the java docs.
Syntax
String getMessage()
void printStackTrace()
String toString()
Class Exception
The class Exception represents exceptions that a program faces due to abnormal or special conditions during execution. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run time Exceptions).
Class RuntimeException
Runtime exceptions represent programming errors that manifest at runtime. For example ArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of the java.lang.RuntimeException class, which is a subclass of the Exception class. These are basically business logic programming errors.
Class Error
Errors are irrecoverable condtions that can never be caught. Example: Memory leak, LinkageError etc. Errors are direct subclass of Throwable class.
Checked and Unchecked Exceptions
Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses. Checked Exceptions forces programmers to deal with the exception that may be thrown. Example: Arithmetic exception. When a checked exception occurs in a method, the method must either catch the exception and take the appropriate action, or pass the exception on to its caller
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. Unchecked exceptions , however, the compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBounds Exception. They are either irrecoverable (Errors) and the program should not attempt to deal with them, or they are logical programming errors. (Runtime Exceptions). Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
Exception Statement Syntax
Exceptions are handled using a try-catch-finally construct, which has the Syntax
try {
} catch (
}
} finally { // finally block
}
try Block
The java code that you think may produce an exception is placed within a try block for a
suitable catch block to handle the error.
If no exception occurs the execution proceeds with the finally block else it will look for the
matching catch block to handle the error. Again if the matching catch handler is not found execution
proceeds with the finally block and the default exception handler throws an exception.. If an exception is
generated within the try block, the remaining statements in the try block are not executed.
catch Block
Exceptions thrown during execution of the try block can be caught and handled in a catch block. On exit from a catch block, normal execution continues and the finally block is executed
(Though the catch block throws an exception).
finally Block
A finally block is always executed, regardless of the cause of exit from the try block, or whether any catch block was executed. Generally finally block is used for freeing resources, cleaning up, closing connections etc. If the finally clock executes a control transfer statement such as a return or a break statement, then this control
statement determines how the execution will proceed regardless of any return or control statement present in the try or catch.
The following program illustrates the scenario.
try { |
Output
Computing Division.
Exception : / by zero
Finally Block Executes. Exception Occurred
result : -1
Below is a program showing the Normal Execution of the Program.
Please note that no NullPointerException is generated as was expected by most people
public class DivideException2 { |
Output
null (And not NullPointerException)
Rules for try, catch and finally Blocks
1. For each try block there can be zero or more catch blocks, but only one finally block. |
Java exception handling mechanism enables you to catch exceptions in java using try, catch, finally block. be An exception consists of a block of code called a try block, a block of code called a catch block, and the finally block. Let’s examine each of these in detail.
public class DivideException1 { |
Output
Computing Division.
Exception : / by zero
Finally Block Executes. Exception Occurred
Main Program Terminating
As shown above when the divide by zero calculation is attempted, an ArithmeticException is thrown. and program execution is transferred to the catch statement. Because the exception is thrown from the try block, the remaining statements of the try block
are skipped. The finally block executes.
Defining new EXCEPTIONS!!
We can have our own custom Exception handler to deal with special exception conditions instead of using existing exception classes. Custom exceptions usually extend the Exception class directly or any subclass of Exception (making it checked).
The super() call can be used to set a detail message in the throwable. Below is an example that shows the use of Custom exception’s along with how the throw and throws clause are used.
class BadTemperature extends Exception{ |
Output
Very Hot
Very Cold
Perfect Temperature
throw, throws statement
A program can explicitly throw an exception using the throw statement besides the implicit exception thrown.
The general format of the throw statement is as follows:
throw
The Exception reference must be of type Throwable class or one of its subclasses. A detail message can be passed to the constructor when the exception object is created.
throw new TemperatureException(”Too hot”);
A throws clause can be used in the method prototype.
Method() throws
}
Each
When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a matching catch block that can handle the exception. Any associated finally block of a try block encountered along the search path is executed. If no handler is found, then the exception is dealt with by the default exception handler at the top level. If a handler is found, execution resumes with the code in its catch block. Below is an example to show the use of a throws and a throw statement.
public class DivideException3 { |
Output
Computing Division.
Finally Block Executes
Result : 10
Computing Division.
Finally Block Executes. Exception Occurred
Exception : Division attempt by 0
Using break and return with Exceptions
This example demonstrates the use of the break, continue and return statements with exceptions. Note that the finally block is executed always except when the return statement is executed.
public class ExceptionExample6 { |
Output
Counter : 1
x : 10 y : 1
Counter : 2
/ by zero
Counter : 3
Counter : 4
Handling Multiple Exceptions
It should be known by now that we can have multiple catch blocks for a particular try block to handle many different kind of exceptions that can be generated. Below is a program to demonstrate the use of multiple catch blocks.
import java.io.DataInputStream; |
Java String Buffer
StringBuffer Class
StringBuffer class is a mutable class unlike the String class which is immutable. Both the capacity and character string of a StringBuffer Class. StringBuffer can be changed dynamically. String buffers are preferred when heavy modification of character strings is involved (appending, inserting, deleting, modifying etc). Strings can be obtained from string buffers. Since the StringBuffer class does not override the equals() method from the Object class, contents of string buffers should be converted to String objects for string comparison.
A StringIndexOutOfBoundsException is thrown if an index is not valid when using wrong index in String Buffer manipulations
Creation of StringBuffers
StringBuffer Constructors
public class StringBufferDemo { |
Output
strBuf1 : Bob
strBuf2 capacity : 100
strBuf3 capacity : 16
StringBuffer Functions
The following program explains the usage of the some of the basic StringBuffer methods like ;
1. capacity()
Returns the current capacity of the String buffer.
2. length()
Returns the length (character count) of this string buffer.
3. charAt(int index)
The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.
4. setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to ch
5. toString()
Converts to a string representing the data in this string buffer
6. insert(int offset, char c)
Inserts the string representation of the char argument into this string buffer.
Note that the StringBuffer class has got many overloaded ‘insert’ methods which can be used based on the application need.
7. delete(int start, int end)
Removes the characters in a substring of this StringBuffer
8. replace(int start, int end, String str)
Replaces the characters in a substring of this StringBuffer with characters in the specified String.
9. reverse()
The character sequence contained in this string buffer is replaced by the reverse of the sequence.
10. append(String str)
Appends the string to this string buffer.
Note that the StringBuffer class has got many overloaded ‘append’ methods which can be used based on the application need.
11. setLength(int newLength)
Sets the length of this String buffer.
public class StringBufferFunctionsDemo { |
Output
strBuf1 : Bobby
strBuf1 capacity : 21
strBuf2 capacity : 100
strBuf3 capacity : 16
strBuf1 length : 5
strBuf1 charAt 2 : b
strBuf1 after setCharAt 1 to t is : Btbby
strBuf1 toString() is : Btbby
strBuf3 when appended with a String : beginner-java-tutorial
strBuf3 when c is inserted at 1 : bceginner-java-tutorial
strBuf3 when c is deleted at 1 : b
Reversed strBuf3 : b
strBuf2 :
Java Strings
Strings in java
Java String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on the same reference. A java.lang.String class is final which implies no class and extend it. The java.lang.String class differs from other classes, one difference being that the String objects can be used with the += and + operators for concatenation. Two useful methods for String objects are equals( ) and substring( ). The equals( ) method is used for testing whether two Strings contain the same value. The substring( ) method is used to obtain a selected portion of a String.
Java.lang.String class creation
A simple String can be created using a string literal enclosed inside double quotes as shown;
String str1 = “My name is bob”;
Since a string literal is a reference, it can be manipulated like any other String reference. The reference value of a string literal can be assigned to another String reference.
If 2 or more Strings have the same set of characters in the same sequence then they share the same reference in memory. Below illustrates this phenomenon.
String str1 = “My name is bob”;
String str2 = “My name is bob”;
String str3 = “My name ”+ “is bob”; //Compile time expression
String name = “bob”;
String str4 = “My name is” + name;
String str5 = new String(“My name is bob”);
Constructing String objects can also be done from arrays of bytes, arrays of characters, or string buffers. A simple way to convert any primitive value to its string representation is by concatenating it with the empty string (”"), using the string concatenation operator (+).
public class StringsDemo {Earn money online, click here Strings in javaJava String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on the same reference. A java.lang.String class is final which implies no class and extend it. The java.lang.String class differs from other classes, one difference being that the String objects can be used with the += and + operators for concatenation. Two useful methods for String objects are equals( ) and substring( ). The equals( ) method is used for testing whether two Strings contain the same value. The substring( ) method is used to obtain a selected portion of a String. Java.lang.String class creationA simple String can be created using a string literal enclosed inside double quotes as shown; String str1 = “My name is bob”; Since a string literal is a reference, it can be manipulated like any other String reference. The reference value of a string literal can be assigned to another String reference. If 2 or more Strings have the same set of characters in the same sequence then they share the same reference in memory. Below illustrates this phenomenon. String str1 = “My name is bob”; In the above code all the String references str1, str2 and str3 denote the same String object, initialized with the character string: “My name is bob”. But the Strings str4 and str5 denote new String objects. Constructing String objects can also be done from arrays of bytes, arrays of characters, or string buffers. A simple way to convert any primitive value to its string representation is by concatenating it with the empty string (”"), using the string concatenation operator (+).
Output byteStr : String Equality
Output str1 == str2 : true Java String FunctionsThe following program explains the usage of the some of the basic String methods like ; 1. compareTo(String anotherString) 2. charAt(int index) 3. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 4. length() 5. equals(Object anObject) 6. equalsIgnoreCase(String anotherString) 7. toUpperCase() 7. toLowerCase() Converts all of the characters in this String to upper case using the rules of the default locale. 9. concat(String str) 10. indexOf(int ch) Returns the index within this string of the first occurrence of the specified character. 11. indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. 12. indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. 13. indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. 14. lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character. 15. lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index. 16. lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of the specified substring. 17. lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index. 18. substring(int beginIndex) Returns a new string that is a substring of this string. 19. substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string. 20. replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. 21. trim() Returns a copy of the string, with leading and trailing whitespace omitted. 22. toString() This object (which is already a string!) is itself returned.
Output Length of the String str1 : 14 Character at position 3 is : n The String str2 is : My name is bob Comparision Test : bob < cob Equals Teststr3.equalsIgnoreCase(5) : true str3.equals(6) : true str1.equals(3) : false str5 : BoB str5 Uppercase: BOB str1 Lowercase: My name is bob str1.concat(str4): My name is bobcob str7 : Now for some Search and Replace Examples newStr : Now for Tome Search and Replace ExampleT Indexof Operations on Strings Index of p in Now for some Search and Replace Examples : 26 Index of for in Now for some Search and Replace Examples : 4 Below is a program to check for Alpha Numeric character’s in the string.
Output characters are present:true Below is a java program to Reverse a string (Reverse by words / characters)
Output Original String: beginner java tutorial |
Output
byteStr :
charStr : abCD
buffStr : abcde
String Equality
public class StringsDemo2 { |
Output
str1 == str2 : true
str2 == str3 : true
str3 == str1 : true
str4 == str5 : false
str1 == str4 : false
str1 == str5 : false
str1.equals(str2) : true
str2.equals(str3) : true
str3.equals(str1) : true
str4.equals(str5) : true
str1.equals(str4) : true
str1.equals(str5) : true
Java String Functions
The following program explains the usage of the some of the basic String methods like ;
1. compareTo(String anotherString)
Compares two strings lexicographically.
2. charAt(int index)
Returns the character at the specified index.
3. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
4. length()
Returns the length of this string.
5. equals(Object anObject)
Compares this string to the specified object.
6. equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
7. toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
7. toLowerCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
9. concat(String str)
Concatenates the specified string to the end of this string.
10. indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
11. indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
12. indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
13. indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
14. lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
15. lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
16. lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
17. lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
18. substring(int beginIndex)
Returns a new string that is a substring of this string.
19. substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
20. replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
21. trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
22. toString()
This object (which is already a string!) is itself returned.
public class StringsDemo3 { |
Output
Length of the String str1 : 14
Character at position 3 is : n
The String str2 is : My name is bob
Comparision Test : bob < cob
Equals Teststr3.equalsIgnoreCase(5) : true
str3.equals(6) : true
str1.equals(3) : false
str5 : BoB
str5 Uppercase: BOB
str1 Lowercase: My name is bob
str1.concat(str4): My name is bobcob
str7 : Now for some Search and Replace Examples
newStr : Now for Tome Search and Replace ExampleT
Indexof Operations on Strings
Index of p in Now for some Search and Replace Examples : 26
Index of for in Now for some Search and Replace Examples : 4
str7.indexOf(for, 30) : -1
str7.indexOf(’p', 30) : 36
str7.lastIndexOf(’p') : 36
str7.lastIndexOf(’p', 4) : -1
SubString Operations on Stringsstr8 : SubString Example
str8.substring(5) : ring Example
str8.substring(3,6) : Str
Below is a program to check for Alpha Numeric character’s in the string.
public class TestAlphaNumericCharacters { |
Output
characters are present:true
Numbers are present :true
Below is a java program to Reverse a string (Reverse by words / characters)
import java.util.*; |
Output
Original String: beginner java tutorial
Reversed String by Words: tutorial java beginner
Reversed String by characters: lairotut avaj rennigeb
Method Overriding in Java
A program to explain the different concepts of Java Method Overridding
class CustomException extends Exception {
}
class SuperClassWithDifferentMethods {
protected int field1 = 10;
protected static int field2 = 20;
public void method1() {
System.out.println("SuperClassWithDifferentMethods.method1()");
}
public final void method2() {
System.out.println("SuperClassWithDifferentMethods.method2()");
}
private void method3() {
System.out.println("SuperClassWithDifferentMethods.method3()");
}
private final void method4() {
System.out.println(”SuperClassWithDifferentMethods.method4()”);
}
public static void method5() {
System.out.println(”SuperClassWithDifferentMethods.method5()”);
}
public void method6() throws Exception {
System.out.println(”SuperClassWithDifferentMethods.method6()”);
}
private void method7() {
System.out.println(”SuperClassWithDifferentMethods.method7()”);
}
private void method8(int x) {
System.out.println(”SuperClassWithDifferentMethods.method8()”);
}
public static void method9() {
System.out.println(”SuperClassWithDifferentMethods.method9()”);
}
}
class OverridingClass extends SuperClassWithDifferentMethods {
public int field1 = 30;
public static int field2 = 40;
public void method1() {
System.out.println(”OverridingClass.method1()”);
}
//We can’t override a public final method
/* public final void method2(){
System.out.println(”OverridingClass.method2()”);
}*/
private void method3() {
System.out.println(”OverridingClass.method3()”);
}
private final void method4() {
System.out.println(”OverridingClass.method4()”);
}
public static void method5() {
System.out.println(”OverridingClass.method5()”);
}
public void method6() throws CustomException {
System.out.println(”OverridingClass.method6()”);
}
public void method7() {
System.out.println(”OverridingClass.method7()”);
}
public void method8(final int x) {
System.out.println(”OverridingClass.method8()”);
}
//A static method cannot be overridden to be non-static instance method
/*public void method9() {
System.out.println(”OverridingClass.method9()”);
}*/
}
public class MethodOverridingDemo {
public static void main(String[] args) {
OverridingClass oc1 = new OverridingClass();
SuperClassWithDifferentMethods sc3 = new OverridingClass();
oc1.method1();
oc1.method2();
// Since its private, the below 2 methods are not visible
/* oc1.method3();
oc1.method4();*/
oc1.method5();
try {
oc1.method6();
} catch (CustomException e) {
e.printStackTrace();
}
oc1.method7();
oc1.method8(100);
System.out.println(”oc1.field1 : ” + oc1.field1);
System.out.println(”oc1.field2 : ” + oc1.field2);
System.out.println(”sc3.field1 : ” + sc3.field1);
System.out.println(”sc3.field2 : ” + sc3.field2);
sc3.method5();
OverridingClass overClass = new OverridingClass();
SuperClassWithDifferentMethods supClass = (SuperClassWithDifferentMethods) overClass;
supClass.method5();
supClass.method1();
}
}
Output
OverridingClass.method1()
SuperClassWithDifferentMethods.method2()
OverridingClass.method5()
OverridingClass.method6()
OverridingClass.method7()
OverridingClass.method8()
oc1.field1 : 30
oc1.field2 : 40
sc3.field1 : 10
sc3.field2 : 20
SuperClassWithDifferentMethods.method5()
SuperClassWithDifferentMethods.method5()
OverridingClass.method1()
Download MethodOverridingDemo.java
The new method definitions in the subclass OverridingClass have the same signature and the same return type as the methods in the superclass SuperClassWithDifferentMethods. The new overridden method6 definition specifies a subset of the exceptions (CustomException). The new overridden method7 definition also widens the accessibility to public from private. The overriding method8 also declares the parameter to be final, which is not a part of the method signature and Method Overriding holds good. A static method cannot be overridden to be non-static instance method as shown in the overridden method declaration of method9. A static method is class-specific and not part of any object, while overriding methods are invoked on behalf of objects of the subclass. There are no such restrictions on the fields, as for fields only the field names matter. A final method cannot be overridden, an attempt to which will result in a compile-time error. A private method is not accessible outside the class in which it is defined; therefore, a subclass cannot override it.
A subclass must use the ‘super’ keyword in order to invoke an overridden method in the superclass. A subclass cannot override fields of the superclass, but it can hide them. Code in the subclass can use the keyword super to access members, including hidden fields.
The following distinction between invoking instance methods on an object and accessing fields of an object must be noted. When an instance method is invoked on an object using a reference, it is the class of the current object denoted by the reference, not the type of the reference, that determines which method implementation will be executed. When a field of an object is accessed using a reference, it is the type of the reference, not the class of the current object denoted by the reference, that determines which field will actually be accessed. This is demonstrated in the above program.
Object typecasting
Object Reference Type Casting
In java object typecasting one object reference can be type cast into another object reference. The cast can be to its own class type or to one of its subclass or superclass types or interfaces. There are compile-time rules and runtime rules for casting in java.
How to Typecast Objects with a dynamically loaded Class ? - The casting of object references depends on the relationship of the classes involved in the same hierarchy. Any object reference can be assigned to a reference variable of the type Object, because the Object class is a superclass of every Java class.
There can be 2 casting java scenarios
· Upcasting
· Downcasting
When we cast a reference along the class hierarchy in a direction from the root class towards the children or subclasses, it is a downcast. When we cast a reference along the class hierarchy in a direction from the sub classes towards the root, it is an upcast. We need not use a cast operator in this case.
The compile-time rules are there to catch attempted casts in cases that are simply not possible. This happens when we try to attempt casts on objects that are totally unrelated (that is not subclass super class relationship or a class-interface relationship) At runtime a ClassCastException is thrown if the object being cast is not compatible with the new type it is being cast to.
Below is an example showing when a ClassCastException can occur during object casting
//X is a supper class of Y and Z which are sibblings. |
Casting Object References: Implicit Casting using a Compiler
In general an implicit cast is done when an Object reference is assigned (cast) to:
* A reference variable whose type is the same as the class from which the object was instantiated.
An Object as Object is a super class of every Class.
* A reference variable whose type is a super class of the class from which the object was instantiated.
* A reference variable whose type is an interface that is implemented by the class from which the object was instantiated.
* A reference variable whose type is an interface that is implemented by a super class of the class from which the object was instantiated.
Consider an interface Vehicle, a super class Car and its subclass Ford. The following example shows the automatic conversion of object references handled by the compiler
| interface Vehicle { } class Car implements Vehicle { } Want to earn money online, click here class Ford extends Car { |
Let c be a variable of type Car class and f be of class Ford and v be an vehicle interface reference. We can assign the Ford reference to the Car variable:
I.e. we can do the following
Example 1
c = f; //Ok Compiles fine
Where c = new Car();
And, f = new Ford();
The compiler automatically handles the conversion (assignment) since the types are compatible (sub class - super class relationship), i.e., the type Car can hold the type Ford since a Ford is a Car.
Example 2
v = c; //Ok Compiles fine
c = v; // illegal conversion from interface type to class type results in compilation error
Where c = new Car();
And v is a Vehicle interface reference (Vehicle v)
The compiler automatically handles the conversion (assignment) since the types are compatible (class – interface relationship), i.e., the type Car can be cast to Vehicle interface type since Car implements Vehicle Interface. (Car is a Vehicle).
Casting Object References: Explicit Casting
Sometimes we do an explicit cast in java when implicit casts don’t work or are not helpful for a particular scenario. The explicit cast is nothing but the name of the new “type” inside a pair of matched parentheses. As before, we consider the same Car and Ford Class
| class Car { void carMethod(){ } } Want to earn money online, click here class Ford extends Car { |
We also have a breakingSystem() function which takes Car reference (Superclass reference) as an input parameter.
The method will invoke carMethod() regardless of the type of object (Car or Ford Reference) and if it is a Ford object, it will also invoke fordMethod(). We use the instanceof operator to determine the type of object at run time.
| public void breakingSystem (Car obj) { obj.carMethod(); if (obj instanceof Ford) Want to earn money online, click here ((Ford)obj).fordMethod (); |
To invoke the fordMethod(), the operation (Ford)obj tells the compiler to treat the Car object referenced by obj as if it is a Ford object. Without the cast, the compiler will give an error message indicating that fordMethod() cannot be found in the Car definition.
The following program shown illustrates the use of the cast operator with references.
Note: Classes Honda and Ford are Siblings in the class Hierarchy. Both these classes are subclasses of Class Car. Both Car and HeavyVehicle Class extend Object Class. Any class that does not explicitly extend some other class will automatically extends the Object by default. This code instantiates an object of the class Ford and assigns the object’s reference to a reference variable of type Car. This assignment is allowed as Car is a superclass of Ford. In order to use a reference of a class type to invoke a method, the method must be defined at or above that class in the class hierarchy. Hence an object of Class Car cannot invoke a method present in Class Ford, since the method fordMethod is not present in Class Car or any of its superclasses. Hence this problem can be colved by a simple downcast by casting the Car object reference to the Ford Class Object reference as done in the program. Also an attempt to cast an object reference to its Sibling Object reference produces a ClassCastException at runtime, although compilation happens without any error.
|
One common casting that is performed when dealing with collections is, you can cast an object reference into a String.
import java.util.Vector; |
Output
Username : asdf
Username : asdf
Password : qwer
instanceof Operator
The instanceof operator is called the type comparison operator, lets you determine if an object belongs to a specific class, or implements a specific interface. It returns true if an object is an instance of the class or if the object implements the interface, otherwise it returns false.
Below is an example showing the use of instanceof operator
class Vehicle { |
Output
hV is an HeavyVehicle: true
T is an HeavyVehicle: true
hV is a Truck: false
hv2 is an HeavyVehicle: false