Abstract Class in Java
Abstract Class in Java
Abstract Class in Java
Java is a simple and yet powerful object oriented programming language and it is in many respects
similar to C++. Java originated at Sun Microsystems, Inc. in 1991. It was conceived by James
Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. It
was developed to provide a platform-independent programming language. This site gives you
an Introduction to Java Programming accompanied with many java examples. Its a complete
course in java programming for beginners to advanced java.
Platform independent
Unlike many other programming languages including C and C++ when Java is compiled, it is not
compiled into platform specific machine, rather into platform independent byte code. This byte code is
distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being
run.
Java was designed with a concept of ‘write once and run everywhere’. Java Virtual Machine plays the
central role in this concept. The JVM is the environment in which Java programs execute. It is a
software that is implemented on top of real hardware and operating system. When the source code
(.java files) is compiled, it is translated into byte codes and then placed into (.class) files. The JVM
executes these bytecodes. So Java byte codes can be thought of as the machine language of the JVM.
A JVM can either interpret the bytecode one instruction at a time or the bytecode can be compiled
further for the real microprocessor using what is called ajust-in-time compiler. The JVM must be
implemented on a particular platform before compiled programs can run on that platform.
• Reusability of Code
• New data and functions can be easily addedJava has powerful features. The following are
some of them:-
Simple
Reusable
Portable (Platform Independent)
Distributed
Robust
Secure
High Performance
Dynamic
Threaded
Interpreted
OOP Concepts
Abstraction
Abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of
objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the
viewer.
Encapsulation
Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its
structure and behavior ; encapsulation serves to separate the contractual interface of an abstraction
and its implementation.
Encapsulation
Inheritance
Inheritance is the process by which one object acquires the properties of another object.
Polymorphism
Polymorphism is the existence of the classes or methods in different forms or single name denoting
different
implementations.
Java is Distributed
With extensive set of routines to handle TCP/IP protocols like HTTP and FTP java can open and access
the objects across net via URLs.
Java is Multithreaded
One of the powerful aspects of the Java language is that it allows multiple threads of execution to run
concurrently within the same program A single Java program can have many different threads
executing independently and continuously. Multiple Java applets can run on the browser at the same
time sharing the CPU time.
Java is Secure
Java was designed to allow secure execution of code across network. To make Java secure many of
the features of C and C++ were eliminated. Java does not use Pointers. Java programs cannot access
arbitrary addresses in memory.
Garbage collection
Automatic garbage collection is another great feature of Java with which it prevents inadvertent
corruption of memory. Similar to C++, Java has a new operator to allocate memory on the heap for a
new object. But it does not use delete operator to free the memory as it is done in C++ to free the
memory if the object is no longer needed. It is done automatically with garbage collector.
Java Applications
Java has evolved from a simple language providing interactive dynamic content for web pages to a
predominant enterprise-enabled programming language suitable for developing significant and critical
applications. Today, It is used for many types of applications including Web based applications,
Financial applications, Gaming applications, embedded systems, Distributed enterprise applications,
mobile applications, Image processors, desktop applications and many more. This site outlines the
building blocks of java by stating few java examples along with some java tutorials.
Getting Java Basics quickly has become easy with Javabeginner.com. This site is for the java
programmers who want to use the Java programming language to create applications using the Java
basics. This site is for absolute beginners to advanced java programmers who do not require any
prerequisite Java knowledge. For getting started with Java you’ll have to have some basic
understanding of the concepts of programming.
After going through all the tutorials in this site, you would have learnt the essential concepts and
features of the Java Programming Language which include exceptions, Swing GUI programming,
Collections framework etc. A lot of code examples are used through out tutorial to make you
understand the language better.
All the listings and programs in the website are compiled and run using the JDK 1.5.
Download : JDK and JRE 1.5
Java Architecture
The Java environment is composed of a number of system components. You use these components at
compile time to create the Java program and at run time to execute the program. Java achieves its
independence by creating programs designed to run on the Java Virtual Machine rather than any
specific computer system.
• After you write a Java program, you use a compiler that reads the statements in the program
and translates them into a machine independent format called bytecode.
• Bytecode files, which are very compact, are easily transported through a distributed system
like the Internet.
• The compiled Java code (resulting byte code) will be executed at run time.
Java programs can be written and executed in two ways:
Below is a java sample code for the traditional Hello World program. Basically, the idea behind this
Hello World program is to learn how to create a program, compile and run it. To create your java
source code you can use any editor( Text pad/Edit plus are my favorites) or you can use an IDE like
Eclipse.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}//End of main
}//End of HelloWorld Class
Output
Hello World
I created a class named “HelloWorld” containing a simple main function within it. The keyword class
specifies that we are defining a class. The name of a public class is spelled exactly as the name of the
file (Case Sensitive). All java programs begin execution with the method named main(). main method
that gets executed has the following signature : public static void main(String args[]).Declaring this
method as public means that it is accessible from outside the class so that the JVM can find it when it
looks for the program to start it. It is necessary that the method is declared with return type void (i.e.
no arguments are returned from the method). The main method contains a String argument array
that can contain the command line arguments. The brackets { and } mark the beginning and ending
of the class. The program contains a line ‘System.out.println(”Hello World”);’ that tells the computer
to print out on one line of text namely ‘Hello World’. The semi-colon ‘;’ ends the line of code. The
double slashes ‘//’ are used for comments that can be used to describe what a source code is doing.
Everything to the right of the slashes on the same line does not get compiled, as they are simply the
comments in a program.
All the 3 valid main method’s shown above accepts a single String array argument.
Compiling and Running an Application
To compile and run the program you need the JDK distributed by Sun Microsystems. The JDK contains
documentation, examples, installation instructions, class libraries and packages, and tools. Download
an editor like Textpad/EditPlus to type your code. You must save your source code with a .java
extension. The name of the file must be the name of the public class contained in the file.
javadoc
The javadoc tool provided by Sun is used to produce documentation for an application or program,
Jar Files
A jar file is used to group together related class files into a single file for more compact storage,
distribution, and transmission.
When you get this error, you should conclude that your operating system cannot find the compiler
(javac). To solve this error you need to set the PATH variable.
Firstly the PATH variable is set so that we can compile and execute programs from any directory
without having to type the full path of the command. To set the PATH of jdk on your system
(Windows XP), add the full path of the jdk<version>\bin directory to the PATH variable. Set the PATH
as follows on a Windows machine:
a. Click Start > Right Click “My Computer” and click on “Properties”
b. Click Advanced > Environment Variables.
c. Add the location of bin folder of JDK installation for PATH in User Variables and System Variables. A
typical value for PATH is:
C:\jdk<version>\bin (jdk<version is nothing but the name of the directory where jdk is installed)
If there are already some entries in the PATH variable then you must add a semicolon and then add
the above value (Version being replaced with the version of JDK). The new path takes effect in each
new command prompt window you open after setting the PATH variable.
If you receive this error, java cannot find your compiled byte code file, HelloWorld.class.If both your
class files and source code are in the same working directory and if you try running your program
from the current working directory than, your program must get executed without any problems as,
java tries to find your .class file is your current directory. If your class files are present in some other
directory other than that of the java files we must set the CLASSPATH pointing to the directory that
contain your compiled class files.CLASSPATH can be set as follows on a Windows machine:
a. Click Start > Right Click “My Computer” and click on “Properties”
b. Click Advanced > Environment Variables.
Add the location of classes’ folder containing all your java classes in User Variables.
If there are already some entries in the CLASSPATH variable then you must add a semicolon and then
add the new value . The new class path takes effect in each new command prompt window you open
after setting the CLASSPATH variable.
Java 1.5
The Java 1.5 released in September 2004.
Goals
New Features
This part of the java tutorial teaches you the basic language elements and syntax for the java
programming language. Once you get these basic language concepts you can continue with the other
object oriented programming language concepts.
Keywords
There are certain words with a specific meaning in java which tell (help) the compiler what the
program is supposed to do. These Keywords cannot be used as variable names, class names, or
method names. Keywords in java are case sensitive, all characters being lower case.
Keywords are reserved words that are predefined in the language; see the table below (Taken from
Sun Java Site). All the keywords are in lowercase.
abstract default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
}
}
Some Tricky Observations: The words virtual, ifdef, typedef, friend, struct and union are all words
related to
the C programming language. const and goto are Java keywords. The word finalize is the name of a
method
of the Object class and hence not a keyword. enum and label are not keywords.
Comments
Comments are descriptions that are added to a program to make code easier to understand. The
compiler ignores comments and hence its only for documentation of the program.
Block style comments begin with /* and terminate with */ that spans multiple lines.
Line style comments begin with // and terminate at the end of the line. (Shown in the above
program)
Documentation style comments begin with /** and terminate with */ that spans multiple lines. They
are generally created using the automatic documentation generation tool, such as javadoc. (Shown in
the above program)
name of this compiled file is comprised of the name of the class with .class as an extension.
Note in the above example, a compilation error results in where the variable is tried to be accessed
and not at the place where its declared without any value.
The data type indicates the attributes of the variable, such as the range of values that can be stored
and the operators that can be used to manipulate the variable. Java has four main primitive data
types built into the language. You can also create your own composite data types.
Java has four main primitive data types built into the language. We can also create our own data
types.
Character: char
The following chart (Taken from Sun Java Site) summarizes the default values for the java built in
data types. Since I thought Mentioning the size was not important as part of learning Java, I have not
mentioned it in the below table. The size for each Java type can be obtained by a simple Google
search.
Data Type Default Value (for fields) Range
int 0
long 0L
float 0.0f
double 0.0d
boolean false
For Example
In the above statement, String is the data type for the identifier message. If you don’t specify a
value when the variable is declared, it will be assigned the default value for its data type.
• Can consist of upper and lower case letters, digits, dollar sign ($) and the underscore ( _ )
character.
• Within a given section of your program or scope, each user defined item must have a unique
identifier
Classes
A class is nothing but a blueprint for creating different objects which defines its properties and
behaviors. An object exhibits the properties and behaviors defined by its class. A class can contain
fields and methods to describe the behavior of an object. Methods are nothing but members of a class
that provide a service for an object or perform some business logic.
Objects
An object is an instance of a class created using a new operator. The new operator returns a
reference to a new instance of a class. This reference can be assigned to a reference variable of the
class. The process of creating objects from a class is called instantiation. An object reference provides
a handle to an object that is created and stored in memory. In Java, objects can only be manipulated
via references, which can be stored in variables.
Interface
An Interface is a contract in the form of collection of method and constant declarations. When a class
implements an interface, it promises to implement all of the methods declared in that interface.
Instance Members
Each object created will have its own copies of the fields defined in its class called instance variables
which represent an object’s state. The methods of an object define its behaviour called instance
methods. Instance variables and instance methods, which belong to objects, are collectively called
instance members. The dot ‘.’ notation with a object reference is used to access Instance Members.
Static Members
Static members are those that belong to a class as a whole and not to a particular instance (object).
A static variable is initialized when the class is loaded. Similarly, a class can have static methods.
Static variables and static methods are collectively known as static members, and are declared with a
keyword static. Static members in the class can be accessed either by using the class name or by
using the object reference, but instance members can only be accessed via object references.
Below is a program showing the various parts of the basic language syntax that were discussed
above.
/** Comment
* Displays "Hello World!" to the standard output.
*/
public class HelloWorld {
String output = "";
static HelloWorld helloObj; //Line 1
public HelloWorld(){
output = "Hello World";
}
Java Operators
They are used to manipulate primitive data types. Java operators can be classified as unary, binary,
or ternary—meaning taking one, two, or three arguments, respectively. A unary operator may appear
before (prefix) its argument or after (postfix) its argument. A binary or ternary operator appears
between its arguments.
Java operators fall into eight different categories: assignment, arithmetic, relational, logical,
bitwise,
compound assignment, conditional, and type.
Assignment Operators =
Arithmetic Operators - + * / % ++ --
Relational Operators > < >= <= == !=
Conditional Operator ?:
Java has eight different operator types: assignment, arithmetic, relational, logical, bitwise, compound
assignment, conditional, and type.
Assignment operators
The java assignment operator statement has the following syntax:
<variable> = <expression>
If the value already exists in the variable it is overwritten by the assignment operator (=).
public class AssignmentOperatorsDemo {
public AssignmentOperatorsDemo() {
// Assigning Primitive Values
int j, k;
j = 10; // j gets the value 10.
j = 5; // j gets the value 5. Previous value is overwritten.
k = j; // k gets the value 5.
System.out.println("j is : " + j);
System.out.println("k is : " + k);
// Assigning References
Integer i1 = new Integer("1");
Integer i2 = new Integer("2");
System.out.println("i1 is : " + i1);
System.out.println("i2 is : " + i2);
i1 = i2;
System.out.println("i1 is : " + i1);
System.out.println("i2 is : " + i2);
// Multiple Assignments
k = j = 10; // (k = (j = 10))
System.out.println("j is : " + j);
System.out.println("k is : " + k);
}
public static void main(String args[]) {
new AssignmentOperatorsDemo();
}
}
Download AssignmentOperatorsDemoSource code
Arithmetic operators
Java provides eight Arithmetic operators. They are for addition, subtraction, multiplication, division,
modulo (or remainder), increment (or add 1), decrement (or subtract 1), and negation. An example
program is shown below that demonstrates the different arithmetic operators in java.
The binary operator + is overloaded in the sense that the operation performed is determined by the
type of the operands. When one of the operands is a String object, the other operand is implicitly
converted to its string representation and string concatenation is performed.
String message = 100 + “Messages”; //”100 Messages”
public ArithmeticOperatorsDemo() {
int x, y = 10, z = 5;
x = y + z;
System.out.println("+ operator resulted in " + x);
x = y - z;
System.out.println("- operator resulted in " + x);
x = y * z;
System.out.println("* operator resulted in " + x);
x = y / z;
System.out.println("/ operator resulted in " + x);
x = y % z;
System.out.println("% operator resulted in " + x);
x = y++;
System.out.println("Postfix ++ operator resulted in " + x);
x = ++z;
System.out.println("Prefix ++ operator resulted in " + x);
x = -y;
System.out.println("Unary operator resulted in " + x);
// Some examples of special Cases
int tooBig = Integer.MAX_VALUE + 1; // -2147483648 which is
// Integer.MIN_VALUE.
int tooSmall = Integer.MIN_VALUE - 1; // 2147483647 which is
// Integer.MAX_VALUE.
System.out.println("tooBig becomes " + tooBig);
System.out.println("tooSmall becomes " + tooSmall);
System.out.println(4.0 / 0.0); // Prints: Infinity
System.out.println(-4.0 / 0.0); // Prints: -Infinity
System.out.println(0.0 / 0.0); // Prints: NaN
double d1 = 12 / 8; // result: 1 by integer division. d1 gets the value
// 1.0.
double d2 = 12.0F / 8; // result: 1.5
System.out.println("d1 is " + d1);
System.out.println("d2 iss " + d2);
}
public static void main(String args[]) {
new ArithmeticOperatorsDemo();
}
}
Download ArithmeticOperatorsDemo Source code
Relational operators
Relational operators in Java are used to compare 2 or more objects. Java provides six relational
operators:
greater than (>), less than (<), greater than or equal (>=), less than or equal (<=), equal (==), and
not equal (!=).
All relational operators are binary operators, and their operands are numeric expressions.
Binary numeric promotion is applied to the operands of these operators. The evaluation results in a
boolean value. Relational operators have precedence lower than arithmetic operators, but higher than
that of the assignment operators. An example program is shown below that demonstrates the
different relational operators in java.
public RelationalOperatorsDemo( ) {
int x = 10, y = 5;
System.out.println("x > y : "+(x > y));
System.out.println("x < y : "+(x < y));
System.out.println("x >= y : "+(x >=
y));
System.out.println("x <= y : "+(x <=
y));
System.out.println("x == y : "+(x ==
y));
System.out.println("x != y : "+(x !=
y));
Logical operators
Logical operators return a true or false value based on the state of the Variables. There are six logical,
or boolean, operators. They are AND, conditional AND, OR, conditional OR, exclusive OR, and NOT.
Each argument to a logical operator must be a boolean data type, and the result is always a boolean
data type. An example program is shown below that demonstrates the different Logical operators in
java.
public class LogicalOperatorsDemo {
public LogicalOperatorsDemo() {
boolean x = true;
boolean y = false;
System.out.println("x & y : " + (x &
y));
System.out.println("x && y : " + (x &&
y));
System.out.println("x | y : " + (x |
y));
System.out.println("x || y: " + (x ||
y));
System.out.println("x ^ y : " + (x ^
y));
System.out.println("!x : " + (!x));
}
public static void main(String args[]) {
new LogicalOperatorsDemo();
}
}
Download LogicalOperatorsDemo Source code
Given that x and y represent boolean expressions, the boolean logical operators are defined in the
Table below.
x y !x x & y x | y x ^ y
x && y x || y
Bitwise operators
Java provides Bit wise operators to manipulate the contents of variables at the bit level.
These variables must be of numeric data type ( char, short, int, or long). Java provides seven bitwise
operators. They are AND, OR, Exclusive-OR, Complement, Left-shift, Signed Right-shift, and Unsigned
Right-shift. An example program is shown below that demonstrates the different Bit wise operators in
java.
public class BitwiseOperatorsDemo {
public BitwiseOperatorsDemo() {
int x = 0xFAEF; //1 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1
int y = 0xF8E9; //1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 1
int z;
System.out.println("x & y : " + (x & y));
System.out.println("x | y : " + (x | y));
System.out.println("x ^ y : " + (x ^ y));
System.out.println("~x : " + (~x));
System.out.println("x << y : " + (x << y));
System.out.println("x >> y : " + (x >> y));
System.out.println("x >>> y : " + (x >>> y));
//There is no unsigned left shift operator
}
public static void main(String args[]) {
new BitwiseOperatorsDemo();
}
}
Download BitwiseOperatorsDemo Source code
The result of applying bitwise operators between two corresponding bits in the operands is shown in
the Table below.
A B ~A A & B A | B A ^ B
1 1 0 1 1 0
1 0 0 0 1 1
0 1 1 0 1 1
0 0 1 0 0 0
Output
3,0,3
/*
* The below program demonstrates bitwise operators keeping in mind operator precedence
* Operator Precedence starting with the highest is -> |, ^, &
*/
Compound operators
The compound operators perform shortcuts in common programming operations. Java has eleven
compound assignment operators.
Syntax:
The above statement is the same as, argument1 = argument1 operator argument2. An example
program is shown below that demonstrates the different Compound operators in java.
public class CompoundOperatorsDemo {
public CompoundOperatorsDemo() {
int x = 0, y = 5;
x += 3;
System.out.println("x : " + x);
y *= x;
System.out.println("y : " + y);
/*Similarly other operators can be applied as shortcuts. Other
Conditional operators
The Conditional operator is the only ternary (operator takes three arguments) operator in Java. The
operator evaluates the first argument and, if true, evaluates the second argument. If the first
argument evaluates to false, then the third argument is evaluated. The conditional operator is the
expression equivalent of the if-else statement. The conditional expression can be nested and the
conditional operator associates from right to left:(a?b?c?d:e:f:g) evaluates as (a?(b?(c?
d:e):f):g)
An example program is shown below that demonstrates the Ternary operator in java.
public class TernaryOperatorsDemo {
public TernaryOperatorsDemo() {
int x = 10, y = 12, z = 0;
z = x > y ? x : y;
System.out.println("z : " + z);
}
public static void main(String args[]) {
new TernaryOperatorsDemo();
}
}
Download TernaryOperatorsDemo Source code
/*
* The following programs shows that when no explicit parenthesis is used then the
conditional operator
* evaluation is from right to left
*/
FFT
Type conversion allows a value to be changed from one primitive data type to another. Conversion
can occur explicitly, as specified in
the program, or implicitly, by Java itself. Java allows both type widening and type narrowing
conversions.
In java Conversions can occur by the following ways:
• Using an arithmetic operator is used with arguments of different data types (arithmetic
promotion)
Operator Precedence
The order in which operators are applied is known as precedence. Operators with a higher precedence
are applied before operators with a lower precedence. The operator precedence order of Java is
shown below. Operators at the top of the table are applied before operators lower down in the table.
If two operators have the same precedence, they are applied in the order they appear in a statement.
That is, from left to right. You can use parentheses to override the default precedence.
postfix [] . () expr++ expr–
multiplicative */%
additive +-
equality == !=
bitwise
^
exclusive OR
bitwise inclusive
|
OR
logical OR ||
ternary ?:
assignment = “op=”
Example
result = 4 + 5 * 3
First (5 * 3) is evaluated and the result is added to 4 giving the Final Result value as 19. Note that ‘*’
takes higher precedence than ‘+’ according to chart shown above. This kind of precedence of one
operator over another applies to all the operators.
QUIZ
1. How to generate a random number between 1 to x, x being a whole number greater than
1
Java Control statements control the order of execution in a java program, based on data values
and conditional logic. There are three main categories of control flow statements;
We use control statements when we want to change the default sequential order of execution
Selection Statements
The If Statement
The if statement executes a block of code only if the specified expression is true. If the value is false,
then the if block is skipped and execution continues with the rest of the program. You can either have
a single statement or a block of code within an if statement. Note that the conditional expression
must be a Boolean expression.
Output
b>a
Download IfStatementDemo.java
The If-else Statement
The if/else statement is an extension of the if statement. If the statements in the if statement fails,
the statements in the else block are executed. You can either have a single statement or a block of
code within if-else blocks. Note that the conditional expression must be a Boolean expression.
Below is an example that demonstrates conditional execution based on if else statement condition.
public class IfElseStatementDemo {
Output
b>a
Download IfElseStatementDemo.java
Switch Case Statement The switch case statement, also called a case statement is a multi-
way branch with several choices. A switch is easier to implement than a series of if/else
statements. The switch statement begins with a keyword, followed by an expression that
equates to a no long integral value. Following the controlling expression is a code block that
contains zero or more labeled cases. Each label must equate to an integer constant and each
must be unique. When the switch statement executes, it compares the value of the
controlling expression to the values of each case label. The program will select the value of
the case label that equals the value of the controlling expression and branch down that path
to the end of the code block. If none of the case label values match, then none of the codes
within the switch statement code block will be executed. Java includes a default label to use
in cases where there are no matches. We can have a nested switch within a case block of an
outer switch.
Its general form is as follows:
switch (<non-long integral expression>) {
case label1: <statement1>
case label2: <statement2>
…
case labeln: <statementn>
default: <statement>
} // end switch
When executing a switch statement, the program falls through to the next case. Therefore, if
you want to exit in the middle of the switch statement code block, you must insert a break
statement, which causes the program to continue executing after the current code block.
Below is a java example that demonstrates conditional execution based on nested if else statement
condition to find the greatest of 3 numbers.
public class SwitchCaseStatementDemo {
Output
c is the greatest
Control statements control the order of execution in a java program, based on data values and
conditional logic.
There are three main categories of control flow statements;
We use control statements when we want to change the default sequential order of execution
Iteration Statements
While Statement
The while statement is a looping construct control statement that executes a block of code while a
condition is true. You can either have a single statement or a block of code within the while loop. The
loop will never be executed if the testing expression evaluates to false. The loop condition must be a
boolean expression.
}
}
Output
Download WhileLoopDemo.java
The do-while loop is similar to the while loop, except that the test is performed at the end of the loop
instead of at the beginning. This ensures that the loop will be executed at least once. A do-while loop
begins with the keyword do, followed by the statements that make up the body of the loop. Finally,
the keyword while and the test expression completes the do-while loop. When the loop condition
becomes false, the loop is terminated and execution continues with the statement immediately
following the loop. You can either have a single statement or a block of code within the do-while loop.
do
<loop body>
while (<loop condition>);
Below is an example that demonstrates the looping construct namely do-while loop used to print
numbers from 1 to 10.
Download DoWhileLoopDemo.java
0.0
1.0
1.0
2.0
3.0
5.0
8.0
13.0
21.0
34.0
55.0
89.0
144.0
233.0
377.0
610.0
987.0
1597.0
2584.0
4181.0
6765.0
Download Fibonacci.java
For Loops
The for loop is a looping construct which can execute a set of instructions a specified number of
times. It’s a counter controlled loop.
The first part of a for statement is a starting initialization, which executes once before the loop
begins. The <initialization> section can also be a comma-separated list of expression statements. The
second part of a for statement is a test expression. As long as the expression is true, the loop will
continue. If this expression is evaluated as false the first time, the loop will never be executed. The
third part of the for statement is the body of the loop. These are the instructions that are repeated
each time the program executes the loop. The final part of the for statement is an increment
expression that automatically executes after each repetition of the loop body. Typically, this
statement changes the value of the counter, which is then tested to see if the loop should continue.
All the sections in the for-header are optional. Any one of them can be left empty, but the two
semicolons are mandatory. In particular, leaving out the <loop condition> signifies that the loop
condition is true. The (;;) form of for loop is commonly used to construct an infinite loop.
Below is an example that demonstrates the looping construct namely for loop used to print numbers
from 1 to 10.
Download ForLoopDemo.java
ontrol statements control the order of execution in a java program, based on data values and
conditional logic. There are three main categories of control flow statements;
We use control statements when we want to change the default sequential order of execution
Transfer Statements
Continue Statement
A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume
at the top of the nearest enclosing loop. You use a continue statement when you do not want to
execute the remaining statements in the loop, but you do not want to exit the loop itself.
You can also provide a loop with a label and then use the label in your continue statement. The label
name is optional, and is usually only used when you wish to return to the outermost loop in a series
of nested loops.
Below is a program to demonstrate the use of continue statement to print Odd Numbers between 1 to
10.
Download ContinueExample.java
Break Statement
The break statement transfers control out of the enclosing loop ( for, while, do or switch statement).
You use a break statement when you want to jump immediately to the statement following the
enclosing control structure. You can also provide a loop with a label, and then use the label in your
break statement. The label name is optional, and is usually only used when you wish to terminate the
outermost loop in a series of nested loops.
Below is a program to demonstrate the use of break statement to print numbers Numbers 1 to 10.
Numbers 1 - 10
1
2
3
4
5
6
7
8
9
10
Download BreakExample.java
ava Access Specifiers
The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a
class can control what information or data can be accessible by other classes. To take advantage of
encapsulation, you should minimize access whenever possible.
Java provides a number of access modifiers to help you set the level of access you want for classes as
well as the fields, methods and constructors in your classes. A member has package or default
accessibility when no accessibility modifier is specified.
Access Modifiers
1. private
2. protected
3. default
4. public
Fields, methods and constructors declared public (least restrictive) within a public class are visible to
any class in the Java program, whether these classes are in the same package or in another package.
The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also
cannot be used for fields and methods within an interface. Fields, methods or constructors declared
private are strictly controlled, which means they cannot be accesses by anywhere outside the
enclosing class. A standard design strategy is to make all fields private and provide public getter
methods for them.
The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for
fields and methods within an interface. Fields, methods and constructors declared protected in a
superclass can be accessed only by subclasses in other packages. Classes in the same package can
also access protected fields, methods and constructors as well, even if they are not a subclass of the
protected member’s class.
Java provides a default specifier which is used when no access modifier is present. Any class, field,
method or constructor that has no declared access modifier is accessible only by classes in the same
package. The default modifier is not used for fields and methods within an interface.
Below is a program to demonstrate the use of public, private, protected and default access
modifiers while accessing fields and methods. The output of each of these java files depict the
Java access specifiers.
The first class is SubclassInSamePackage.java which is present in pckage1 package. This java file
contains the Base class and a subclass within the enclosing class that belongs to the same class as
shown below.
package pckage1;
class BaseClass {
subClassObj.setY(20);
System.out.println("Value of y is : "+subClassObj.y);*/
//Access Modifiers - Protected
System.out.println("Value of z is : " + subClassObj.z);
subClassObj.setZ(30);
System.out.println("Value of z is : " + subClassObj.z);
//Access Modifiers - Default
System.out.println("Value of x is : " + subClassObj.a);
subClassObj.setA(20);
System.out.println("Value of x is : " + subClassObj.a);
}
}
Output
Value of x is : 10
Value of x is : 20
Value of z is : 10
Value of z is : 30
Value of x is : 10
Value of x is : 20
The second class is SubClassInDifferentPackage.java which is present in a different package then the
first one. This java class extends First class (SubclassInSamePackage.java).
import pckage1.*;
subClassObj.setY(20);
System.out.println("Value of y is : "+subClassObj.y);*/
//Access specifiers - Protected
// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are protected.
/* System.out.println("Value of z is : "+subClassObj.z);
subClassObj.setZ(30);
System.out.println("Value of z is : "+subClassObj.z);*/
System.out.println("Value of z is : " + subClassDiffObj.getZZZ());
//Access Modifiers - Default
// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are default.
/*
System.out.println("Value of a is : "+subClassObj.a);
subClassObj.setA(20);
System.out.println("Value of a is : "+subClassObj.a);*/
}
}
Output
Value of x is : 10
Value of x is : 30
Value of z is : 10
The third class is ClassInDifferentPackage.java which is present in a different package then the first
one.
import pckage1.*;
subClassObj.setY(20);
System.out.println("Value of y is : "+subClassObj.y);*/
//Access Modifiers - Protected
// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are protected.
/* System.out.println("Value of z is : "+subClassObj.z);
subClassObj.setZ(30);
System.out.println("Value of z is : "+subClassObj.z);*/
//Access Modifiers - Default
// If we remove the comments it would result in a compilaton
// error as the fields and methods being accessed are default.
/* System.out.println("Value of a is : "+subClassObj.a);
subClassObj.setA(20);
System.out.println("Value of a is : "+subClassObj.a);*/
}
}
Output
Value of x is : 10
Value of x is : 30
A class is nothing but a blueprint or a template for creating different objects which defines its
properties and behaviors. Java class objects exhibit the properties and behaviors defined by its class.
A class can contain fields and methods to describe the behavior of an object.
Methods are nothing but members of a class that provide a service for an object or perform some
business logic. Java fields and member functions names are case sensitive. Current states of a class’s
corresponding object are stored in the object’s instance variables. Methods define the operations that
can be performed in java programming.
Below is an example showing the Objects and Classes of the Cube class that defines 3 fields namely
length, breadth and height. Also the class contains a member function getVolume().
public class Cube {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
}
How do you reference a data member/function?
This is accomplished by stating the name of the object reference, followed by a period (dot), followed
by the name of the member inside the object.
( objectReference.member ). You call a method for an object by naming the object followed by a
period (dot), followed by the name of the method and its argument list, like this:
objectName.methodName(arg1, arg2, arg3).
For example:
cubeObject.length = 4;
cubeObject.breadth = 4;
cubeObject.height = 4;
cubeObject.getvolume()
Instance Variables
Instance variables stores the state of the object. Each class would have its own copy of the variable.
Every object has a state that is determined by the values stored in the object. An object is said to
have changed its state when one or more data values stored in the object have been modified. When
an object responds to a message, it will usually perform an action, change its state etc. An object that
has the ability to store values is often said to have persistence.
Consider this simple Java program showing the use of static fields and static methods
// Class and Object initialization showing the Object Oriented concepts in Java
class Cube {
Download CubeStaticTest.java
Output
Variables defined in an interface are implicitly final. You can’t change value of a final variable (is a
constant). A final class can’t be extended i.e., final class may not be subclassed. This is done for
security reasons with basic classes like String and Integer. It also allows the compiler to make some
optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden
when its class is inherited. Any attempt to override or hide a final method will result in a compiler
error.
equals
toString()
wait()
notify()
notifyAll()
hashcode()
clone()
An object is an instance of a class created using a new operator. The new operator returns a
reference to a new instance of a class. This reference can be assigned to a reference variable of the
class. The process of creating objects from a class is called instantiation. An object encapsulates state
and behavior.
An object reference provides a handle to an object that is created and stored in memory. In Java,
objects can only be manipulated via references, which can be stored in variables.
Creating variables of your class type is similar to creating variables of primitive data types, such as
integer or float. Each time you create an object, a new set of instance variables comes into existence
which defines the characteristics of that object. If you want to create an object of the class and have
the reference variable associated with this object, you must also allocate memory for the object by
using the new operator. This process is called instantiating an object or creating an object instance.
When you create a new object, you use the new operator to instantiate the object. The new operator
returns the location of the object which you assign o a reference type.
Below is an example showing the creation of Cube objects by using the new operator.
public class Cube {
Download Cube.java
Method Overloading
Method overloading results when two or more methods in the same class have the same name but
different parameters. Methods with the same name must differ in their types or number of
parameters. This allows the compiler to match parameters and choose the correct method when a
number of choices exist. Changing just the return type is not enough to overload a method, and will
be a compile-time error. They must have a different signature. When no method matching the input
parameters is found, the compiler attempts to convert the input parameters to types of greater
precision. A match may then be found without error. At compile time, the right implementation is
chosen based on the signature of the method call
Download MethodOverloadDemo.java
Output
No parameters
One parameter: 2
Two parameters: 10 , 20
Sum is 30
Below is a code snippet to show whether a Class Object Represents a Class or Interface:
Class cls = java.lang.String.class;
boolean isClass = !cls.isInterface(); // true
cls = java.lang.Cloneable.class;
isClass = !cls.isInterface(); // false
Constructors
A java constructor has the same name as the name of the class to which it belongs. Constructor’s
syntax does not include a return type, since constructors never return a value.
Constructors may include parameters of various types. When the constructor is invoked using the new
operator, the types must match those that are specified in the constructor definition.
Java provides a default constructor which takes no arguments and performs no special actions or
initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the
super() call. Constructor arguments provide you with a way to provide parameters for the
initialization of an object.
Below is an example of a cube class containing 2 constructors. (one default and one parameterized
constructor).
public class Cube1 {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube1() {
length = 10;
breadth = 10;
height = 10;
}
Cube1(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
cubeObj2 = new Cube1(10, 20, 30);
Download Cube1.java
Note: If a class defines an explicit constructor, it no longer has a default constructor to set the state
of the objects.
If such a class requires a default constructor, its implementation must be provided. Any attempt to
call the default constructor will be a compile time error if an explicit default constructor is not
provided in such a case.
It is possible to use this() construct, to implement local chaining of constructors in a class. The this()
call in a constructorinvokes the an other constructor with the corresponding parameter list within the
same class. Calling the default constructor to create a Cube object results in the second and third
parameterized constructors being called as well. Java requires that any this() call must occur as the
first statement in a constructor.
Below is an example of a cube class containing 3 constructors which demostrates the this() method in
Constructors context
public class Cube2 {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube2() {
this(10, 10);
System.out.println("Finished with Default Constructor");
}
Cube2(int l, int b) {
this(l, b, 10);
System.out.println("Finished with Parameterized Constructor having 2
params");
}
Cube2(int l, int b, int h) {
length = l;
breadth = b;
height = h;
System.out.println("Finished with Parameterized Constructor having 3
params");
}
public static void main(String[] args) {
Cube2 cubeObj1, cubeObj2;
cubeObj1 = new Cube2();
cubeObj2 = new Cube2(10, 20, 30);
System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume());
}
}
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube2() {
this(10, 10);
System.out.println("Finished with Default Constructor");
}
Cube2(int l, int b) {
this(l, b, 10);
System.out.println("Finished with Parameterized Constructor having 2
params");
}
Cube2(int l, int b, int h) {
length = l;
breadth = b;
height = h;
System.out.println("Finished with Parameterized Constructor having 3
params");
}
public static void main(String[] args) {
Cube2 cubeObj1, cubeObj2;
cubeObj1 = new Cube2();
cubeObj2 = new Cube2(10, 20, 30);
System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume());
}
}
Output
Download Cube2.java
Constructor Chaining
Every constructor calls its superclass constructor. An implied super() is therefore included in each
constructor which does not include either the this() function or an explicit super() call as its first
statement. The super() statement invokes a constructor of the super class.
The implicit super() can be replaced by an explicit super(). The super statement must be the first
statement of the constructor.
The explicit super allows parameter values to be passed to the constructor of its superclass and must
have matching parameter types A super() call in the constructor of a subclass will result in the call of
the relevant constructor from the superclass, based on the signature of the call. This is called
constructor chaining.
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube() {
this(10, 10);
System.out.println("Finished with Default Constructor of Cube");
}
Cube(int l, int b) {
this(l, b, 10);
System.out.println("Finished with Parameterized Constructor having
2 params of
Cube");
}
Cube(int l, int b, int h) {
length = l;
breadth = b;
height = h;
System.out.println("Finished with Parameterized Constructor having
3 params of
Cube");
}
}
int weight;
SpecialCube() {
super();
weight = 10;
}
SpecialCube(int l, int b) {
this(l, b, 10);
System.out.println("Finished with Parameterized Constructor having
2 params of
SpecialCube");
}
SpecialCube(int l, int b, int h) {
super(l, b, h);
weight = 20;
System.out.println("Finished with Parameterized Constructor having
3 params of
SpecialCube");
}
public static void main(String[] args) {
SpecialCube specialObj1 = new SpecialCube();
SpecialCube specialObj2 = new SpecialCube(10, 20);
System.out.println("Volume of SpecialCube1 is : "
+ specialObj1.getVolume());
System.out.println("Weight of SpecialCube1 is : "
+ specialObj1.weight);
System.out.println("Volume of SpecialCube2 is : "
+ specialObj2.getVolume());
System.out.println("Weight of SpecialCube2 is : "
+ specialObj2.weight);
}
}
Download SpecialCube.java
Output
The super() construct as with this() construct: if used, must occur as the first statement in a
constructor, and it can only be used in a constructor declaration. This implies that this() and super()
calls cannot both occur in the same constructor. Just as the this() construct leads to chaining of
constructors in the same class, the super() construct leads to chaining of subclass constructors to
superclass constructors.
if a constructor has neither a this() nor a super() construct as its first statement, then a super() call
to the default constructor in the superclass is inserted.
Note: If a class only defines non-default constructors, then its subclasses will not include an implicit
super() call. This will be flagged as a compile-time error. The subclasses must then explicitly call a
superclass constructor, using the super() construct with the right arguments to match the appropriate
constructor of the superclass.
Below is an example of a class demonstrating constructor chaining using explicit super() call.
class Cube {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube(int l, int b, int h) {
length = l;
breadth = b;
height = h;
System.out.println("Finished with Parameterized Constructor having
3 params of Cube");
}
}
int weight;
SpecialCube1() {
super(10, 20, 30); //Will Give a Compilation Error without this line
weight = 10;
}
public static void main(String[] args) {
SpecialCube1 specialObj1 = new SpecialCube1();
System.out.println("Volume of SpecialCube1 is : "+
specialObj1.getVolume());
}
}
Output
Finished with Parameterized Constructor having 3 params of Cube
Volume of SpecialCube1 is : 6000
Download SpecialCube1.java
Java Serilization
Java Serialization
ntroduction to Object Serialization
Java object serialization is used to persist Java objects to a file, database, network, process or any
other system. Serialization flattens objects into an ordered, or serialized stream of bytes. The ordered
stream of bytes can then be read at a later time, or in another environment, to recreate the original
objects.
Java serialization does not cannot occur for transient or static fields. Marking the field transient
prevents the state from being written to the stream and from being restored during deserialization.
Java provides classes to support writing objects to streams and restoring objects from streams. Only
objects that support the java.io.Serializableinterface or the java.io.Externalizable interface can be
written to streams.
public interface Serializable
You can use the transient keyword to describe temporary variables, or variables that contain local
information,
These high-level streams are each chained to a low-level stream, such as FileInputStream or
FileOutputStream.
The low-level streams handle the bytes of data. The writeObject method saves the state of the class
by writing the individual fields to the ObjectOutputStream. The readObject method is used to
deserialize the object from
the object input stream.
Case 1: Below is an example that demonstrates object Serialization into a File
GetPersonDetails is the class that is used to Deserialize object from the File (person.txt).
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;
public class GetPersonDetails {
PersonPersist is the class that is used to serialize object into the File (person.txt).
public class PersonPersist {
——————————————————————————–
Case 2: Below is an example that demonstrates object Serialization into the database
PersonDetails remains the same as shown above
GetPersonDetails remains the same as shown above
PersonPersist is the class that is used to serialize object into the into the Database Table SerialTest.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PersonPersist {
——————————————————————————–
Case 3: Below is an example that demonstrates object Serialization into the database using Base 64
Encoder
PersonDetails remains the same as shown above
GetPersonDetails remains the same as shown above
Create SerialTest Table
create table SerialTest(
name BLOB,
viewname VARCHAR2(30)
);
PersonPersist is the class that is used to serialize object into the Database Table SerialTest
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PersonPersist {
int numofGears;
String color;
abstract boolean hasDiskBrake();
abstract int getNoofGears();
}
abstract class Shape {
static int x, y;
public Point() {
x = 0;
y = 0;
}
public double area() {
return 0;
}
public double perimeter() {
return 0;
}
public static void print() {
System.out.println("point: " + x + "," + y);
}
public static void main(String args[]) {
Point p = new Point();
p.print();
}
}
Output
point: 0, 0
Notice that, in order to create a Point object, its class cannot be abstract. This means that all of the
abstract methods of the Shape class must be implemented by the Point class.
The subclass must define an implementation for every abstract method of the abstract superclass, or
the subclass itself will also be abstract. Similarly other shape objects can be created using the generic
Shape Abstract class.
A big Disadvantage of using abstract classes is not able to use multiple inheritance. In the sense,
when a class extends an abstract class, it can’t extend any other class.
Java Interface
In Java, this multiple inheritance problem is solved with a powerful construct called interfaces.
Interface can be used to define a generic template and then one or more abstract classes to define
partial implementations of the interface. Interfaces just specify the method declaration (implicitly
public and abstract) and can only contain fields (which are implicitly public static final). Interface
definition begins with a keyword interface. An interface like that of an abstract class cannot be
instantiated.
Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one or
more interfaces. Java does not support multiple inheritance, but it allows you to extend one class and
implement many interfaces.
If a class that implements an interface does not define all the methods of the interface, then it must
be declared abstract and the method definitions must be provided by the subclass that extends the
abstract class.
Example 1: Below is an example of a Shape interface
interface Shape {
static int x, y;
public Point() {
x = 0;
y = 0;
}
public double area() {
return 0;
}
public double volume() {
return 0;
}
public static void print() {
System.out.println("point: " + x + "," + y);
}
public static void main(String args[]) {
Point p = new Point();
p.print();
}
}
Similarly, other shape objects can be created by interface programming by implementing generic
Shape Interface.
Example 2: Below is a java interfaces program showing the power of interface programming in java
Listing below shows 2 interfaces and 4 classes one being an abstract class.
Note: The method toString in class A1 is an overridden version of the method defined in the class
named Object. The classes B1 and C1 satisfy the interface contract. But since the class D1 does not
define all the methods of the implemented interface I2, the class D1 is declared abstract.
Also,
i1.methodI2() produces a compilation error as the method is not declared in I1 or any of its super
interfaces if present. Hence a downcast of interface reference I1 solves the problem as shown in the
program. The same problem applies to i1.methodA1(), which is again resolved by a downcast.
When we invoke the toString() method which is a method of an Object, there does not seem to be any
problem as every interface or class extends Object and any class can override the default toString() to
suit your application needs. ((C1)o1).methodI1() compiles successfully, but produces a
ClassCastException at runtime. This is because B1 does not have any relationship with C1 except they
are “siblings”. You can’t cast siblings into one another.
When a given interface method is invoked on a given reference, the behavior that results will be
appropriate to the class from which that particular object was instantiated. This is runtime
polymorphism based on interfaces and overridden methods.
interface I1 {
interface I2 extends I1 {
class A1 {
class C1 implements I2 {
Polymorphism
Polymorphism means one name, many forms. There are 3 distinct forms of Java Polymorphism;
Method overloading (Compile time polymorphism)
Method overriding through inheritance (Run time polymorphism)
Method overriding through the Java interface (Run time polymorphism)
Polymorphism allows a reference to denote objects of different types at different times during
execution. A super type reference exhibits polymorphic behavior, since it can denote objects of its
subtypes.
interface Shape {
int x = 10;
public double area( ) {
return (6 * x * x);
}
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.
public class RunTimeCastDemo {
* 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 {
}
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
Example 2
v = c; //Ok Compiles fine
c = v; // illegal conversion from interface type to class type results in compilation error
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).
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(){
}
}
class Ford extends Car {
void fordMethod () {
}
}
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)
((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.
void carMethod() {
}
}
void fordMethod() {
System.out.println("I am fordMethod defined in Class Ford");
}
}
void fordMethod() {
System.out.println("I am fordMethod defined in Class Ford");
}
}
public class ObjectCastingEx {
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.
String name;
Vehicle() {
name = "Vehicle";
}
}
HeavyVehicle() {
name = "HeavyVehicle";
}
}
Truck() {
name = "Truck";
}
}
LightVehicle() {
name = "LightVehicle";
}
}
Output
hV is an HeavyVehicle: true
T is an HeavyVehicle: true
hV is a Truck: false
hv2 is an HeavyVehicle: false
Java Inheritance
Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that
an object of a subclass can be used wherever an object of the superclass can be used.
Class Inheritance in javamechanism is used to build new classes from existing classes. The
inheritance relationship is transitive: if class x extends class y, then a class z, which extends class x,
will also inherit from class y.
For example a car class can inherit some properties from a General vehicle class. Here we find that
the base class is the vehicle class and the subclass is the more specific car class. A subclass must use
the extends clause to derive from a super class which must be written in the header of the subclass
definition. The subclass inherits members of the superclass and hence promotes code reuse. The
subclass itself can add its own new behavior and properties. The java.lang.Object class is always at
the top of any Class inheritance hierarchy.
class Box {
double width;
double height;
double depth;
Box() {
}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
void getVolume() {
System.out.println("Volume is : " + width * height * depth);
}
}
double weight;
MatchBox() {
}
MatchBox(double w, double h, double d, double m) {
super(w, h, d);
weight = m;
}
public static void main(String args[]) {
MatchBox mb1 = new MatchBox(10, 10, 10, 10);
mb1.getVolume();
System.out.println("width of MatchBox 1 is " + mb1.width);
System.out.println("height of MatchBox 1 is " + mb1.height);
System.out.println("depth of MatchBox 1 is " + mb1.depth);
System.out.println("weight of MatchBox 1 is " + mb1.weight);
}
}
Output
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0
Download MatchBox.java
1. Private members of the superclass are not inherited by the subclass and can only be indirectly
accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses in
other packages, as these members are only accessible by their simple names in subclasses within the
same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a
subclass.
4. A subclass can extend only one superclass
class Vehicle {
// Instance fields
int noOfTyres; // no of tyres
private boolean accessories; // check if accessorees present or not
protected String brand; // Brand of the car
// Static fields
private static int counter; // No of Vehicle objects created
// Constructor
Vehicle() {
System.out.println("Constructor of the Super class called");
noOfTyres = 5;
accessories = true;
brand = "X";
counter++;
}
// Instance methods
public void switchOn() {
accessories = true;
}
public void switchOff() {
accessories = false;
}
public boolean isPresent() {
return accessories;
}
private void getBrand() {
System.out.println("Vehicle Brand: " + brand);
}
// Static methods
public static void getNoOfVehicles() {
System.out.println("Number of Vehicles: " + counter);
}
}
Output
Download VehicleDetails.java
The this reference to the current object is useful in situations where a local variable hides, or
shadows, a field with the same name. If a method needs to pass the current object to another
method, it can do so using the this reference. Note that the this reference cannot be used in a static
context, as static code is not executed in the context of any object.
class Counter {
int i = 0;
Counter increment() {
i++;
return this;
}
void print() {
System.out.println("i = " + i);
}
}
Output
Volume is : 1000.0
width of MatchBox 1 is 10.0
height of MatchBox 1 is 10.0
depth of MatchBox 1 is 10.0
weight of MatchBox 1 is 10.0
The new method definition must have the same method signature (i.e., method name and
parameters) and return type. Only parameter types and return type are chosen as criteria for
matching method signature. So if a subclass has its method parameters as final it doesn’t really
matter for method overriding scenarios as it still holds true. The new method definition cannot narrow
the accessibility of the method, but it can widen it. The new method definition can only specify all or
none, or a subset of the exception classes (including their subclasses) specified in the throws clause
of the overridden method in the super class
class SuperClassWithDifferentMethods {
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 {
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()");
}*/
}
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
Java toString Method
Implementing toString method in java is done by overriding the Object’s toString method.
The java toString() method is used when we need a string representation of an object. It is defined
in Object class. This method can be overridden to customize the String representation of the Object.
Below is a program showing the use of the Object’s Default toString java method.
class PointCoordinates {
private int x, y;
public PointCoordinates(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
Download ToStringDemo.java
PointCoordinates@119c082 testing
In the above example when we try printing PointCoordinates object, it internally calls the Object’s
toString() method as we have not overridden the java toString() method. Since out example has no
toString method, the default one in Object is used. The format of the default toString method of the
Object is as shown below.
Class Name, “@”, and the hex version of the object’s hashcode concatenated into a string.
The default hashCode method in Object is typically implemented by converting the memory address
of the object into an integer.
Below is an example shown of the same program by Overriding the default Object toString() method.
The toString() method must be descriptive and should generally cover all the contents of the object.
class PointCoordinates {
private int x, y;
public PointCoordinates(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
// Custom toString() Method.
public String toString() {
return "X=" + x + " " + "Y=" + y;
}
}
Download ToStringDemo2.java
X=10 Y=10
X=10 Y=10 testing
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.
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.
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 (+).
public class StringsDemo {
System.out.println("byteStr : "+byteStr);
System.out.println("charStr : "+charStr);
System.out.println("buffStr : "+buffStr);
Download StringDemo1.java
Output
byteStr :
charStr : abCD
buffStr : abcde
–~~~~~~~~~~~~–
String Equality
public class StringsDemo2 {
Download StringDemo2.java
Output
1. compareTo(String anotherString)
Compares two strings lexicographically.
2. charAt(int index)
Returns the character at the specified index.
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.
Returns the index within this string of the first occurrence of the specified character.
Returns the index within this string of the first occurrence of the specified character, starting the
search at the specified index.
Returns the index within this string of the first occurrence of the specified substring.
Returns the index within this string of the first occurrence of the specified substring, starting at the
specified index.
Returns the index within this string of the last occurrence of the specified character.
Returns the index within this string of the last occurrence of the specified character, searching
backward starting at the specified index.
Returns the index within this string of the rightmost occurrence of the specified substring.
Returns the index within this string of the last occurrence of the specified substring, searching
backward starting at the specified index.
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()
Output
Output
* == Operator
* equals method
* compareTo method
Download StringComparision1.java
The equals method is used when we need to compare the content of the text present in the String
objects. This method returns true when two String objects hold the same content (i.e. the same
values). The following Program would print “The strings are unequal” In the first case and “The
strings are equal” in the second case.
public class StringComparision2 {
Download StringComparision2.java
Download StringComparision3.java
Java StringBuffer
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 {
Download StringBufferDemo.java
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.
5. toString()
Converts to a string representing the data in this string buffer
9. reverse()
The character sequence contained in this string buffer is replaced by the reverse of the sequence.
Download StringBufferFunctionsDemo.java
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 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.
System.out.println("Computing Division.");
int average = totalSum/totalNumber;
System.out.println("Average : "+ average);
}
}
Download DivideException.java
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.
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.
try {
<code>
} catch (<exception type1> <parameter1>) { // 0 or more
<statements>
}
} finally { // finally block
<statements>
}
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.
}
} finally { // finally block
<statements>
}
Download DivideException2.java
Output
Computing Division.
Exception : / by zero
Finally Block Executes. Exception Occurred
result : -1
}
catch(Exception e){
System.out.println("Exception : "+ e.getMessage());
}
finally{
if(quotient != -1){
System.out.println("Finally Block Executes");
System.out.println("Result : "+ quotient);
}else{
System.out.println("Finally Block Executes. Exception
Occurred");
return quotient;
}
}
return quotient;
}
}
Output
–~~~~~~~~~~~~–
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.
2. The catch blocks and finally block must always appear in conjunction
with a try 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 {
}
}
}
Download DivideException1.javaOutput
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.
TooHot(){
super ("Default messaeg : Hot");
}
TooHot(String message){
super (message);
}
}
TooCold(){
super ("Default messaeg : Cold");
}
TooCold(String message){
super (message);
}
}
class TempertureObject{
int temperature;
Download ExceptionExample.javaOutput
Output
Very Hot
Very Cold
Perfect Temperature
A program can explicitly throw an exception using the throw statement besides the implicit exception
thrown.
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.
Each <ExceptionTypei> can be a checked or unchecked or sometimes even a custom Exception. The
exception type specified in the throws clause in the method prototype can be a super class type of the
actual exceptions thrown. Also an overriding method cannot allow more checked exceptions in its
throws clause than the inherited method does.
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 {
}
finally{
if(quotient != -1){
System.out.println("Finally Block Executes");
System.out.println("Result : "+ quotient);
}else{
System.out.println("Finally Block Executes. Exception
Occurred");
}
}
return quotient;
}
}
Download DivideException3.javaOutput
Output
Computing Division.
Finally Block Executes
Result : 10
Computing Division.
Finally Block Executes. Exception Occurred
Exception : Division attempt by 0
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 {
int x = 10, y = 2;
int counter = 0;
boolean flag = true;
while (flag) {
start:
try {
if ( y > 1 )
break start;
if ( y < 0 )
return;
x = x / y;
System.out.println ( "x : " + x + " y : "+y );
}
catch ( Exception e ) {
System.out.println ( e.getMessage() );
}
finally {
++counter;
System.out.println ( "Counter : " + counter );
}
--y;
}
}
}
Download ExceptionExample6.javaOutput
Output
Counter : 1
x : 10 y : 1
Counter : 2
/ by zero
Counter : 3
Counter : 4
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;
import java.io.IOException;
import javax.swing.JOptionPane;
public class ExceptionExample7{
static int numerator, denominator;
try{
numerator = Integer.parseInt( num );
denominator = Integer.parseInt( denom );
}
catch ( NumberFormatException nfe ){
System.out.println( "One of the inputs is not an
integer" );
return;
}
catch ( Exception e ){
System.out.println( "Exception: " + e.getMessage( ) );
return;
}
Singleton Pattern
ttern we need to consider the following 4 steps:
vate constructor
ctDemo {
nstructor is private
jectDemo() {
Code
letonObject singletonObject;
nstructor is private
jectDemo() {
Code
etonObjectDemo getSingletonObject() {
null) {
gletonObject = new SingletonObjectDemo();
letonObject;
e a copy of the Object by cloning it using the Object’s clone method. This