Java: Origins and Evolution
Java: Origins and Evolution
Java was originally designed for interactive television, but it was too advanced technology for
the digital cable television industry at the time. The history of Java starts with the Green Team.
Java team members (also known as Green Team), initiated this project to develop a language for
digital devices such as set-top boxes, televisions, etc. However, it was best suited for internet
programming. Later, Java technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented,
Interpreted, and Dynamic". Java was developed by James Gosling, who is known as the father of
Java, in 1995. James Gosling and his team members started the project in the early '90s.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.
Following are given significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
June 1991. The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in electronic appliances like set-top
boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
Why Java was named as "Oak"?
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the
U.S.A., France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
7) Why had they chose the name Java for Java language? The team gathered to choose a new name.
The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted
something that reflected the essence of the technology: revolutionary, dynamic, lively, cool,
unique, and easy to spell, and fun to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so
unique, most of the team members preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a
kind of espresso bean. Java name was chosen by James Gosling while having a cup of coffee
nearby his office.
Many java versions have been released till now. The current stable release of Java is Java SE 10.
Since Java SE 8 release, the Oracle corporation follows a pattern in which every even version is
release in March month and an odd version released in September month.
OBJECT-ORIENTED PROGRAMMING
Object-oriented programming (OOP) is a programming paradigm based on the concept of
“objects”, which may contain data, in the form of fields, often known as attributes; and code,
in the form of procedures, often known as methods.
List of object-oriented programming languages
C# J# Scala
Abstraction
Abstraction is one of the key concepts of object-oriented programming (OOP) languages.
Its main goal is to handle complexity by hiding unnecessary details from the user. This en-
ables the user to implement more complex logic on top of the provided abstraction without
understanding about all the hidden complexity.
For example, people do not think of a car as a set of tens of thousands of individual parts.
They think of it as a well-defined object with its own unique behavior. This abstraction allows
people to use a car to drive to the desired location without worrying about the complexity of
the parts that form the car. They can ignore the details of how the engine, transmission, and
braking systems work. Instead, they are free to utilize the object as a whole.
For example, a Dog is part of the classification Mammal, which in turn is part of the Ani-
mal class. Without the use of hierarchies, each object would need to define all of its charac-
teristics explicitly. However, by use of inheritance, an object need only define those qualities
that make it unique within its class. It can inherit its general attributes from its parent. Thus,
inheritance makes it possible for one object to be a specific instance of a more general case.
Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface
to be used for a general class of actions. The specific action is determined by the exact nature
of the situation.
For eg, a dog’s sense of smell is polymorphic. If the dog smells a cat, it will bark and run
after it. If the dog smells its food, it will salivate and run to its bowl. The same sense of smell
is at work in both situations. The difference is what is being smelled, that is, the type of data
being operated upon by the dog’s nose.
Consider a stack (which is a last-in, first-out LIFO list). We might have a program that re-
quires three types of stacks. One stack is used for integer values, one for floating-point values,
and one for characters. The algorithm that implements each stack is the same, even though
the data being stored differs.
CHARACTERISTICS OF JAVA
Simple :
• Java is Easy to write and more readable.
• Java has a concise, cohesive set of features that makes it easy to learn and use.
• Most of the concepts are drawn from C++, thus making Java learning simpler.
Secure :
• Java program cannot harm other system thus making it secure.
• Java provides a secure means of creating Internet applications.
• Java provides secure way to access web applications.
Portable :
• Java programs can execute in any environment for which there is a Java run-time
system.
• Java programs can run on any platform (Linux, Window, Mac)
• Java programs can be transferred over world wide web (e.g applets)
Object-oriented :
• Java programming is object-oriented programming language.
• Like C++, java provides most of the object oriented features.
• Java is pure OOP Language. (while C++ is semi object oriented)
Robust :
• Java encourages error-free programming by being strictly typed and performing run-
time checks.
Multithreaded :
• Java provides integrated support for multithreaded programming.
Architecture-neutral :
• Java is not tied to a specific machine or operating system architecture.
• Java is machine independent.
Interpreted :
• Java supports cross-platform code through the use of Java bytecode.
• Bytecode can be interpreted on any platform by JVM (Java Virtual Machine).
High performance :
• Bytecodes are highly optimized.
• JVM can execute bytecodes much faster .
Distributed :
• Java is designed with the distributed environment.
• Java can be transmitted over internet.
Dynamic :
• Java programs carry substantial amounts of run-time type information with them that
is used to verify and resolve accesses to objects at run time.
JAVA RUNTIME ENVIRONMENT (JRE)
The Java Runtime Environment (JRE) is a set of software tools for development of Java
applications. It combines the Java Virtual Machine (JVM), platform core classes and support-
ing libraries.
JRE is part of the Java Development Kit (JDK), but can be downloaded separately. JRE
was originally developed by Sun Microsystems Inc., a wholly-owned subsidiary of Oracle
Corporation.
JRE consists of the following components:
Name of the component Elements of the component
Deployment technologies Deployment
Java Web Start
Java Plug-in
User interface toolkits Abstract Window Toolkit (AWT)
Swing
Java 2D
Accessibility
Image I/O
Print Service
Sound
Drag and Drop (DnD)
Input methods.
Integration libraries Interface Definition Language (IDL)
Java Database Connectivity (JDBC)
Java Naming and Directory Interface (JNDI)
Remote Method Invocation (RMI)
Remote Method Invocation Over Internet
Inter-Orb Protocol (RMI-IIOP)
Scripting.
base libraries International support
Input/Output (I/O)
Eextension mechanism
Beans
Java Management Extensions (JMX)
Java Native Interface (JNI)
Math
Networking
Override Mechanism
Security
Serialization and Java for XML Processing
(XML JAXP).
Lang and util base libraries lang and util
Management
Versioning
Zip
Instrument
Reflection
Collections
Concurrency
Java Archive (JAR)
Logging
Preferences API
Ref Objects
Regular Expressions.
Java Virtual Machine (JVM) Java HotSpot Client
Server Virtual Machines
JAVA VIRTUAL MACHINE (JVM)
The JVM is a program that provides the runtime environment necessary for Java pro-
grams to execute. Java programs cannot run without JVM for the appropriate hardware and
OS platform.
Java programs are started by a command line, such as:
java <arguments> <program name>
This brings up the JVM as an operating system process that provides the Java runtime
environment. Then the program is executed in the context of an empty virtual machine.
When the JVM takes in a Java program for execution, the program is not provided as
Java language source code. Instead, the Java language source must have been converted (or
compiled) into a form known as Java bytecode. Java bytecode must be supplied to the JVM
in a format called class files. These class files always have a .class extension.
The JVM is an interpreter for the bytecode form of the program. It steps through one
bytecode instruction at a time. It is an abstract computing machine that enables a computer
to run a Java program.
Class Name
Static Attributes
Dynamic Behaviors
Abstraction
Abstraction refers to the quality of dealing with ideas rather than events. It basically deals
with hiding the details and showing the essential things to the user.
We all know how to turn the TV on, but we don’t need to know how it works in order to
enjoy it.
Abstraction means simple things like objects, classes, and variables represent more com-
plex underlying code and data. It avoids repeating the same work multiple times. In java, we
use abstract class and interface to achieve abstraction.
Abstract class:
Abstract class in Java contains the ‘abstract’ keyword. If a class is declared abstract, it
cannot be instantiated. So we cannot create an object of an abstract class. Also, an abstract
class can contain abstract as well as concrete methods.
To use an abstract class, we have to inherit it from another class where we have to provide
implementations for the abstract methods there itself, else it will also become an abstract
class.
Interface:
Interface in Java is a collection of abstract methods and static constants. In an interface,
each method is public and abstract but it does not contain any constructor. Along with ab-
straction, interface also helps to achieve multiple inheritance in Java.
So an interface is a group of related methods with empty bodies.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
It means to hide our data in order to make it safe from any modification.
The best way to understand encapsulation is to look at the example of a medical capsule,
where the drug is always safe inside the capsule. Similarly, through encapsulation the meth-
ods and variables of a class are well hidden and safe.
A java class is the example of encapsulation.
Encapsulation can be achieved in Java by:
• Declaring the variables of a class as private.
• Providing public setter and getter methods to modify and view the variables values.
Inheritance
This is a special feature of Object Oriented Programming in Java. It lets programmers
create new classes that share some of the attributes of existing classes.
For eg, a child inherits the properties from his father.
Similarly, in Java, there are two classes:
1. Parent class (Super or Base class)
2. Child class (Subclass or Derived class)
A class which inherits the properties is known as ‘Child class’ whereas a class whose
properties are inherited is known as ‘Parent class’.
Inheritance is classified into 4 types:
Single Inheritance
It enables a derived class to inherit the properties and behavior from a single parent
class.
Here, Class A is a parent class and Class B is a child class which inherits the properties
and behavior of the parent class.
Multilevel Inheritance
When a class is derived from a class which is also derived from another class, i.e. a class
having more than one parent class but at different levels, such type of inheritance is called
Multilevel Inheritance.
Here, class B inherits the properties and behavior of class A and class C inherits the prop-
erties of class B. Class A is the parent class for B and class B is the parent class for C. So, class
C implicitly inherits the properties and methods of class A along with Class B.
Hierarchical Inheritance
When a class has more than one child class (sub class), then such kind of inheritance is known
as hierarchical inheritance.
Here, classes B and C are the child classes which are inheriting from the parent class A.
Hybrid Inheritance
Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance.
Since multiple inheritance is not supported in Java as it leads to ambiguity, this type of inheri-
tance can only be achieved through the use of the interfaces.
Here, class A is a parent class for classes B and C, whereas classes B and C are the parent
classes of D which is the only child class of B and C.
Polymorphism
Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means
forms. It is the ability of a variable, function or object to take on multiple forms. In other
words, polymorphism allows us to define one interface or method and have multiple imple-
mentations.
For eg, Bank is a base class that provides a method rate of interest. But, rate of interest
may differ according to banks. For example, SBI, ICICI and AXIS are the child classes that
provide different rates of interest.
Polymorphism in Java is of two types:
• Run time polymorphism
• Compile time polymorphism
Run time polymorphism:
In Java, runtime polymorphism refers to a process in which a call to an overridden method
is resolved at runtime rather than at compile-time. Method overriding is an example of run
time polymorphism.
Rules:
The package statement should be the first line in the source file.
•
There can be only one package statement in each source file.
•
If a package statement is not used, the class, interfaces, enumerations, and annotation
• types will be placed in the current default package.
It is a good practice to use names of packages with lower case letters to avoid any
• conflicts with the names of classes and interfaces.
Following package example contains interface named animals:
import packagename;
or
import packagename.* ;
We may import a single class or all the classes belonging to a package.
• To import a single class, we specify the name of the class
• To import all classes, we specify *.
Examples of the import statement:
Statement in Java Purpose
import [Link]; imports the definition of the MyClass
class that is defined in the mypackage
package.
import [Link]. imports the definition of EmpClass
EmpClass; belonging to the [Link].
[Link] package.
import [Link].*; imports all the classes belonging to the
[Link] package.
Part 3: Zero or More top-level Declarations
The Java source file should have one and only one public class. The class name which is
defined as public should be the name of Java source file along with .java extension.
Source File Declaration Rules
• There can be only one public class per source file.
• A source file can have multiple non-public classes.
• The public class name should be the name of the source file which should have
.java extension at the end.
• For eg, if the class name is public class Employee{}, then the source file should be
as [Link].
• If the class is defined inside a package, then the package statement should be the first
statement in the source file.
• If import statements are present, then they must be written between the package
statement and the class declaration. If there are no package statements, then the
import statement should be the first line in the source file.
• Import and package statements will imply to all the classes present in the source file.
It is not possible to declare different import and/or package statements to different
classes in the source file.
COMPILATION
In Java, programs are not compiled into executable files. Java source code is compiled
into bytecode using javac compiler. The bytecodes are platform-independent instructions for
the Java VM. They are saved on the disk with the file extension .class. When the program
is to be run, the bytecode is converted into the machine code using the just-in-time (JIT) com-
piler. It is then fed to the memory and executed.
Java code needs to be compiled twice in order to be executed:
1. Java programs need to be compiled to bytecode.
2. When the bytecode is run, it needs to be converted to machine code.
The Java classes / bytecode are compiled to machine code and loaded into memory by the
JVM when needed for the first time.
Compiling the Program
The Java compiler is invoked at the command line with the following syntax:
javac [Link]
Interpreting and Running the Program
Once the java program successfully compiles into Java bytecodes, we can interpret and
run applications on any Java VM, or interpret and run applets in any Web browser with a Java
VM built in such as Netscape or Internet Explorer. Interpreting and running a Java program
means invoking the Java VM byte code interpreter, which converts the Java byte codes to
platform-dependent machine codes so your computer can understand and run the program.
The Java interpreter is invoked at the command line with the following syntax:
java ExampleProgram
Quick compilation procedure
To execute the first Java program, follow the steps:
1. Open text editor. For example, Notepad or Notepad++ on Windows; Gedit, Kate or
SciTE on Linux; or, XCode on Mac OS, etc.
2. Type the java program in a new text document.
3. Save the file as [Link].
4. Next, open any command-line application. For example, Command Prompt on
Windows; and, Terminal on Linux and Mac OS.
5. Compile the Java source file using the command: javac [Link]
6. Once the compiler returns to the prompt, run the application using the following
command:
java HelloWorld
FUNDAMENTAL PROGRAMMING STRUCTURES IN JAVA
Java Comments
The java comments are statements that are not executed by the compiler and interpreter.
The comments can be used to provide information or explanation about the variable, method,
class or any statement. It can also be used to hide program code for specific time.
Types of Java Comments
There are 3 types of comments in java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment
1) Java Single Line Comment
The single line comment is used to comment only one line. A single-line comment begins
with a // and ends at the end of the line.
Syntax Example
//Comment //This is single line comment
2) Java Multi Line Comment
This type of comment must begin with /* and end with */. Anything between these two
comment symbols is ignored by the compiler. A multiline comment may be several lines
long.
Syntax Example
/*Comment starts /* This is a
continues comment */
Commnent ends*/
* This
*such as <h1> */
*comment ends*/
DATA TYPES
Java is a statically typed and also a strongly typed language. In Java, each type of data
(such as integer, character, hexadecimal, etc. ) is predefined as part of the programming lan-
guage and all constants or variables defined within a given program must be described with
one of the data types.
Data types represent the different values to be stored in the variable. In java, there are two
categories of data types:
o Primitive data types
o Non-primitive data types
VARIABLES
A variable is the holder that can hold the value while the java program is executed. A
variable is assigned with a datatype. It is name of reserved area allocated in memory. In
other words, it is a name of memory location. There are three types of variables in java: local,
instance and static.
A variable provides us with named storage that our programs can manipulate. Each vari-
able in Java has a specific type, which determines the size and layout of the variable’s mem-
ory; the range of values that can be stored within that memory; and the set of operations that
can be applied to the variable.
Before using any variable, it must be declared. The following statement expresses the
basic form of a variable declaration –
datatype variable [ = value][, variable [ = value] ...] ;
Here data type is one of Java’s data types and variable is the name of the variable. To de-
clare more than one variable of the specified type, use a comma-separated list.
Example
int a, b, c; // Declaration of variables a, b, and c.
int a = 20, b = 30; // initialization
byte B = 22; // Declaratrion initializes a byte type variable B.
Types of Variable
There are three types of variables in java:
• local variable
• instance variable
• static variable
Local Variable
• Local variables are declared inside the methods, constructors, or blocks.
• Local variables are created when the method, constructor or block is entered
• Local variable will be destroyed once it exits the method, constructor, or block.
• Local variables are visible only within the declared method, constructor, or block.
• Local variables are implemented at stack level internally.
• There is no default value for local variables, so local variables should be declared and
an initial value should be assigned before the first use.
• Access specifiers cannot be used for local variables.
Instance Variable
• A variable declared inside the class but outside the method, is called instance variable.
Instance variables are declared in a class, but outside a method, constructor or any
block.
• A slot for each instance variable value is created when a space is allocated for an
object in the heap.
• Instance variables are created when an object is created with the use of the keyword
‘new’ and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object’s state that must be present
throughout the class.
• Instance variables can be declared in class level before or after use.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block in the
class. It is recommended to make these variables as private. However, visibility for
subclasses can be given for these variables with the use of access modifiers.
• Instance variables have default values.
○ numbers, the default value is 0,
○ Booleans it is false,
○ Object references it is null.
• Values can be assigned during the declaration or within the constructor.
• Instance variables cannot be declared as static.
• Instance variables can be accessed directly by calling the variable name inside the class.
However, within static methods (when instance variables are given accessibility), they
should be called using the fully qualified name. [Link].
Static variable
• Class variables also known as static variables are declared with the static keyword in
a class, but outside a method, constructor or a block.
• Only one copy of each class variable per class is created, regardless of how many
objects are created from it.
• Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never
change from their initial value.
• Static variables are stored in the static memory. It is rare to use static variables other
than declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program
stops.
• Visibility is same as instance variables. However, most static variables are declared
public since they must be available for users of the class.
• Default values are same as instance variables.
○ numbers, the default value is 0;
○ Booleans, it is false;
○ Object references, it is null.
• Values can be assigned during the declaration or within the constructor. Additionally,
values can be assigned in special static initializer blocks.
• Static variables cannot be local.
• Static variables can be accessed by calling with the class name ClassName.
VariableName.
• When declaring class variables as public static final, then variable names (constants)
are all in upper case. If the static variables are not public and final, the naming syntax
is the same as instance and local variables.
DEFINING CLASSES IN JAVA
A class is an entity that determines how an object will behave and what the object will
contain. A class is the basic building block of an object-oriented language such as Java. It
is acting as a template that describes the data and behavior associated with instances of that
class.
When you instantiate a class means creating an object. The class contains set of variables
and methods.
The data associated with a class or object is stored in variables; the behavior associated
with a class or object is implemented with methods. A class is a blueprint from which indi-
vidual objects are created.
class MyClass {
// field,
//constructor, and
// method declarations
}
Example:
class Myclass{
public static void main(String[] args)
{
[Link](“Hello World!”); //Display the string.
}
}
The keyword class begins the class definition for a class named name. The variables and
methods of the class are embraced by the curly brackets that begin and end the class definition
block. The “Hello World” application has no variables and has a single method named main.
In Java, the simplest form of a class definition is
class name {
...
}
In general, class declarations can include these components, in order:
1. Modifiers : A class can be public or has default access.
2. Class name: The name should begin with a initial letter.
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class,
if any, preceded by the keyword implements. A class can implement more than one
interface.
5. Body: The class body surrounded by braces, { }.
CONSTRUCTORS
Every class has a constructor. If the constructor is not defined in the class, the Java com-
piler builds a default constructor for that class. While a new object is created, at least one
constructor will be invoked. The main rule of constructors is that they should have the same
name as the class. A class can have more than one constructor.
Constructors are used for initializing new objects. Fields are variables that provide the
state of the class and its objects, and methods are used to implement the behavior of the class
and its objects.
Rules for writing Constructor
• Constructor(s) of a class must have same name as the class name in which it resides.
• A constructor in Java cannot be abstract, final, static and synchronized.
• Access modifiers can be used in constructor declaration to control its access i.e which
other class can call the constructor.
Following is an example of a constructor −
Example
public class myclass {
public myclass() { // Constructor
}
public myclass(String name) {
// This constructor has one parameter, name.
}
}
Types of Constructors
There are two type of constructor in Java:
1. No-argument constructor:
A constructor that has no parameter is known as default constructor.
If the constructor is not defined in a class, then compiler creates default con-
structor (with no arguments) for the class. If we write a constructor with ar-
guments or no-argument then compiler does not create default constructor.
Default constructor provides the default values to the object like 0, null etc. depending on the
type.
// Java Program to illustrate calling a no-argument constructor
import [Link].*;
class myclass
{
int num;
String name;
// this would be invoked while object of that class created.
myclass()
{
[Link](“Constructor called”);
}
}
class myclassmain
{
public static void main (String[] args)
{
// this would invoke default constructor.
myclass m1 = new myclass();
// Default constructor provides the default values to the object like 0, null
[Link]([Link]);
[Link]([Link]);
}
}
2. Parameterized Constructor
A constructor that has parameters is known as parameterized constructor. If we want to
initialize fields of the class with your own values, then use parameterized constructor.
Assignment Operators
The following are the assignment operators supported by Java.
Operator Description Example
=
C = A + B will as-
(Simple Assigns values from right side oper- sign value of
assignment ands to left side operand.
A + B into C
operator)
+=
(Add AND It adds right operand to the left operand C += A is equiva-
assignment and assigns the result to left operand. lent to C = C + A
operator)
-=
(Subtract It subtracts right operand from the left
C -= A is equiva-
AND operand and assigns the result to left
lent to C = C – A
assignment operand.
operator)
*=
(Multiply It multiplies right operand with the left
C *= A is equiva-
AND operand and assigns the result to left
lent to C = C * A
assignment operand.
operator)
/=
(Divide It divides left operand with the right
C /= A is equiva-
AND operand and assigns the result to left
lent to C = C / A
assignment operand.
operator)
%=
(Modulus It takes modulus using two operands C %= A is equiva-
AND assign- and assigns the result to left operand. lent to C = C % A
ment opera-
tor)
C <<= 2 is same as
<<= Left shift AND assignment operator.
C = C << 2
C >>= 2 is same as
>>= Right shift AND assignment operator.
C = C >> 2
C &= 2 is same as
&= Bitwise AND assignment operator.
C=C&2
{
public static void main(String[] args)
{
int a = 20, b = 10, c, d, e = 10, f = 4, g = 9;
c = b;
[Link](“Value of c = “ + c);
a += 1;
b -= 1;
e *= 2;
f /= 2;
[Link](“a, b, e, f = “ +
a + “,” + b + “,” + e + “,” + f);
}
}
Ternary Operator
Conditional Operator ( ? : )
Since the conditional operator has three operands, it is referred as the ternary operator.
This operator consists of three operands and is used to evaluate Boolean expressions. The
goal of the operator is to decide, which value should be assigned to the variable. The operator
is written as –
variable x = (expression) ? value if true : value if false
Following is an example −
Example:
public class example
{
public static void main(String args[])
{
int a, b;
a = 10;
b = (a == 0) ? 20: 30;
[Link]( “b : “ + b );
}
}
Unary Operators
Unary operators use only one operand. They are used to increment, decrement or negate
a value.
Operator Description
- Unary minus negating the values
+ Unary plus converting a negative value to positive
++ :Increment operator incrementing the value by 1
— : Decrement operator decrementing the value by 1
! : Logical not operator inverting a boolean value
// Java program to illustrate unary operators
public class operators
{
public static void main(String[] args)
{
int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;
boolean condition = true;
c = ++a;
[Link](“Value of c (++a) = “ + c);
c = b++;
[Link](“Value of c (b++) = “ + c);
c = --d;
[Link](“Value of c (--d) = “ + c);
c = --e;
[Link](“Value of c (--e) = “ + c);
[Link](“Value of !condition =” + !condition);
}
}
Precedence of Java Operators
Operator precedence determines the grouping of operands in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator −
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 pro-
gram.
The simple if statement has the following syntax:
if (<conditional expression>)
<statement action>
The following program explains the if statement.
public class programIF{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
[Link](“a > b”);
if (a < b)
[Link](“b < a”);
}
}
The If-else Statement
The if/else statement is an extension of the if statement. If the condition in the if statement
fails, the statements in the else block are executed. The if-else statement has the following
syntax:
if (<conditional expression>)
<statement action>
else
<statement action>
Example:
Program to compute addition of two numbers (no argument and with return value)
[Link](“Sum:”+[Link](a,b));
}
}
Sample Output:
Sum:30
Example:
Pass by value
class Swapper{
int a;
int b;
Swapper(int x, int y) // constructor to initialize variables
{
a = x;
b = y;
}
void swap(int x, int y) // method to interchange values
{
int temp; temp = x;
x=y;
y=temp;
}
}class Main{
public static void main(String[] args){
Swapper obj = new Swapper(10, 20); // create object
[Link](“Before swapping: a=”+obj.a+” b=”+obj.b);
[Link](obj.a,obj.b); // call the method by passing class object as parameter
[Link](“Before swapping: a=”+obj.a+” b=”+obj.b);
}
}
Sample Output:
Before swapping: a=10 b=20
After swapping: a=10 b=20
Here, to call method swap() first create an object for class Swapper. Then the method is
called by passing object values a and b as input parameters. As these values are scalar, the
parameters are passed using pass by value technique. So the changes carried out inside the
method are not reflected in original value of a and b.
Pass by Reference
In pass-by-reference, reference (address) of the actual parameters is passed to the local
parameters in the method definition. So, the changes performed on local parameters are re-
flected on the actual parameters.
Example:
class Swapper{
int a;
int b;
Swapper(int x, int y) // constructor to initialize variables
{
a = x;
b = y;
}
void swap(Swapper ref) // method to interchange values
{
int temp = ref.a;
ref.a = ref.b;
ref.b = temp;
}
}
class PassByRef{
public static void main(String[] args){
Swapper obj = new Swapper(10, 20); // create object
[Link](“Before swapping: a=”+obj.a+” b=”+obj.b);
}
}
public class Main {
public static void main(String[] args) {
MethodOverload obj=new MethodOverload();
[Link](); // call all versions of add()
[Link](1,2);
[Link](1,2,3);
[Link](12.3,23.4);
}
}
Sample Output:
No parameters
Sum:3
Sum:6
Sum:35.7
Here, add() is overloaded four times. The first version takes no parameters, second takes
two integers, third takes three integers and fourth accepts two double parameter.
CONSTRUCTOR OVERLOADING
Like methods, we can overload constructors for creating objects in different ways.
Compiler differentiates constructors on the basis of numbers of parameters, types of the
parameters and order of the parameters.
Creating an Object
The class provides the blueprints for objects. The objects are the instances of the class. In
Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class −
• Declaration − A variable declaration with a variable name with an object type.
• Instantiation − The ‘new’ keyword is used to create the object.
• Initialization − The ‘new’ keyword is followed by a call to a constructor. This call
initializes the new object.
METHODS IN JAVA
A method is a collection of statement that performs specific task. In Java, each method is
a part of a class and they define the behavior of that class. In Java, method is a jargon used
for method.
Advantages of methods
• Program development and debugging are easier
• Increases code sharing and code reusability
• Increases program readability
• It makes program modular and easy to understanding
• It shortens the program length by reducing code redundancy
Types of methods
There are two types of methods in Java programming:
• Standard library methods (built-in methods or predefined methods)
• User defined methods
Standard library methods
The standard library methods are built-in methods in Java programming to handle tasks
such as mathematical computations, I/O processing, graphics, string handling etc. These
methods are already defined and come along with Java class libraries, organized in packages.
In order to use built-in methods, we must import the corresponding packages. Some of library
methods are listed below.
Packages Library Methods Descriptions
[Link] acos() Computes arc cosine of the argument
All maths related methods exp() Computes the e raised to given power
are defined in this class
abs() Computes absolute value of argument
log() Computes natural logarithm
sqrt() Computes square root of the argument
pow() Computes the number raised to given
power
[Link] charAt() Returns the char value at the specified
index.
All string related methods concat()
are defined in this class compareTo() Concatenates two string
Example:
Program to compute square root of a given number using built-in method.
public class MathEx {
public static void main(String[] args) {
[Link](“Square root of 14 is: “ + [Link](14));
}
}
Sample Output:
Square root of 14 is: 3.7416573867739413
User-defined methods
The methods created by user are called user defined methods.
Every method has the following.
• Method declaration (also called as method signature or method prototype)
• Method definition (body of the method)
• Method call (invoke/activate the method)
Method Declaration
The syntax of method declaration is:
Syntax:
return_type method_name(parameter_list);
Here, the return_type specifies the data type of the value returned by method. It will be
void if the method returns nothing. method_name indicates the unique name assigned to the
method. parameter_list specifies the list of values accepted by the method.
Method Definition
Method definition provides the actual body of the method. The instructions to complete a
specific task are written in method definition. The syntax of method is as follows:
Syntax:
modifier return_type method_name(parameter_list){
// body of the method
}
Here,
Modifier – Defines the access type of the method i.e accessibility re-
gion of method in the application
return_type – Data type of the value returned by the method or void if
method returns nothing
method_name – Unique name to identify the method. The name must follow
the rules of identifier
parameter_list – List of input parameters separated by comma. It must be
like
datatype parameter1,datatype parameter2,……
List will be empty () in case of no input parameters.
method body – block of code enclosed within { and } braces to perform
specific task
The first line of the method definition must match exactly with the method prototype. A
method cannot be defined inside another method.
Method Call
A method gets executed only when it is called. The syntax for method call is.
Syntax:
method_name(parameters);
When a method is called, the program control transfers to the method definition where
the actual code gets executed and returns back to the calling point. The number and type of
parameters passed in method call should match exactly with the parameter list mentioned in
method prototype.
Example:
Method name
class Addition{
Modifier
public int add(int a,int b){
Return type Body of the method
return(a+b);
}
Parameter list
}
class Main{
Method call
Method return public static void main(String args[]){
int sum=0,a=1,b=12;
Addition obj=new Addition();
sum=[Link](a,b);
[Link](“Sum:”+sum);
}
}
STATIC KEYWORD
The static keyword indicates that the member belongs to the class instead of a specific
instance. It is used to create class variable and mainly used for memory management. The
static keyword can be used with:
• Variable (static variable or class variable)
• Method (static method or class method)
• Block (static block)
• Nested class (static class)
• import (static import)
Static variable
Variable declared with keyword static is a static variable. It is a class level variable com-
monly shared by all objects of the class.
• Memory allocation for such variables only happens once when the class is loaded in
the memory.
• scope of the static variable is class scope ( accessible only inside the class)
• lifetime is global ( memory is assigned till the class is removed by JVM).
• Automatically initialized to 0.
• It is accessible using [Link]
• Static variables can be accessed directly in static and non-static methods.
Example :
StaticEx(){ StaticEx(){
[Link](no); [Link](no);
no++; no++;
} }
} }
public static void main(String[] args) public static void main(String[] args)
{ {
} }
} }
10 10
10 11
10 12
Static Method
The method declared with static keyword is known as static method. main() is most com-
mon static method.
• It belongs to the class and not to object of a class.
• A static method can directly access only static variables of class and directly invoke
only static methods of the class.
• Static methods cannot access non-static members(instance variables or instance
methods) of the class
• Static method cant access this and super references
• It can be called through the name of class without creating any instance of that class.
For example, [Link]()
Example:
class StaticEx{
static int x;
int y=10;
static void display(){
[Link](“Static Method “+x); // static method accessing static variable
}
public void show(){
[Link](“Non static method “+y);
[Link](“Non static method “+x); // non-static method can access static variable
}
}
public class Main
{
public static void main(String[] args) {
StaticEx obj=new StaticEx();
[Link](); // static method invoked without using object
[Link]();
}
}
Sample Output:
Static Method 0
Non static method 10
Non static method 0
In this example, class StaticEx consists of a static variable x and static method display().
The static method cannot access a non-static variable. If you try to access y inside static
method display(), it will result in compilation error.
Static in main
Constructor
Nested class (static class)
Nested class is a class declared inside another class. The inner class must be a static class
declared using keyword static. The static nested class can refer directly to static members of
the enclosing classes, even if those members are private.
Syntax:
class OuterClass{
……..
static class InnerClass{
……….
}
}
We can create object for static nested class directly without creating object for outer class.
For example:
[Link]=new [Link]();
Example:
class Outer{
static int x=10;
static class Inner{
int y=20;
public void show(){
[Link](x+y); // nested class accessing its own data & outer
class static data
}
}
}
class Main{
public static void main(String args[]){
[Link] obj=new [Link](); // Creating object for static nested class
[Link]();
}
}
Sample Output:
30
Static Import
The static import allows the programmer to access any static members of imported class
directly. There is no need to qualify it by its name.
Syntax:
Import static package_name;
Advantage:
• Less coding is required if you have access any static member of a class oftenly.
Disadvantage:
• Overuse of static import makes program unreadable and unmaintable.
Example:
import static [Link].*;
class StaticImportEx{
public static void main(String args[]){
[Link](“Static Import Example”); //Now no need of [Link]
}
}
Sample Output:
Static Import Example
ACCESS SPECIFIERS
Access specifiers or access modifiers in java specifies accessibility (scope) of a data mem-
ber, method, constructor or class. It determines whether a data or method in a class can be
used or invoked by other class or subclass.
Types of Access Specifiers
There are 4 types of java access specifiers:
1. Private
2. Default (no speciifer)
3. Protected
4. Public
The details about accessibility level for access specifiers are shown in following table.
Access Modifiers Default Private Protected Public
Accessible inside the class Yes Yes Yes Yes
Accessible within the subclass
Yes No Yes Yes
inside the same package
Accessible outside the package No No No Yes
Accessible within the subclass
No No Yes Yes
outside the package
Private access modifier
Private data fields and methods are accessible only inside the class where it is declared i.e
accessible only by same class members. It provides low level of accessibility. Encapsulation
and data hiding can be achieved using private specifier.
Example:
Role of private specifier
class PrivateEx{
private int x; // private data
public int y; // public data
private PrivateEx(){} // private constructor
public PrivateEx(int a,int b){ // public constructor
x=a;
y=b;
}
}
public class Main {
public static void main(String[] args) {
PrivateEx obj1=new PrivateEx(); // Error: private constructor cannot be applied
PrivateEx obj2=new PrivateEx(10,20); // public constructor can be applied to obj2
[Link](obj2.y); // public data y is accessible by a non-member
[Link](obj2.x); //Error: x has private access in PrivateEx
}
}
In this example, we have created two classes PrivateEx and Main. A class contains private
data member, private constructor and public method. We are accessing these private members
from outside the class, so there is compile time error.
Example:
class DefaultEx{
Sample Output:
10
In the above example, the scope of class DefaultEx and its data y is default. So it can be
accessible within the same package and cannot be accessed from outside the package.
Example:
Role of protected specifier
class Base{
protected void show(){
[Link](“In Base”);
}
}
public class Main extends Base{
public static void main(String[] args) {
Main obj=new Main();
[Link]();
}
}
Sample Output:
In Base
In this example, show() of class Base is declared as protected, so it can be accessed from
outside the class only through inheritance. Chapter 2 explains the concept of inheritance in
detail.
Public access modifier
The public access specifier has highest level of accessibility. Methods, class, and fields
declared as public are accessible by any class in the same package or in other package.
Example:
Role of public specifier
class PublicEx{
public int no=10;
}
public class Main{
public static void main(String[] args) {
PublicEx obj=new PublicEx();
[Link]([Link]);
}
}
Sample Output:
10
In this example, public data no is accessible both by member and non-member of the
class.
ARRAYS
Array is a collection of elements of similar data type stored in contiguous memory loca-
tion. The array size is fixed i.e we can’t increase/decrease its size at runtime. It is index based
and the first element is stored at 0th index.
Advantages of Array
• Code Optimization: Multiple values can be stored under common name. Date retrieval
or sorting is an easy process.
• Random access: Data at any location can be retrieved randomly using the index.
Disadvantages of Array
• Inefficient memory usage: Array is static. It is not resizable at runtime based on number
of user’s input. To overcome this limitation, Java introduce collection concept.
Types of Array
There are two types of array.
• One Dimensional Array
• Multidimensional Array
Example:
int[] a=new int[5]; //defining an integer array for 5 elements
Alternatively, we can create and initialize array using following syntax.
Syntax:
dataType[] arrayName=new datatype[]{list of values separated by comma};
Or
Example:
Program to access 2D array elements
class TwoDimEx
{
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][] = { {1,1,12},{2,16,1},{12,42,2} };
// printing 2D array
for (int i=0; i< [Link]; i++)
{
for (int j=0; j < arr[i].length ; j++)
[Link](arr[i][j] + “ “);
[Link]();
}
}
}
Sample Output:
1 1 12
2 16 1
12 42 2
Jagged Array
Jagged array is an array of arrays with different row size i.e. with different dimensions.
Example:
class Main {
public static void main(String[] args) {
int[][] a = {
{11, 3, 43},
{3, 5, 8, 1},
{9},
};
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
If you are not using any IDE, you need to follow the syntax given below:
For Example
javac -d . [Link]
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
You need to use fully qualified name e.g. [Link] etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
The . represents the current folder.
There are three ways to access the package from outside the package.
1. import package.*;
2. import [Link];
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Example of package that import the packagename.*
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. [Link] and [Link]
packages contain Date class.
Example of package by import fully qualified name
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}
Output:Hello
Note: If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.
ORDER OF CONSTRUCTOR INVOCATION
• Constructors are invoked in the order of their derivation
• If a subclass constructor does not explicitly invoke a superclass constructor using
super() in the first line, the Java compiler automatically inserts a call to the no-
argument constructor of the superclass. If the superclass does not have a no-argument
constructor, it will generate a compile-time error.
Example:
class A
{
A(){
[Link](“A’s Constructor”);
}
}
/* sub class B extending A */
class B extends A
{
B(){
super();
[Link](“B’s Constructor”);
}
}
/* sub class C extending B */
class C extends B{
C(){
super();
[Link](“C’s Constructor”);
}
}
/* Driver program to test */
class Main
{
public static void main(String[] args)
{
C obj = new C();
}
}
Sample Output:
A’s Constructor
B’s Constructor
C’s Constructor
Invoking Superclass Parameterized Constructor
To call parameterized constructor of superclass, we must use the super keyword as shown
below.
Syntax:
super(value);
Example:
class SuperCls{
int x;
SuperCls(int x){
this.x=x; // this refers to current invoking object
}
}
class SubCls extends SuperCls{
int y;
SubCls(int x,int y){
super(x); // invoking parameterized constructor of superclass
this.y=y;
}
public void display(){
[Link](“x: “+x+” y: “+y);
}
}
public class Main
{
public static void main(String[] args) {
SubCls obj=new SubCls(10,20);
[Link]();
}
}
Sample Output:
x: 10 y: 20
The program contains a superclass and a subclass, where the superclass contains a param-
eterized constructor which accepts a integer value, and we used the super keyword to invoke
the parameterized constructor of the superclass.
THE OBJECT CLASS
The Object class is the parent class of all the classes in java by default (directly or indi-
rectly). The [Link] class is the root of the class hierarchy. Some of the Object class
are Boolean, Math, Number, String etc.
Object
Some of the important methods defined in Object class are listed below.
Object class Methods Description
boolean equals(Object) Returns true if two references point to the same object.
String toString() Converts object to String
void notify()
void notifyAll() Used in synchronizing threads
void wait()
void finalize() Called just before an object is garbage collected
Returns a new object that are exactly the same as the current
Object clone()
object
int hashCode() Returns a hash code value for the object.
Example:
public class Test
{
public static void main(String[] args)
{
Output:
Roars
In the above code, Animal is an abstract class and Lion is a concrete class.
Example 2
abstract class Bank
{
abstract int getRateOfInterest();
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class PNB extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
public class TestBank
{
public static void main(String args[])
{
Bank b=new SBI();//if object is PNB, method of PNB will be invoked
int interest=[Link]();
[Link](“Rate of Interest is: “+interest+” %”);
b=new PNB();
[Link](“Rate of Interest is: “+[Link]()+” %”);
}
}
Output:
Rate of Interest is: 7 %
Rate of Interest is: 8 %
Abstract class with concrete (normal) method
Abstract classes can also have normal methods with definitions, along with abstract
methods.
Sample Code:
abstract class A
{
abstract void callme();
public void normal()
{
[Link](“this is a normal (concrete) method.”);
}
}
public class B extends A
{
void callme()
{
[Link](“this is an callme (abstract) method.”);
}
public static void main(String[] args)
{
B b = new B();
[Link]();
[Link]();
}
}
Output:
this is an callme (abstract) method.
this is a normal (concrete) method.
Observations about abstract classes in Java
1. An instance of an abstract class cannot be created; But, we can have references
of abstract class type though.
Sample Code:
abstract class Base
{
abstract void fun();
}
class Derived extends Base
{
void fun()
{
[Link](“Derived fun() called”);
}
}
public class Main
{
public static void main(String args[])
{
// Base b = new Base(); Will lead to error
// We can have references of Base type.
Base b = new Derived();
[Link]();
}
}
Output:
Derived fun() called
3. We can have an abstract class without any abstract method. This allows us to create
classes that cannot be instantiated, but can only be inherited.
Sample Code:
abstract class Base
{
void fun()
{
[Link](“Within Base fun()”);
}
}
class Derived extends Base
{
}
public class Main
{
public static void main(String args[])
{
Derived d = new Derived();
[Link]();
}
}
Output:
Within Base fun()
4. Abstract classes can also have final methods (methods that cannot be
overridden).
Sample Code:
abstract class Base
{
final void fun()
{
[Link](“Within Derived fun()”);
}
}
class Derived extends Base
{
}
public class Main
{
public static void main(String args[])
{
Base b = new Derived();
[Link]();
}
}
Output:
Within Derived fun()
FINAL KEYWORD
The final keyword in java is used to restrict the user. The java final keyword can be
ap-plied to:
• variable
• method
• class
}
public static void main(String args[])
{
Vehicle obj=new
Vehicle();[Link]();
}
}
Output:
/[Link]: error: variable speedlimit not initialized in the default
constructor final int speedlimit; //blank final variable
^
1 error
{ {
OR
//code //code
} }
Sample Code:
final class XYZ
{
}
Syntax:
accessspecifier interface interfacename
{
return-type method-name1(parameter-
list); return-type method-
name2(parameter-list); type final-
varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-
list); type final-varnameN = value;
}
When no access specifier is included, then default access results, and the interface is
only available to other members of the package in which it is declared. When it is
declared as pub-lic, the interface can be used by any other code.
• The java file must have the same name as the interface.
• The methods that are declared have no bodies. They end with a semicolon after
the parameter list. They are abstract methods; there can be no default
implementation of any method specified within an interface.
• Each class that includes an interface must implement all of the methods.
• Variables can be declared inside of interface declarations. They are implicitly
final and static, meaning they cannot be changed by the implementing class.
They must also be initialized.
• All methods and variables are implicitly public.
Sample Code:
The following code declares a simple interface Animal that contains two methods
called eat() and travel() that take no parameter.
/* File name : [Link]
*/interface Animal {
public void eat();
public void travel();
}
Implementing an Interface
Once an interface has been defined, one or more classes can implement that
interface. To implement an interface, the ‘implements’ clause is included in a class definition
and then the methods defined by the interface are created.
Syntax:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
Properties of java interface
If a class implements more than one interface, the interfaces are separated with
a
comma.
If a class implements two interfaces that declare the same method, then the
same method will be used by clients of either interface.
The methods that implement an interface must be declared public.
Rules The type signature of the implementing method must match exactly the type
signature specified in the interface definition.
{
[Link](“Mammal travels”);
}
public int noOfLegs()
{
return 0;
}
public static void main(String args[])
{
Mammal m = new
Mammal(); [Link]();
[Link]();
}
}
Output:
Mammal eats
Mammal travels
It is both permissible and common for classes that implement interfaces to define ad-
ditional members of their own. In the above code, Mammal class defines additional
method called noOfLegs().
Sample Code 2:
The following code initially defines an interface ‘Sample’ with two members. This
inter-face is implemented by a class named ‘testClass’.
import [Link].*;
// A simple
interface interface
Sample
{
final String name =
“Shree”; void display();
}
// A class that implements interface.
public class testClass implements
Sample
{
public void display()
{
[Link](“Welcome”);
}
public static void main (String[] args)
{
testClass t = new
testClass(); [Link]();
[Link](name);
}
}
Output:
Welcom
e Shree
Sample Code 3:
In this example, Drawable interface has only one method. Its implementation is
provided by Rectangle and Circle classes.
interface Drawable
{
void draw();
}
class Rectangle implements Drawable
{
public void draw()
{
[Link](“Drawing rectangle”);
}
}
class Circle implements Drawable
{
public void draw()
{
[Link](“Drawing circle”);
}
}
public class TestInterface
{
public static void main(String args[])
{
Drawable d=new
Circle();[Link]();
}
}
Output:
Drawing circle
Nested Interface
An interface can be declared as a member of a class or another interface. Such an
inter- face is called a member interface or a nested interface. A nested interface can be
declared as public, private, or protected.
Sample Code:
interface MyInterfaceA
{
void display();
interface
MyInterfaceB
{
void myMethod();
}
}
public class NestedInterfaceDemo1 implements [Link]
{
public void myMethod()
{
[Link](“Nested interface method”);
}
public static void main(String args[])
{
[Link] obj= new
NestedInterfaceDemo1(); [Link]();
}
}
Output:
Nested interface method
Differences between classes and interfaces
Both classes and Interfaces are used to create new reference types. A class is a
collection of fields and methods that operate on fields. A class creates reference types
and these refer- ence types are used to create objects. A class has a signature and a body.
The syntax of class declaration is shown below:
class class_Name extends superclass implements interface_1,….interface_n
// class signature
{
//body of class.
}
Signature of a class has class’s name and information that tells whether the class has
in- herited another class. The body of a class has fields and methods that operate on
those fields. A Class is created using a keyword class.
When a class is instantiated, each object created contains a copy of fields and
methods with them. The fields and members declared inside a class can be static or
nonstatic. Static members value is constant for each object whereas, the non-static
members are initialized by each object differently according to its requirement.
Members of a class have access specifiers that decide the visibility and accessibility
of the members to the user or to the subclasses. The access specifiers are public, private and
pro- tected. A class can be inherited by another class using the access specifier which
will decide the visibility of members of a superclass (inherited class) in a subclass
(inheriting class).
An interface has fully abstract methods (methods with nobody). An interface is
syntacti- cally similar to the class but there is a major difference between class and
interface that is a class can be instantiated, but an interface can never be instantiated.
An interface is used to create the reference types. The importance of an interface in
Java is that, a class can inherit only a single class. To circumvent this restriction, the
designers of Java introduced a concept of interface. An interface declaration is
syntactically similar to a class, but there is no field declaration in interface and the
methods inside an interface do not have any implementation. An interface is declared
using a keyword interface.
Aspect for
Class Interface
compariso
n
An interface can never be
A class is instantiated to
Basic instanti- ated as the methods are
create
unable to perform any action on
objects.
invoking.
Keyword class Interface
Access The members of a class can The members of an interface
specifier be private, public or protected. are always public.
The methods of a class are The methods in an interface
Methods
defined to perform a specific are purely abstract.
action.
A class can implement any An interface can extend
inheritance num- ber of interfaces and can multiple interfaces but cannot
extend only one class. implement any interface.
Inheritance
extends implements
keyword
An interface can never have a
A class can have constructors
Constructor constructor as there is hardly
to
any variable to initialize.
initialize the variables.
class class_Name Interface interface_Name
{ {
//fields Type var_name=value;
Declaratio
//Methods Type method1(parameter-
n Syntax
} list); Type
method2(parameter-list);
..
}
The following example shows that a class that implements one interface:
public interface interface_example
{
public void method1();
public string method2();
}
public class class_name implements interface_example
{
public void method1()
{
..
}
public string method2()
{
…
}
}
Inheritance between concrete (non-abstract) and abstract classes use extends keyword.
It is possible to extend only one class to another. Java does not support multiple
inheri- tance. However, multilevel inheritance i.e., any number of classes in a ladder is
possible. For example, in the following code class C extends the class B, where the class
B extends class A.
class A {}
class B extends A {
} class C extends B
{}
Inheritance between classes (including abstract classes) and interfaces, use
implements keyword.
To support multiple inheritance, it uses interfaces. So after implements keyword,
there can be any number of interfaces. For example, in the following code, class B
extends only one class A and two interfaces I1 and I2.
interface I1
{} interface I2
{} class A
class B extends A implements I1, I2
{
}
Inheritance between two interfaces, is possible with the use of extends keyword only.
For example, in the following code, interface I2 extends the interface I1.
interface I1 { }
interface I2 extends I1{ }
OBJECT CLONING
Object cloning refers to creation of exact copy of an object. It creates a new instance
of the class of current object and initializes all its fields with exactly the contents of the
corre- sponding fields of this object. In Java, there is no operator to create copy of an
object. Unlike C++, in Java, if we use assignment operator then it will create a copy of
reference variable and not the object. This can be explained by taking an example.
Following program demon-strates the same.
// Java program to demonstrate that assignment operator creates a new reference to
same object.
import [Link].*;
class sample
{
int a;
float b;
sample(
)
{
a = 10;
b = 20;
}
}
class Mainclass
{
public static void main(String[] args)
{
sample ob1 = new sample();
[Link](ob1.a + “ “ +
ob1.b);sample ob2 = ob1;
ob2.a = 100;
[Link](ob1.a+”
“+ob1.b);
[Link](ob2.a+”
“+ob2.b);
}
}
Output:
10 20.0
100 20.0
100 20.0
Creating a copy using clone() method
The class whose object’s copy is to be made must have a public clone method in it or
in one of its parent class.
• Every class that implements clone() should call [Link]() to obtain the
cloned
object reference.
• The class must also implement [Link] interface whose object
clone we want to create otherwise it will throw CloneNotSupportedException
when clone method is called on that class’s object.
• Syntax:
• protected Object clone() throws CloneNotSupportedException
import
[Link]; class
sample1
{
int a, b;
}
class sample2 implements Cloneable
{
int c;
int
d;
sample1 s = new sample1();
public Object clone() throws CloneNotSupportedException
{
return [Link]();
}
}
public class Mainclass
{
public static void main(String args[]) throws CloneNotSupportedException
{
sample2 ob1 = new
sample2(); ob1.c = 10;
ob1.d = 20;
ob1.s.a = 30;
ob1.s.b = 40;
sample2 ob2 = (sample2)[Link]();
ob2.d = 100; //Change in primitive type of ob2 will not be reflected in ob1 field
ob2.s.a = 300; //Change in object type field will be reflected in both ob2
and
ob1(shallow copy)
[Link](ob1.c + “ “ + ob1.d + “ “ +ob1.s.a + “ “ +
ob1.s.b);[Link](ob2.c + “ “ + ob2.d + “ “ +ob2.s.a + “ “
+ ob2.s.b);
}
}
Types of Object cloning
1. Deep Copy
2. Shallow Copy
Shallow copy
Shallow copy is method of copying an object. It is the default in cloning. In this
method the fields of an old object ob1 are copied to the new object ob2. While copying the
object type field the reference is copied to ob2 i.e. object ob2 will point to same location
as pointed out by ob1. If the field value is a primitive type it copies the value of the
primitive type. So, any changes made in referenced objects will be reflected in other
object.
Note:
Shallow copies are cheap and simple to make.
Deep Copy
To create a deep copy of object ob1 and place it in a new object ob2 then new copy
of any referenced objects fields are created and these references are placed in object ob2.
This means any changes made in referenced object fields in object ob1 or ob2 will be
reflected only in that object and not in the other. A deep copy copies all fields, and
makes copies of dynamically allocated memory pointed to by the fields. A deep copy
occurs when an object is copied along with the objects to which it refers.