Java Tutorial: Prerequisites
Java Tutorial: Prerequisites
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
2. Object-oriented
3. Platform independent 9.Interpreted
4.Secured 10.High Performance
5. Robust 11. Multithreaded
6. Architecture neutral 12.Distributed
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
Eg.
private String title;
private String author;
private String publisher;
Rules For Instance Variable
Class variables are variables declared with in a class, outside any method, with
the static keyword.
Eg.
double 8 - - 123.86
Static variables are initialized only once , at the start of the execution . These
variables will be initialized first, before the initialization of any instance
variables.
A single copy to be shared by all instances of the class
A static variable can be accessed directly by the class name and doesn’t need
any object.
Syntax : <class-name>.<variable-name>.
Static variable can be final to make constant.
Syntax: public static final double RATE_OF_INT=15.5;
Static Variable Memory Diagram
Static Method
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a
class.
static method can access static data member and can change the value of it.
It is a method which belongs to the class and not to the object(instance)
A static method can access only static data. It can not access non-static data
(instance variables)
Static Method
1) string1.concat(string2);
1) "My name is ".concat("Zara");
2) "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.
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 length()
Returns the length of this string.
boolean matches(String regex) :-Tells whether or not this string matches
the given regular expression.
String replace(char oldChar, char newChar) :-Returns a new string
resulting from replacing all occurrences of oldChar in this string with
newChar.
String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular
expression with the given replacement.
String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular
expression with the given replacement.
String trim() :-Returns a copy of the string, with leading and trailing
whitespace omitted.
static String valueOf([int][float][…….] x) :-Returns the string
representation of the passed data type argument.
Inheritance can be defined as the process where one object acquires the
properties of another.
Inheritance is a mechanism in which one object
acquires all the properties and behaviours of parent
object.
The idea behind inheritance is that you can create new classes that are built
upon existing classes.
When you inherit from an existing class, you reuse (or inherit) methods and
fields.
Inheritance represents the IS-A relationship.
extends keyword is used to achieve inheritance.
Inheritance Example
If you are overriding any method, overriden method (i.e. declared in subclass)
must not be
more restrictive.
Access Levels are in sequence of
1)Private
2)Default
3)Protected
4)Public
Example
Cont.. Next page
Covariant Return Type
The covariant return type specifies that the return type may vary in the same
direction as the subclass.
Before Java5, it was not possible to override any method by changing the
return type.
But now, since Java5,it is possible to override method by changing the return
type if subclass overrides any method whose return type is Non-Primitive but
it changes its return type to subclass type.
Let's take a simple example:
super keyword
The super is a reference variable that is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is
created implicitely because it is referred by super reference variable.
Usage of super Keyword:-
1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.
Restricting Inheritance
Parent
Inherited
capability
Child
Final Members: A way for Preventing Overriding of Members in
Subclasses
Shape
Circle Rectangle
The Shape Abstract Class
<<Interface>>
Speaker
speak()
interface Speaker {
public void speak( );
}
Implementing Interfaces
• Interfaces are used like super-classes who properties are inherited by
classes. This is achieved by creating a class that implements the given
interface as follows:
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
class A DYNAMIC METHOD DISPATCH
{ 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 }
{ class D extends A
void show() {
{ void show()
System.out.println("Hello This {
is 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(); Hello This is show() in C
a1.show(); Hello This is show() in D
a1 = new C();
a1.show();
a1 = new D();
a1.show();
}
}
class override3
{
public static void main(String args[])
{
A a1 = new B();
B b1 = (B) a1;
/*
A a1 = new B();
C c1 = (C) a1;
class B extends A{ NO
int show(){
System.out.println("Hi"); CODE WILL
return 10; COMPILE & RUN
} SUCESSFULLY
}
class A{ What’s Wrong Here
static int show(){
System.out.println("class A");
return 0;
}
}
sample.java:12: show() in B
class B extends A{ cannot override show() in A;
void show(){ overridden method is static
System.out.println("class B"); void show()
} ^
} 1 error
Nested Classes
Java programming language allows you to
define a class within another class
Enclosing
class OuterClass Class OR
{ ... Outer Class
A nested class is a member
class NestedClass { ... of
} its enclosing class
}
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();
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 for
A.B b1 = a1.new B(100); non-static classes you need an outer
class reference.
b1.show();
} Inner class Reference
}
Outer class Name
// STEP 1
// Create an Outer Instance first
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()
Local inner classes Can not be declared as
class A public,private or protected
{
private int a;
protected static int b=10;
A(int a)
1.Class B is visible only in method show().
{
2.It can be used within this show() method only
this.a=a;
3.Local inner classes can only use final variables
}
from its enclosing method.
void show()
4.However inner classes can refer to its fields of
{
enclosing class.
class B
{}
}
}
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)
{ Reference for A’s a
this.b=b;
} Reference for B’s b
void display()
{ Reference is wrong / errorneous
System.out.println("a="+a); ‘x’ is local variable inside the local
System.out.println("b="+b); method. Local classes can use only
System.out.println("x="+x); final fields from enclosing method
}
} // End of class B
E:\oop>java innertest
a1=10
a=20
b=40
c=60
Hello
Anonymous Inner classes
X x1 = new X()
{ Anonymous inner class implementing an interface
public int sum(int a,int b)
{
return a+b;
}
public int mul(int a,int b)
{
return a*b;
}
};
System.out.println(x1.sum(10,20));
System.out.println(x1.mul(10,20));
}// End of main
}// End of innertest2