Core Java
Core Java
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
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
Modifier Class Class Methods Method
Variables Variables
public
private
protected
default
final
abstract
strictfp
transient
synchronized
native
volatile
static
Modifier Example
Access Control Modifiers
Java provides a number of access modifiers to set access
levels for classes, variables, methods and constructors. The four
access levels are:
Default:-Visible to the package. No modifiers are needed.
Private:-Visible to the class only .
Public:-Visible to the world.
Protected:-Visible to the package and all subclasses.
Non Access Modifiers
Java provides a number of non-access modifiers to achieve
many other functionality.
The static modifier for creating class methods and variables
The final modifier for finalizing the implementations of classes,
methods, and variables.
The abstract modifier for creating abstract classes and
methods.
The synchronized and volatile modifiers, which are used for
threads.
Naming convention
A naming convention is a rule to follow as you decide what to
name your identifiers (e.g. class, package,variable, method, etc.),
but it is not mandatory to follow that is why it is known as
convention not rule.
Advantage:
By using standard Java naming conventions they make their
code easier to read for themselves and for other programmers.
Readability of Java code is important because it means less time is
spent trying to figure out what the code does.
Class Name should begin with uppercase letter and be a noun
e.g.String,System,Thread etc.
Interface Name should begin with uppercase letter and be an adjective
(whereever possible), e.g.Runnable,ActionListener etc.
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.
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.
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
class A
{ DYNAMIC METHOD DISPATCH
void show() class C extends A
{ {
System.out.println("He void show()
llo This is show() in {
A"); System.out.println("H
} ello This is show() in
} C");
class B extends A }
{ }
void show() class D extends A
{ {
System.out.println("He void show()
llo This is show() in {
B"); System.out.println("H
} ello This is show() in
} D");
} CONTINUED…..
class override2
{
public static void main(String
args[])
{ Hello This is show() in A
A a1 = new A(); Hello This is show() in B
a1.show(); Hello This is show() in C
a1 = new B(); Hello This is show() in D
a1.show();
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()
class B extends A{ in B cannot override
void show(){ show() in A; overridden
System.out.println("class B");method is static
} 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();
}
Call to System.out.println("b="+b);
print() of }
outer class } // End of class B
} // End of class A
Example 1 [Non-static Nested Class]
cont….
class innertest1
{
Inner class Name
public static void main(String args[])
{ Outer class Reference
A a1 = new A(10);
To create an inner class
A.B b1 = a1.new B(100); instance for non-static classes
you need an outer class
b1.show();
reference.
} Inner class Reference
}
Outer class Name
// STEP 1
// Create an Outer Instance first
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( // print(); INVALID
"a="+a); A a1 = new A(10);
} a1.print();
Static nested class can System.out.println("b="+b);
refere to outer } } // End of class B
members only through } // End of class A
outer reference
Example cont….
class innertest10
{
public static void main(String
args[])
{
A.B b1 = new A.B(100);
Instance of
b1.show();
static Inner
}
class
}
Static Nested class
class A{
private int a;
Example 2
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 public,private or
private int a; protected
protected static int b=10;
A(int a)
1.Class B is visible only in method
{
show().
this.a=a;
2.It can be used within this show()
}
method only
void show()
3.Local inner classes can only use final
{
variables from its enclosing method.
class B
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)
{ Reference for A’s a
this.b=b;
} Reference for B’s b
void display()
{ Reference is wrong /
System.out.println("a="+a); errorneous
System.out.println("b="+b); ‘x’ is local variable inside
System.out.println("x="+x); the local method. Local
} classes can use only final
} // End of class B fields from enclosing
method
} // End of show() method
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
X x1 = new X()
{ Anonymous inner class implementing an
public int sum(int a,int b)
interface
{
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