Core Java-2
Core Java-2
Prerequisites
Before you start doing practice with various types of examples
given in this reference, I'm making an assumption that you are
already aware about what is a computer program and what is a
computer programming language.
Where It Is Used
According to Sun, 3 billion devices run Java. There are many devices
where Java is currently used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player,
antivirus etc.
2. Web Applications such as irctc.co.in
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.
Types Of Java Applications
There are mainly 4 type of applications that can be created using Java:
1) Standalone Application
It is also known as desktop application or window-based application.
An application that we need to install
on every machine such as media player, antivirus etc. AWT and Swing
are used in Java for creating
standalone applications.
2) Web Application
An application that runs on the server side and creates dynamic page,
is called web application. Currently,
servlet, jsp, struts, jsf etc. technologies are used for creating web
applications in Java.
Cont..
3) Enterprise Application
An application that is distributed in nature, such as banking
applications etc. It has the advantage of high
level security, load balancing and clustering. In Java, EJB is used for
creating enterprise applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android
and Java ME are used for creating mobile
applications.
Java Overview
Java programming language was originally developed by Sun
Microsystems, which was initiated by James Gosling and released in
1995 as core component of Sun Microsystems Java platform (Java
1.0 [J2SE]).
As of December 08 the latest release of the Java Standard Edition is 6
(J2SE).
With the advancement of Java and its wide spread popularity,
multiple configurations were built to suite various types of platforms.
Ex: J2EE for Enterprise Applications, J2ME for Mobile Applications.
Features of Java
I. Simple 9.Interpreted
2. Object-oriented
10.High Performance
3. Platform independent 11. Multithreaded
4.Secured 12.Distributed
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
Features Of Java
Object Oriented : In java everything is an Object. Java can be easily
extended since it is based on the Object model.
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.
Features Of Java Cont..
Simple :Java is designed to be easy to learn. If you understand the
basic concept of OOP java would be easy to master.
Secure : With Java's secure feature it enables to develop virus-free,
tamper-free systems. Authentication techniques are based on
public-key encryption.
Architectural- neutral :Java compiler generates an architecture-
neutral object file format which makes the compiled code to be
executable on many processors, with the presence Java runtime
system.
Features Of Java Cont..
Portable :being architectural neutral and having no implementation
dependent aspects of the specification makes Java portable.
Compiler and Java is written in ANSI C with a clean portability
boundary means We may carry the Java byte code to any platform.
Robust : Robust simply means strong. Java uses strong memory
management. There are lack of pointers that avoids security
problem. There is automatic garbage collection in Java. There is
exception handling and type
checking mechanism in Java. All these points makes Java robust.
Multi-threaded : With Java's multi-threaded feature it is possible to
write programs that can do many tasks simultaneously. This design
feature allows developers to construct smoothly running interactive
applications.
Features Of Java Cont..
Interpreted :Java byte code is translated on the fly to native machine
instructions and is not stored anywhere. The development process is
more rapid and analytical since the linking is an incremental and
light weight process.
High Performance: With the use of Just-In-Time compilers Java
enables high performance.
Distributed :Java is designed for the distributed environment of the
internet.
Dynamic : Java is considered to be more dynamic than C or C++
since it is designed to adapt to an evolving environment. Java
programs can carry extensive amount of run-time information that
can be used to verify and resolve accesses to objects on run-time.
My First Java Programme
40
Java
41
Basic Datatypes
double 8 - - 123.86
char 2 0 216 – 1 ‘a’, ‘\n’
boolean - - - true, false
Reference Data Types
Reference variables are created using defined constructors of the
classes. They are used to access objects. These variables are
declared to be of a specific type that cannot be changed. For
example, Employee, Puppy etc.
Class objects, and various type of array variables come under
reference data type.
Default value of any reference variable is null.
A reference variable can be used to refer to any object of the
declared type or any compatible type.
Example : Animal animal = new Animal("giraffe");
Java Modifier Types
Modifiers are keywords that you add to those definitions to change
their meanings. The Java language has a wide variety of modifiers,
including the following:
Java Access Modifiers
Non Access Modifiers
To use a modifier, you include its keyword in the definition of a
class, method, or variable. The modifier precedes the rest of the
statement, as in the following examples (Italic ones)
Java Modifiers
45
Modifier Class Class Methods Method
Variables Variables
public
private
protected
default
final
abstract
strictfp
transient
synchronized
native
volatile
static
Modifier Example
Access Control Modifiers
1) string1.concat(string2);
2) "My name is ".concat("Zara");
3) "Hello," + " world" + "!"
char charAt(int index)
Returns the character at the specified index.
int compareTo(Object o)
Compares this String to another Object.
int compareTo(String anotherString)
Compares two strings lexicographically.
int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case
differences.
String concat(String str)
Concatenates the specified string to the end of this string.
boolean contentEquals(StringBuffer sb)
Returns true if and only if this String represents the same
sequence of characters as the specified StringBuffer.
static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the
array specified.
static String copyValueOf(char[] data, int offset, int count)
Returns a String that represents the character sequence in the
array specified.
boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
boolean equals(Object anObject)
Compares this string to the specified object.
int hashCode()
Returns a hash code for this string.
int indexOf(int ch)
Returns the index within this string of the first occurrence of the
specified character.
int 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.
int indexOf(String str)
Returns the index within this string of the first occurrence of the
specified substring.
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the
specified substring, starting at the specified index.
int 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.
int 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.
int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of
the specified substring.
int 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.
int length()
Returns the length of this string.
boolean matches(String regex) :-Tells whether or not this string
matches the given regular expression.
Parent
Inherited
capability
Child
119 Final Members: A way for Preventing
Overriding of Members in Subclasses
All methods and variables can be overridden by default
in subclasses.
This can be prevented by declaring them as final using
the keyword “final” as a modifier. For example:
final int marks = 100;
final void display();
This ensures that functionality defined in this method
cannot be altered any. Similarly, the value of a final
variable cannot be altered.
120 Final Classes: A way for Preventing Classes being extended
Shape
Circle Rectangle
The Shape Abstract Class
124
<<Interface>>
Speaker
speak()
132
Implementing Interfaces Example
class Politician implements Speaker {
public void speak(){
System.out.println(“Talk politics”);
}
}
class Priest implements Speaker {
public void speak(){
System.out.println(“Religious Talks”);
}
}
class Lecturer implements Speaker {
public void speak(){
System.out.println(“Talks Object Oriented Design and
Programming!”);
}
} 133
Extending Interfaces
• Like classes, interfaces can also be extended. The new sub-
interface will inherit all the members of the superinterface in the
manner similar to classes. This is achieved by using the keyword
extends as follows:
134
Inheritance and Interface
Implementation
• A general form of interface implementation:
class Student
{
private String name;
studentbyname studentbyidno studentbyage
private String idno;
private int age;
private String city;
studentbynameidno studentbynameage
…………………..
…………………..
class studentbyname implements comparator
{
public int compare(Object o1,Object o2)
{
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return s1.getName().compareTo(s2.getName());
}
}
class studentbyidno implements comparator
{
public int compare(Object o1,Object o2)
{
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return s1.getIdNo().compareTo(s2.getIdNo());
}
}
class studentbyage implements comparator
{
public int compare(Object o1,Object o2)
{
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if( s1.getAge() > s2.getAge() ) return 1;
if( s1.getAge() < s2.getAge() ) return -1;
return 0;
}
}
class studentbynameidno implements comparator
{
public int compare(Object o1,Object o2)
{
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if( s1.getName().compareTo(s2.getName()) == 0)
return s1.getIdNo().compareTo(s2.getIdNo());
else
return s1.getName().compareTo(s2.getName());
}}
class studentbynameage implements comparator
{
public int compare(Object o1,Object o2)
{
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if( s1.getName().compareTo(s2.getName()) == 0)
return s1.getAge() – s2.getAge();
else
return s1.getName().compareTo(s2.getName());
}
}
Import java.util.*;
class comparatorTest
{
public static void main(String args[])
{
Student[] students = new Student[5];
Student[0] = new Student(“John”,”2000A1Ps234”,23,”Pilani”);
Student[1] = new Student(“Meera”,”2001A1Ps234”,23,”Pilani”);
Student[2] = new Student(“Kamal”,”2001A1Ps344”,23,”Pilani”);
Student[3] = new Student(“Ram”,”2000A2Ps644”,23,”Pilani”);
Student[4] = new Student(“Sham”,”2000A7Ps543”,23,”Pilani”);
// Sort By Name
Comparator c1 = new studentbyname();
Arrays.sort(students,c1);
for(int i=0;i<students.length;i++)
System.out.println(students[i]);
// Sort By Idno // Sort by Name & Age
c1 = new studentbyidno(); c1 = new studentbynameage();
Arrays.sort(students,c1); Arrays.sort(students,c1);
for(int i=0;i<students.length;i++) for(int i=0;i<students.length;i++)
System.out.println(students[i]); System.out.println(students[i]);
} // End of Main
// Sort By Age } // End of test class.
c1 = new studentbyage();
Arrays.sort(students,c1);
for(int i=0;i<students.length;i++)
System.out.println(students[i]);
Collections.sort(boxes);
X x1 = new B();
B b1 = (B) x1; A B C
SORTBOXBYAREA SORTBOXBYVOLUME
import java.util.*; // area() Volume() Methods
class BOX double area()
{ {
private double l,b,h; return 2*(l*b+b*h+h*l);
// Overloaded Constructors }
BOX(double a) double volume()
{ l=b=h=a; {
} return l*b*h;
BOX(double l,double b,double h) }
{ // isEquals() method
this.l=l; boolean isEqual(BOX other)
this.b=b; {
this.h=h; if(this.area() == other.area()) return
} true;
// Acessor Methods return false;
public double getL() /* OR
{ return l; if(area() == other.area()) return true
} return false;
public double getB() */
{ return b; }
}
public double getH() Cont …..
{ return h;
}
static boolean isEquals(BOX b1, BOX b2)
{
if(b1.area() == b2.area()) return true;
return false;
}
public String toString() NOTE :
{
String s1="length:"+l; BOX class is base class
String s2="width:"+b;
String s3="area:"+h;
whose references needs to
String s4="Area:"+area(); be sorted. It does not
String s5="Volume:"+volume(); implement either
return s1+s2+s3+s4+s5;
}
comparable or comparator
} // End of class BOX class
Cont …..
// Comparator class for Sorting by BOX references By length
J j = …..?
1. c = i C
2. j = c
<< class>>
3. i = j
First c = (C) I
Third I = (I) j
Exercise 2
1. I i = c;
2. J j = (J) i;
3. C d = (C) i; C
<< class>>
Second
Exercise 3
A
A a1 = new B();
a1.show(); // call to show() of B
a1 = new C();
a1.show(); // call to show() of C B C D
a1 = new D();
a1.show(); // call to show() of D Assume show() Method is
Overridden by sub
classes
DYNAMIC METHOD DISPATCH
class A class C extends A
{ {
void show() void show()
{
System.out.println("Hello This is {
show() in A"); System.out.println("Hello
} This is show() in C");
} }
class B extends A
}
{
void show() class D extends A
{ {
System.out.println("Hello This is void show()
show() in B"); {
}
} System.out.println("Hello
This is show() in D");
}
}
CONTINUED…..
class override2
{
public static void main(String args[])
{
A a1 = new A(); Hello This is show() in A
a1.show();
Hello This is show() in B
a1 = new B();
a1.show(); Hello This is show() in C
a1 = new C();
Hello This is show() in D
a1.show();
a1 = new D();
a1.show();
}
}
Method Overriding Cont..
1. Sub class can override the methods defined by the super class.
2. Overridden Methods in the sub classes should have same name,
same signature , same return type and may have either the same or
higher scope than super class method.
3. Java implements Run Time Polymorphism/ Dynamic Method
Dispatch by Method Overriding. [Late Binding]
4. Call to Overridden Methods is Resolved at Run Time.
5. Call to a overridden method is not decided by the type of reference
variable Rather by the type of the object where reference variable is
pointing.
6. While Overriding a Method, the sub class should assign either same
or higher access level than super class method.
class override3
{
public static void main(String args[])
{
A a1 = new B();
B b1 = (B) a1;
/*
A a1 = new B();
C c1 = (C) a1;
} Nested
Class
1.Nested has access to other members of the
enclosing class,even if they are declared private
2. Can be private, public, protected or friendly
access
Nested Class Types
Static nested classes
1. Static keyword applied for class declaration
2. Static nested class can use the instance fields/methods of the
outer class only through object reference.
3. Static nested class can be accessed
OuterClass.StaticNestedClass
4. To create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject = new
OuterClass.StaticNestedClass();
Nested Class Types cont..
• Non-Static nested classes
1. These nested classes do not have static keyword applied
2. Non-Static nested class can use the instance fields/methods of
the outer class directly.
3. To create an object for the non-static nested class, use this
syntax:
OuterClass.NestedClass nestedObject = Outerobjectreference.
new innerclass();
Inner class instance can
only exists inside
Outer class instance.
Example 1 [Non-static Nested Class]
class A class B
{ {
private int a; Outer Class int b; Nested
A(int a) B(int b) class with
{ { friendly
this.a =a; int c = b+10; access
} this.b = c;
void print() }
{ void show()
System.out.println("a=" {
+a); print();
} System.out.println("b="+b);
Call to }
print() of } // End of class B
outer class } // End of class A
Example 1 [Non-static Nested Class] cont….
class innertest1
{
public static void main(String args[]) Inner class Name
{ Outer class Reference
A a1 = new A(10);
To create an inner class instance
A.B b1 = a1.new B(100); for non-static classes you need an
outer class reference.
b1.show();
} Inner class Reference
}
Outer class Name
// STEP 1
// Create an Outer Instance first
a=20
A a1 = new A(20);
b=20
A.B b1 = a1.new B(-30);
this.b=-30
b1.show();
Outer b=10
// inner class object instantiation thru anonymous outer
// reference
A.B b2 = new A(30).new B(-40);
b2.show(); a=30
} b=20
} this.b=-40
Outer b=10
Static Inner class / Static Nested class Example
static class B
class A {
{ int b;
private int a; B(int b)
A(int a) Static inner
{
{ class
int c = b+10;
this.a =a; this.b = c;
} }
void print() void show()
{ {
System.out.println("a=" // print(); INVALID
+a); A a1 = new A(10);
} a1.print();
Static nested class can System.out.println("b="+b);
refere to outer members } } // End of class B
only through outer reference } // End of class A
Example cont….
class innertest10
{
public static void main(String args[])
{
A.B b1 = new A.B(100);
b1.show();
Instance of static
}
Inner class
}
Static Nested class Example 2
class A{
private int a;
protected static int b=10;
A(int a){
this.a=a;
}
public void show()
{
System.out.println("a="+a);
display();
}
public static void display()
{
System.out.println("b="+b);
}
}
Example 2 cont….
static class B {
private int a;
protected static int b=100;
B(int a){
this.a=a;
}
void show(){
// A.this.show(); // Won't work show() is non-static in outer
display(); // Will work as method is static in outer
System.out.println("a="+a);
// System.out.println("a="+A.this.a);
// Won't work a is non-static in outer
System.out.println("b="+b); // Will refer to its own b
System.out.println("A'sb="+A.b); // will refer to outer class B
new A(40).show();
// This is how you can call non static methods of outer
}
} // End of inner class B
} // End of class A
Example 2 cont….
class innerTest1
{
public static void main(String args[])
{
A.B b1 = new A.B(-30);
b1.show();
} D:\jdk1.3\bin>java innerTest1
} b=10
a=-30
b=100
A'sb=10
a=40
b=10
Local Inner classes [ Classes Within method
body] Class declared within a
method body.
Here method is show()
class A Local inner classes Can
{ not be declared as
private int a; public,private or
protected static int b=10; protected
A(int a)
{
this.a=a; 1. Class B is visible only in method
} show().
void show()
{ 2. It can be used within this show()
class B method only
{} 3. Local inner classes can only use
} final variables from its enclosing
} method.
4. However inner classes can refer
to its fields of enclosing class.
class A
{ D:\jdk1.3\bin>javac
private int a; innerTest2.java
protected static int b=10; innerTest2.java:23: local
A(int a) variable x is accessed from
{ within inner class;
this.a=a; to be declared final
} System.out.println("x="+x);
void show()
{
^
int x=10; 1 error
class B
{
private int b;
B(int b)
{
this.b=b;
} Reference for A’s a
void display()
{ Reference for B’s b
System.out.println("a="+a); Reference is wrong / errorneous
System.out.println("b="+b); ‘x’ is local variable inside the
System.out.println("x="+x); local method. Local classes can
} use only final fields from
} // End of class B
enclosing method
} // End of show() method
} // End of A class
class innertest class A
{ {
public static void private int a;
private int b;
main(String args[])
int c;
{ A(int a)
final int a1=10; {
this.a =a;
new A(20).show();
b = a+20;
print();
c = a+40;
}// End of main
}
static void print()
void show()
{
{
/*
System.out.println("a1="+a1);
A a1 = new A(30);
System.out.println("a="+a);
a1.show();
System.out.println("b="+b);
*/
System.out.println("c="+c);
System.out.println("Hello"
}
);
} //End of A
}
}
OUTPUT
E:\oop>java innertest
a1=10
a=20
b=40
c=60
Hello
Anonymous Inner classes