Core Java Unit 1
Core Java Unit 1
(ECS)-II
Core JAVA
Unit-1
Introduction:
We know that, there are two paradigms (Models) of Programming languages which are as
follows:
1) Procedure oriented Paradigm (POP).
2) Object oriented Paradigm (OOP).
Procedure Oriented Paradigm (POP):
The POP is also called as functional programming because the strength of POP languages
Isfunction. Also, all the statements in the functions are executed one after another from
top to bottom in sequence manner therefore it is commonly known as “Procedure
oriented”
High level languages such as COBOL, FORTRON, and C etc. are commonly known as
POP languages.
Advantages or Characteristics of POP languages:
1) In case of POP the focus is on Function rather than data.
2) It fallows top-down approach.
3) Program consists of different functions.
4) Most functions share global data.
5) Communication is done between functions i.e. one function can send data to another
function.
6) Data is not hidden i.e. data is easily accessed& modified by other functions therefore it is
not secured.
Object Oriented Paradigm (OOP):
The OOP considers „data‟ as important thing & does not allow it to flow freely around the
program i.e. it provides security for data.
In OOP „data‟ is closely tied with functions or methods that protects it from unauthorized
modification by another function.
OOP allows us to decompose a problem into a number of entities called “object” and then
build data and functions around these objects. In short, an object is combination or
composition of „data‟ & „functions‟ or „methods‟ which is shown in following fig.
In above figure, the data of an abject is only accessed by methods associated with an object.
High level languages such as JAVA, C#, C++ etc. are commonly known as OOP
languages.
Advantages or Characteristics of OOP languages:
1) In case of OOP the focus is on „data‟ rather than function.
2) It fallows bottom-up approach.
3) Program consists of different objects.
4) Main problem is divided into number of entities called „Objects‟
5) Communication is done between objects through methods.
6) Data is hidden i.e. data& functions are tied together with an object that‟s why it is not
easily accessed or modified by other functions therefore it is secured.
7) New „data‟ and „function‟ can easily be added whenever required.
1) Class:
Class is user defined data type which is collection of data and functions or methods.
Here, „data‟ is nothing but properties or characteristics of class whereas „methods‟ are the
functions that operates on data of class
In JAVA language, all functions are defined inside class definition therefore they are
called as „Methods‟. Even main( ) also defined inside class definition.
Single JAVA program contains many classes but out of these classes, any single class
have main( ) method from which execution of program starts.
Class can be declared or defined by using keyword „class‟ followed by „class_name‟ which
is an identifier.
class class_name
{
data_type data1;
Data
data_type data2;
data_type dataN;
return_typemethod1( );
return_typemethod2( ); Methods
return_typemethodN( );
}
Multiple objects can be created for the single class whenever required and each object
hold individual record i.e. individual data & methods.
A class provides the blueprints for objects.
When you define a class, you define a blueprint for a data type.
class emp
{
int emp_no;
char name[20], add[20]; Data (Attributes)
floatsalary;
2) Object:
An Object is an instance or variable of class.
An object can be thought of as an entity which can represent person, place, animal etc.
Object is such run time entity which holds entire data and methods of class.
When program is executed, the objects interact with each other by sending messages to
one another.
There are three properties related with objects:
Identity: This property of an object that distinguishes it from other objects
o
State: This property describes the data stored in the object
o
Behavior: This property describes the methods in the object's interface by which
o
the object can be used
Multiple objects can be created for the single class whenever required and each object
hold individual record.
Data and methods are tied with an object therefore data cannot access or modified by
another function.
Following Fig. shows an object:
3) Data Encapsulation:
The binding of data and methods into single unit is called “Data encapsulation”. And that
keeps both data and methods safe from outside the world and misuse.
Data encapsulation lead to the important OOP concept of data hiding and is
accomplished by class and object. Because, Object binds „data‟ & „methods‟ together
therefore this data is only accessed by methods of corresponding object and not
accessed by outside the world (other methods).
A benefit of encapsulation is that it can reduce system complexity, and thus increases
robustness, by allowing the developer to limit the interdependencies between software
components.
This feature supports the data security in OOP.
Following figure shows Data encapsulation concept:
Private
Function
Public:
Data
4) Data Abstraction:
Data abstraction refers to, providing only essential information to the outside word and
hiding their background details.
This is closely related to encapsulation because abstraction is implemented by
encapsulation.
InJAVA, only public „data‟ or „methods‟ are accessible to the outside world to manipulate
object‟s data, without actually knowing how class has been implemented internally.
If we have to give accessibility to some data of the class then it has to be
madeaspublicand those we have to make hide from outside world then it has to made
private . Thus, Classes makes data abstraction with the help of access specifier or
visibility mode.
E.g.
Let's take one real life example of a TV. Which you can turn on and off, change the
channel, adjust the volume, and add external components such as speakers, VCRs, and
DVD players.
But you do not know its internal detailssuch as,
you do not know how it receives signals over the air or through a cable
How it translates them, and finally displays them on the screen.
Thus we can say, a television clearly separates its internal implementation from its external
interface and you can play with its interfaces like the power button, channel changer, and
volume control without having zero knowledge of its internals
5) Polymorphism:
The word polymorphism is made up of two Greek words “poly” and “morphism”.
“Poly” means many and “morphism” means forms, so polymorphism means many-forms.
In OOP, we implement many functions with same name but these functions are differ
from each other according to their signature. (Signature refers to type of argument and
number of argument accepts by the functions)
In OOP, polymorphism means “one name” named for multiple functions that have
different behaviors.
E.g. Consider following prototype of functions:
int add( );
void add(int);
int add(int, int);
In above example, many functions having same name but all these differ from each other by
signatures therefore here polymorphism occurs.
Basically polymorphism having two types:
Vehicle
Two Four
In above figure, „Vehicle‟ is super base class from which two classes are derived „Two
wheeler‟ and „Four wheeler‟. Also, „Shine‟ and „Splendor‟ are derived classes from „Two
wheeler‟. And „Zen‟, „Alto‟ and „Vista‟ are derived classes from „Four wheeler‟ base class.
7) Message Passing:
The act of communicating with an object to get something done is called as “Message
Passing”
In message passing sending and receiving of information is done by the objects. So this
helps in building real life systems. Following are the basic steps in message passing.
Creating classes that define objects and its behavior.
Creating objects from class definitions
Establishing communication among objects
In OOP, each object is capable of receiving messages, processing data, and sending
messages to other objects and can be viewed as an independent „unit‟ with a distinct role
or responsibility.
Objects react when they receive messages by applying methods on themselves.
A message is a request to an object to invoke one of its methods; in other words, a
message for an object is a simply a call to one of its methods through the object.
When objects communicate with one another, we say that they send and receive
messages.
E.g. [Link](a,b);
Here, we are passing a message getdata()to the objects „X‟ with parameters „a‟ and
„b‟.Following figure shows messaging between object A and Object B:
8) Persistence:
In OOP, Persistence is simply related with the „objects‟ that "Stick around" between
the program.
This is just serialization(It is the process of translating an „object‟ into a format that can be
stored and reconstructed or retrieve later whenever required) an object from Object Oriented
database (OO-database).
In short, due to persistence concept, OOP language is capable to deal with the object
oriented database.
Object
Object Oriented
Store & retrieve Database
object whenever
necessary
Introduction to JAVA
JAVA is general purpose OOP language developed by “Sun
Microsystems” of USA in1991
„James Gosling‟ was the inventor (Creator) of JAVA language.
Originally or firstly JAVA was named as “Oak” (Oak is name of tree which was found in
front of Goslings Office)
Basically, JAVA was designed for the development of software‟s for electronic devices like
TV‟s, VCR‟s, set-top box, Toastersetc.
Java runs on a variety of platforms, such as Windows, Mac OS, and the various versionsof
UNIX.
The „C‟ and „C++‟ languages had limitations in terms of reliability and portability therefore
they modeled their new language JAVA to overcome the drawbacks of „C‟ and „C++‟. Thus,
JAVA made really simple, reliable, portable and powerful language.
History OR Evolution of JAVA:
Following table shows some milestones happen in developing of JAVA language:
Year Development
After exploring the possibility of such idea, the team announced a new
1991
programming language called „Oak‟ (Oak was the first name for JAVA)
In this year, team of Sun Microsystems actual implements there language in home
1992
appliances like Microwave Oven etc. with tiny touch-sensitive screen.
In this year, team of Sun Microsystems came up with new idea to develop web
1993 based application that could run on all types of computers connected to Internet.
For that, they creates 'applet' (tiny program run on Internet by the browser)
In this year, team of Sun Microsystems developed web browser called "HotJava" to
1994
locate and run applet on Internet.
"Oak" was renamed as "JAVA" due to some legal snags (problems). Also, many
1995
popular companies like Netscape and Microsoft announced to support for JAVA
Sun Microsystem releases Java Development Kit 1.0 (JDK 1.0) to develop different
1996
kinds of software.
1997 Sun Microsystem releases Java Development Kit 1.1 (JDK 1.1)
Sun Microsystem releases JAVA 2 with JDK 1.2 of Software Development Kit (SDK
1998
1.2).
Sun Microsystem releases standard Edition of Java which was called J2SE( Java
1999
2 Standard Edition) and J2EE (Java 2 Enterprise Edition)
2000 J2SE with SDK 1.3 was released
2002 J2SE with SDK 1.4 was released
2004 J2SE with JDK 5 (JDK 1.5) was released
Currently Java releases their JDK 7 (JDK 1.7) version. And Java is now under
administration of Oracle organization.
Features 0r Characteristics or Advantages of Java:
Compiled & Interpreted:
Usually, programming language is either compiled or interpreted. But Java combines
both approaches that make Java „two-stage system‟.
In case of Java, First Java compiler translates or converts Java source program into
„byte code‟ ( Byte code is not machine instruction code & byte codefile having
extension „.class‟)
After compilation, Java Interpreter executes this byte code & thus we got our desired
output.
Thus, we can say that Java is Compiled & Interpreted language.
Object Oriented:
Java is pure object oriented language that supports for all OOP‟s concepts.
Almost, In Java, everything is an Object. All data and methods are resided (exist
in) within an object and classes.
The object model in Java is easy to extend because it supports for Inheritance
concept.
Platform independent and Portable:
Portable: We know that, after compilation of Java source program it produce “.class”
file i.e. byte code which is not machine dependent that‟s why such file is easily moved
or transferred from one computer to another computer and hence Java is Portable.
Platform independent: After generation of byte code (.class file), this byte code is easily
interpreted or executed on different kinds of computers having different
platforms(Computers having different Operating system like windows, Linux, Mac OS
etc and different processors etc).
Simple:
Java is designed to be easy to learn. If you understand the basic concepts of OOP then
it is easy to implement in Java language.
Secure:
We know that, most of viruses are attacked on files having extension „.exe‟, „.doc‟,
„.gif‟, „.mpg‟ etc. but after compilation of Java source program it produce “.class” file
i.e. byte code and which is virus free. And hence, Java enables us to develop virus-
free, tamper -free systems.
Architectural-neutral:
Java compiler generates an architecture-neutral class file format which makes the
compiled code to be executable on many processors, with the presence of Java
runtime system.
Robust:
Java is strict type checking language which checks an error at both time i.e at compile
time and also at run time of program.
Due to this ability of checking errors at run time (exception Handling), we can
eliminates any risk of crashing the system using Java.
Multithreaded:
Multithreaded means handling multiple tasks (jobs) simultaneously (at one time).
Java supports for multithreaded programs that means we need not wait for the
application to finish its task before beginning another.
That is using Java, we can run multiple java applications without waiting to finish
another.
Distributed:
Java enables us to make such applications that can open and access remotely over
the internet or network.
That is, multiple programmers at multiple remote locations are capable to work
together on single project. That‟s why Java is distributed.
Dynamic and Extensible:
Dynamic:Java is dynamic language which is capable to link new class libraries,
methods and objects dynamically.
Extensible: Java supports to write functions in C or C++ language such functions are
called “native methods” and then we can add or link these methods with Java such
that they can be used in many applications.
Ability to Deal with Database:
Java supports for JDBC (Java Database Connectivity) to send & retrieve data in
tabular format with the database thus with the help of Java we are able to deal with
database.
Automatic Memory Management:
We know that „memory‟ is very important issue while dealing with computer and we
have to manage it very efficient manner.
Java language supports for „Garbage Collector‟ that automatically manages all the
memory in efficient manner.
Limitations or Disadvantages of Java:
Slow language:
As compared to C and C++ languages, Java language compiler took much more
time to compile the program & also Java interpreter took much more time to
interpret the program that‟s why Java is slow language.
Strict type checking language:
Due to strict type checking, Java language checks much run time errors & that‟s why
Java application took much time to execute.
Case sensitive language:
Due to case sensitive language, we must have to write correct spelling of inbuilt
methods, classes, interfaces etc. while doing programming.
Java does not support for Multiple Inheritance but we can implement it by
using ‘interface’.
C++
C Java
Java Environment:
The main part of Java Environment is JDK (Java Development Kit).
JSL (Java Standard Library) also called as Java API (Application Programming Interface)is
the main part of JDK that contains thousands of Packages.
Further, Packages contains thousands of classes, methods, interfaces etc.
Following Fig. shows Java Environment:
Classes
Methods
Interfaces
Packages
JSL
JDK
Java Environment
Following is the list of tools or components of JDK which are used to develop and run the java
programs:
[Link] Tool or Component Description or Use
It translates or converts java source program into
1 javac (Java Compiler) byte code file & that file understood by java
interpreter
It runs java applications by reading corresponding
2 java (java Interpreter)
byte code file & gives result.
It runs or views java applets onto the web
3 appletviewer
browser.
4 javap (Java disassembler) It converts byte code file into program description
First ofall, java sourcefile (.javafile) is converted into byte code (.class file) by the java
compiler and this byte code file isgiven to the JVM.
In JVM, there is one module or program called „Class loader sub system‟ which performs
following functions:
First, „Class loader sub system‟ loads the „.class‟ file into memory.
Then it verifies whether all byte code instructions are proper or not.
If it finds some problem in byte code then it immediately terminates the execution.
If byte code is proper then it allocates necessary memory to execute the program.
Also, this memory is divided into 5 parts called „Runtime data area‟ & these parts as follows:
1) Method area:
In this memory area; all class code, variables codes, methods codes etc. are stored.
2) Heap:
In this memory area, all objects are created or stored.
3) Java Stacks:
Actually, java methods are stored in „Method area‟ but actual execution of such java
methods are happen under „Java stacks‟ area.
4) PC registers:
This area contains the memory addresses of instructions of the methods.
5) Native method stacks:
All native methods (C, C++ functions) are executed under native methods [Link]
all native methods are connected with JVM by „native method interfaces’
After, allocation of memory into corresponding parts then it comes towards „Execution Engine‟.
Execution Engine can consists from two things VIZ:
1) Interpreter 2) JIT (Just In Time) compiler.
This interpreter and JIT compiler are responsible for converting byte code into machine
instruction such that it easily executed by microprocessor.
After, loading the “.class” file into memory, JVM first identifies which code is to be left
to interpreter and which one to JIT compiler so that the performance is better. The blocks
of code allocated for JIT compiler are also called „hotspots‟. Thus, the interpreter and JIT
compiler will work simultaneously to translate the byte code into machine code.
Note that: JIT compiler is a part of JVM which increases execution speed of program.
Documentation Section
1) Documentation Section:
This section contains set of comments lines showing details of java source program such as
program name, programmer name, date of program, version etc. this help program readability.
In Java, we can give comments by three ways VIZ:-
1) Single line comment:
If we have to specify general information of program within single line then single line
comment is used. Single line comment is given by // notation.
Also, we can specify this comment anywhere in program.
e.g.
// Program Name= Addition of two numbers.
2) Multiline comment:
If we have to specify general information of program within multiple lines then multi
line comment is used. Multiline comment is given by
/*
---------- */ notation.
e.g.
/* Program Name: Multiplication
Programmer: James Gosling */
e.g.
/** This class is used for addition */
public class add
{
/** This method is used for addition */
public void addition( )
{
// statements
}
}
In above example, two times documentation comment is used that will show
description of class „add‟ and description of method „addition( )‟ in HTML file. Note
that: For generation of HTML documentation of java source program using „javadoc‟
component, class and method should be public or protected.
2) Package statement Section:
This section is used to declare our own package. When we declare own package then
it informs to the java compiler to link all classes with our java source program.
Syntax to specify package statement:
packagepackage_name;
e.g.
package student;
More about package will be discussed in next chapter.
3) import statement Section:
In this section we can import existing package in our java source program.
We know that, in case of „C‟ language if we have to use printf( ) method then we include
„stdio.h‟ header file using preprocessor directive „#include‟.
Similarly, if we have to use existing classes or exiting methods for JSL (Java Standard
Library) then we have to import that package in our source program using „import‟
statement.
Syntax to import package in program:
importpackage_name;
e.g.
import [Link].* ;
[Link].*;
class first
{
public static void main(String args[ ])
{
[Link](“Welcome in JAVA programming”);
}
}
In above program,
“[Link]” is a package which is imported using „import‟ keyword. This package contains
lots of inbuilt classes such as System, String, Integer, Float [Link] is default package
i.e. there is no necessary to import it.
Here, main( ) method is compulsory which is declared as public, static and void
It is public because it made available for JVM for interpretation of java program.
It is static because it should be called without any object; it is invoked by JVM
with classname.
It is void because it does not return any value.
Also, main( ) method accepts array of string as argument which is called as command
line argument. The passed values are stored in args[ ] array at individual indices.
[Link]( ) statement:
“System” is inbuilt wrapper class which was found under „[Link]‟ package.
“out” is object of „System‟ class which is „static‟ & hence it is accessed by „System‟
class name.
“println( )” is a method was found in “System” class used to display output and
called by using “out” object.
Steps to execute Java Program:
Following flowchart shows compiling and interpreting Java program;
E.g. Consider, we have „[Link]‟ source program then we can compile it as follow:
If „[Link]‟ program have one class named „good‟ then „good. Class‟ byte code is generated.
Syntax to Interpret or Run or Execute the Byte code:
Java program is interpreted or run or execute using bytecode (.class file) along with „java‟
interpreter which is given as fallow:
Note that: After compilation of java source program, byte code (.class file) is generated. And then
JVM interpret that byte code and we got our result.
In above example; three command line arguments are passed to main( ) method. They are
SACHIN RAMESH SHINDE.
All these arguments are stored in „args‟ String type array in main( ) method at individual
indices as fallow;
args[0]=> SACHIN
args[1]=> RAMESH
args[2]=> SHINDE
Also, we use „+‟ operator to concatenates two strings with each other.
Java Source filecreation or declaration rules:
As the last part of this section let's now look into the source file declaration rules. These rules
are essential when declaring classes, import statements and package statements in a source
file.
A source file can haveonly one public class.
A source file can have multiple non-public classes.
The public class name should be the name of the source file and which should be stored
by .java extension.
For example : Consider there 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.
Java Tokens:
“Token is nothing but smallest individual unit of java source program.”
We know that Java is pure OOP language i.e. every program has classes and every classes has
some methods and methods contains executable statement and every executable statement
contains the tokens i.e. statements are made up of several tokens.
Following are the several tokens in Java program:
1) Keywords 2) Data type 3) Identifier 4) Variable
5) Constant or Literals 6) Operators 7) Special symbols.
Let us see all tokens in details:
4) Variable:
“Variable is the name given to the memory location where the data is stored such quantity
is called as Variable”
OR
“The quantity that changes during program execution is called as Variable”
Concept:
The main concept behind variable is that every variable has an ability to store the data.
DataType variableName ;
Here;
DataType is any valid data type in „Java‟ language.
variableName is an identifier.
Example: int rollno;
Char x;
There are several rules to declare the variable:
1) Variable should not be keyword.
2) Variable should not start with digit.
3) Variable can be combination of alphabets, digits or underscore.
4) Variable should not contain special symbol except underscore.
5) Variable should not contain any white space character like horizontal tab, vertical
tab, new line etc.
6) Variable should be meaningful.
7) Variable can be of any length.
8) Declared variable must be initialized anywhere in block.
5) Constant (Literals):
A literal represent a fixed value that is stored into variable directly in the program. They are
represented directly in the code without any computation.
Literals can be assigned to any primitive type variable.
For example:
bytep = 68;
char a = 'A';
Java has different types of literals VIZ:
1) Integer Literals
2) String Literals
3) Character Literals
4) Float Literals
5) Boolean Literals
Let us see all literals in details:
1) Integer Literals:
Integer literals represent the fixed integer values like 23, 78, 658, -745 etc.
The data type byte, int, long, shortbelongs to decimal number system that uses 10 digits (
from 0 to 9 ) or octal number systemthat uses 8 digits (from 0 to 7) or hexadecimal number
system that uses 16 digits (from 0 to F) to represent any number.
Note that:
Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these
number systems for literals.
For example:
intdecimal = 100;
intoctal = 0144;
inthexa = 0x64;
2) String Literals:
String literals are collection of characters which are representing in between a pair of
double quotes.
Example:
String x="Hello World";
3) Character Literals:
Character literals are characters which are representing in between a pair of single quotes.
Character literals are like „A‟ to „Z‟, „a‟ to „z‟, „0‟ to „9‟or Unicode character like „\u0042‟ or
escape sequence like „\n‟, „\b‟ etc.
Example:
Char x= „ Z‟;
4) Float Literals:
Float literals representsfractional values like 2.3, 86.58, 0.0, -74.5 etc.
These types of literals are used with float and double data types.
While writing such literals, we can use E or e for scientific notation, F or f for float literal
and D or d for double literals (this is default and generally omitted)
For Example:
float p = 9.26;
double q = 1.56e3;
float m =986.8f;
5) Boolean Literals:
Float literals representsonly two values – true or false. It means we can store either „true‟ or
„false‟ into a Boolean type variable
For Example:
boolean p =true;
6) Operators:
An„operator‟is a symbol that tells computer to perform specific task.
OR
An „Operator‟ is a symbol that operates onto the operand to perform specific task.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR (i.e. XOR)
~ Bitwise Complement
<< Bitwise left Shift
>> Bitwise Right Shift
>>> Bitwise Zero fill Right shift
The truth table or working of bitwise operator & , | and ^ is shown in following table:
E.g.:
1) 22&5
128 64 32 16 8 4 2 1
22 0 0 0 1 0 1 1 0
5 0 0 0 0 0 1 0 1
22&5 0 0 0 0 0 1 0 0
In above table, „1‟ bit is found in „4‟ column only therefore „22&5‟ gives result ‘4’
Bitwise OR operator (|):
This operator performs „OR‟ operation on individual bits of the numbers. To understand
the working of „|‟ operator see following example.
E.g.:
1) 35|7
128 64 32 16 8 4 2 1
35 0 0 1 0 0 0 1 1
7 0 0 0 0 0 1 1 1
35|7 0 0 1 0 0 1 1 1
In above table, „1‟ bit is found in „1‟, „2‟, „4‟ and „32‟ columns therefore „35|7‟ gives result
1+2+4+32= 39
Bitwise XOR operator (^):
This operator performs „exclusive OR‟ operation on individual bits of the numbers. Its
symbol is denoted by „^‟ which is called cap, carat or circumflex symbol. To understand the
working of „^‟ operator see following example.
E.g.:1) 47^4
128 64 32 16 8 4 2 1
47 0 0 1 0 1 1 1 1
4 0 0 0 0 0 1 0 0
47^4 0 0 1 0 1 0 1 1
In above table, „1‟ bit is found in „1‟, „2‟, „8‟ and „32‟ columns therefore „47^4‟ gives result
1+2+8+32=43
Bitwise Complementoperator (~):
This operator gives complement form of the given number. Its symbol is denoted by „~‟
which is called „tiled‟ symbol. To understand the working of „~‟ operator see following example.
E.g.:
1) ~47
It gives result= -48
2) ~(-26)
It gives result= 25
Bitwise leftshiftoperator (<<):
This operator shifts the bits towards left side by a specified number of positions. Its
symbol is denoted by „<<‟ which is called double less than symbol. To understand the working
of „<<‟ operator see following example.
E.g.:1) 15<<3
128 64 32 16 8 4 2 1
15 0 0 0 0 1 1 1 1
0 1 1 1 1 0 0 0
In above table, „1‟ bit is found in „8‟, „16‟, „32‟ and „64‟ columns therefore „15<<3‟ gives result
8+16+32+64=120
Bitwise Rightshiftoperator (>>):
This operator shifts the bits towards right side by a specified number of positions. Its
symbol is denoted by „>>‟ which is called double greater than symbol. To understand the
working of „>>‟ operator see following example.
E.g.:1) 25>>3
128 64 32 16 8 4 2 1
25 0 0 0 1 1 0 0 1
0 0 0 0 0 0 1 1
In above table, „1‟ bit is found in „1‟, and „2‟ columns therefore „25>>3‟ gives result
1+2=3
Bitwise Zero Fill Rightshiftoperator (>>>):
This operator also shifts the bits towards right side by a specified number of positions.
But, it stores „0‟ in the sign bit. Its symbol is denoted by „>>>‟ which is called triple greater
than symbol. Since, it always fills „0‟ in the sign bit therefore it is called zero fill right shift
operator.
In case of negative numbers, its output will be positive because sign bit is filled with „0‟
8) ‘new’ operator:
„new‟ operator is used to create object of class.
We know that, objects are created on „heap‟ memory by JVM dynamically.
Syntax to create object:
className obj=new className( );
Here,
„className‟ is name of the class.
„obj‟ is name of created object which is an identifier.
Example: Consider, there is class named „Employee‟ then we create its object as follow,
if(x == true )
w s)
2)
int x=65;
char y = (char) x;//here, the data type of „x‟ is converted into data type of „y‟ using (char) cast operator
Control Statement in Java:
The statement that controls the flow of execution of program is called as “Control statement” or
“Control Structure”.
The following tree diagram shows control statements in Java language:
(Note that: All the Control Statement in Java is same as that of C/C++ language therefore
refer notes of C/C++ language)
for-each loop:
This loop is specially designed to handle elements of „collection‟.
Collection represents a group or set of elements or objects.
For example: We can take an „array‟ as collection because „array is set or group of elements
Also, any class in „[Link]‟ package can be considered as „collection‟ because any class in
„[Link]‟ package handles group of objects such as „stack‟, „vector‟, „LinkedList‟ etc.
The for-each loop repeatedly executes a group of statements for each element of the collection.
The execution of for-each loop depends upon total number of elements or objects present in the
collection.
Syntax:
for (datatypevar : collection )
{
Statements;
}
Here,
„var‟ is an identifier which represents each element of collection one by one. Suppose, the collection has 5
elements then this loop will be executed 5 times and „var‟ will store each element of collection one by one.
„datatype‟ is any valid datatype in Java which is same as collection.
„collection‟ is any collection such as array, stack, linked list, vector etc.
‘continue’statement:
„continue‟statement is specially used in looping statement.
When „continue‟ statement is executed then control transferred back to check the condition
in loop and rest of statements are ignored.
While ( condition1 )
if ( condition2 )
// Program that demonstrate use of „continue‟ statement
classmyloop
{
public static void main(String []st)
{
int i=10;
while(i>=1)
{
if(i>5)
{
[Link](“\t”+i);
i--;
continue;
}
else
{
i--;
}
}
}
Reading Inputes by Scanner class
We can read varieties of inputs from keyboard or from text file using methods of „Scanner‟
class.
Scanner class belongs to „[Link]‟ package.
When Scanner class receives input, it breaks the input into several pieces, called „tokens‟
and these tokens can be retrieved using object of Scanner class.
Note that: Following methods of Scanner class are non-static therefore they are called or
accessed with the help of object of Scanner class.
We can create object of Scanner class as follows:
[Link];
class cricket
{
public static void main(String []args)
{
byte no;
String name;
long contact;
int t_sc;
shortt_wk;
floatball_avg;
double bat_avg;
Scanner sc=new Scanner([Link]);
[Link]("Enter Cricketer No= ");
no=[Link]();
[Link]("Enter Cricketer Name= ");
name=[Link]();
[Link]("Enter Cricketer Contact No= ");
contact=[Link]();
[Link]("Enter Cricketer Total Score= ");
t_sc=[Link]();
[Link]("Enter Cricketer Wickets= ");
t_wk=[Link]();
[Link]("Enter Ball AVG= ");
ball_avg=[Link]();
[Link]("Enter Batting AVG= ");
bat_avg=[Link]();
[Link](" ");
[Link]("CricketerNO="+no);
[Link]("CricketerName="+name);
[Link]("ContactNo="+contact);
[Link]("Total SCore="+t_sc);
[Link]("Total Wickets="+t_wk);
[Link]("Balling AVG="+ball_avg);
[Link]("Batting AVG="+bat_avg);
}
}
Array
“An Array is collection of homogeneous (having same type) elements or items referred by
common name”
In an array the individual element is accessed with the help of integer value and is called
subscript or index. Also all elements of array are stored in continuous memory allocation.
Note that:
We know that, In C/C++ language, memory for array is get allocated at compile time
(i.e. static memory allocation)
But, in JAVA everything is dynamic i.e. for variable, array, objects etc. memory is get
allocated at run time (Dynamic memory allocation) by JVM
Types of Array:
Depending on number of subscripts used in array, array having three types:
1) One Dimensional array: (1 D array)
“The array having only one subscript is called as One dimensional array”
Declaration Syntax:
here;
datatype is any valid datatype in JAVA language
array_nameis name of array which is an identifier.
„size‟ is integer value that denotes total number of elements stored in array
„new‟ is an operator.
e.g.
1) int x[ ]=new int[5];//declares array „x‟ & allocates memory for 5 integers
OR
int [ ]x =new int[5];
here; “p‟ is integer type array which stores five integers at a time. The storage of all elements in
array „p‟ is shown in following figure:
Index 0 1 2 3 4
Elements of ‘P’ 10 20 30 40 50
Address 110 114 118 122 126
In above figure the elements 10, 20, 30, 40, 50 are stored in array „p‟ at individual index.
That is the element 10 is stored at index 0, 20 is stored at index 1 like that, 50 is stored at
index 4. Also all elements are stored in continuous memory location.
Note: Index is nothing but position of the element in an array.
Example of one diamensional array
import [Link].*;
class A
{
Scanner sc=new Scanner([Link]);
int x[]=new int[3];
int i;
void show()
{
[Link]("enter array elements");
for(i=0;i<3;i++)
{
x[i]=[Link]();
}
[Link](" array elements are-:");
for(i=0;i<3;i++)
{
[Link]("\t"+x[i]);
}
}
}
class demo
{
public static void main(String[] args)
{
A p=new A();
[Link]();
}
}
here;
datatype is any valid datatype in Java language
array_nameis name of array which is an identifier.
„Size1‟ is integer value that denotes total number of rows in array
„Size2‟ is integer value that denotes total number of columns in array
e.g.
1) int x[ ][]=newint[3][2]; OR int [ ][ ] x=newint[3][2];
here ;
„x‟ is array which can holds total 6 integers at a time.
3 is rowsize i.e. there are 3 rows in matrix „x‟
2 is columnsize i.e. there are 2 columns in matrix „x‟
Initialization of Two dimensional array:
e.g.
1) int p[ ][ ]={{3,4},{2,9},{7,6}};
2) int z[][]= {{ 5, 3 , 6 } ,{ 1, 7 , 8 } ,{ 9, 4 , 2 } };
„z‟ is integer type two dimensional array which stores nine integers at a time. The storage
here;
of all elements in array „z‟ is shown in following figure:
column
row index 0 1 2 index
0 5 3 6
1 1 7 8
2 9 4 2
In above figure the individual element of array „z‟ is also accessed by following way:
The element 8 can be accessed as z[1][2]
The element 7 can be accessed as z[1][1]
The element 9 can be accessed as z[2][0] etc.
like that we can access all individual elements of matrix „z‟
import [Link].*;
class A class demo
{ {
Scanner sc=new Scanner([Link]); public static void main(String[] args)
int x[][]=new int[2][2]; {
int i,j; A p=new A();
void show() [Link]();
{ }
[Link]("enter array elements"); }
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
x[i][j]=[Link]();
}
}
[Link](" array elements are-:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
[Link]("\t"+x[i][j]);
}
[Link]("");
}
}
}
Multi-Dimensional array:
“The array having more than two subscriptsis called as multi-dimensional array”
Declaration Syntax:
here;
datatype is any valid datatype in Java language.
array_name is an identifier (name given by programmer)
size1, size2,………sizeN are integer constants and that denotes total
number of elements stored in an array.
e.g. 1) int z[][][]=newint[2][4][3];
The above array is the multidimensional array having three subscripts and which stores
12 integer values at a time.
That is above multi-dimensional array stores 2 sets of 4*3 matrices.
2) float x[ ][][][]=new float[2][3][2][2];
The above array „x‟ is also multidimensional array having four subscripts and which stores
24 float values at a time.
Initialization of Multi-dimensional array:
0 1
0 1 2
x[0] 1 4 5
2 7 8
3 3 6
0 1
0 11 12
x[1] 1 14 15
2 17 18
3 13 16
From above, multi-dimensional array we can access individual element as follow:
X[0][1][0] access 4
X[0][2][1] access 8
X[0][3][0] access 3
X[1][1][1] access 15
X[1][2][0] access 17
X[1][3][1] access 16
‘length’ property of array:
„length‟ is property of an array that returns one integer value which is nothing but size of array.
We use this property as follows:
intvar=[Link];
Here, „var‟ is an int type variable which stores size of array return by [Link].
Exampl:
1) intarr[ ]=new int[10]; //declares array with 10 size
arr[0]=45;
arr[1]=90;
intsz=[Link]; //returns array size
[Link](“Array Size=”+sz);
OUTPUT:
Array Size=10
Note that: In above example „arr‟ is array declared with 10 size. And arr[0] and arr[1] are
initialized with values 45 and 90 respectively. But „[Link]‟ statement returns value 10 which
is size of array (Since, „length‟ property returns size of [Link] not returns array elements)
Also, in case of 2D or Multi-dimensional array, „length‟ property returns number of rows of the
array.
Following program shows use of „length‟ property of array.
classarrsize
{
public static void main(String s[])
{
int a[ ]={7,3,9,7,2,4};
int b[ ][ ]=new int[5][7];
int c[ ][ ][ ]=new int[9][3][2];
intx,y,z;
x=[Link];
y=[Link];
z=[Link];
[Link]("1D array size="+x);
[Link]("2D array size="+y);
[Link]("Multi array size="+z);
}
}
Jagged Array:
Jagged array is special array found in Java, which can stores group of different types of
arrays in [Link] is, Jagged array can stores 1D, 2D or multi-dimensional arrays of
different sizes.
When we create jagged array then other arrays can become an elements of created jagged
array.
Jagged array are also called as “Irregular multi-dimensional” array.
Jagged array is helpful when dealing with group of arrays with different sizes.
Following example shows jagged array:
1) int x[ ][ ]=new [2][ ];
Here, „x‟ is jagged array having size 2i.e it stores two 1D arrays. So its elements will
stores from x[0] and x[1].
In given expression: intx[ ][ ]=new int[2][ ];
Here, last pair of brace or bracket is empty. It means that it is jagged array for 1D array.
And thereforex[0] and x[1] can individually stores 1D array separately.
After declaration of jagged array, we have to allocate memory for x[0] and x[1] which is given as
follow:
x[0]=new int[2];
x[1]=new int[3];
Here,
x[0] can have 2 elements which can stores in „x‟ at x[0][0] and x[0][1]
x[1] can have 3 elements which can stores in „x‟ at x[1][0] , x[1][1] and x[1][2]
And complete jagged array „x‟ is shown as follow:
0 1
x[0]
0 1 2
x[1]
class myjag
class myjag {
{ public static void main(String[] args)
public static void main(String[] args) {
{
int z[ ][ ][ ]=new int [3][ ][ ];
int z[ ][ ]=new int [2][ ];
z[0]=new int[2][2];
z[0]=new int[4]; z[1]=new int[3][2];
z[1]=new int[2]; z[2]=new int[3][3];
z[0][0]=10; z[0][0][0]=10;
z[0][1]=11; z[0][0][1]=11;
z[0][2]=12; z[0][1][0]=12;
z[0][3]=13; z[0][1][1]=13;
for(int i=0;i<=1;i++)
for(int i=0;i<=3;i++) {
{ for(int j=0;j<=1;j++)
{
[Link]("\t"+z[0][i]); [Link]("\t"+z[0][i][j]);
} }
[Link]();
[Link](); }
[Link](); [Link]();
[Link]();
z[1][0]=5;
z[1][1]=6; z[1][0][0]=5;
z[1][0][1]=6;
for(int i=0;i<=1;i++) z[1][1][0]=7;
{ z[1][1][1]=8;
z[1][2][0]=9;
[Link]("\t"+z[1][i]); z[1][2][1]=4;
for(int i=0;i<=2;i++)
} {
for(int j=0;j<=1;j++)
} {
} [Link]("\t"+z[1][i][j]);
}
[Link]();
}
[Link]();
[Link]();
z[2][0][0]=11;
z[2][0][1]=22;
z[2][0][2]=33;
z[2][1][0]=44;
z[2][1][1]=55;
z[2][1][2]=66;
z[2][2][0]=77;
z[2][2][1]=88;
z[2][2][2]=99;
for(int i=0;i<=2;i++)
{
for(int j=0;j<=2;j++)
{
[Link]("\t"+z[2][i][j]);
}
[Link]();
}
}
}
STRING
Introduction:
Most of data that transmit from one place to another place is in the form of group of characters.
Such group or set of characters are called as “String”.
We know that, in case of C/C++ language string is nothing but „array of characters‟ & that
terminates with „\0‟ character i.e. NULL character. But this is not true in Java language.
In JAVA, “String is nothing but Object of String class” and which is not array of character. Also,
in JAVA we can create array of character but it is not treated as string.
While dealing with string, JAVA language supports special class called “String” class which
was found under “[Link]” package.
Creating Strings in Java:
We can create Sting in Java by three ways:
We can create a String by assigning group of characters to a String type object:
String str; //declare string type object
str= “Hello”; //assign a group of characters to it
Above two statements can be combined as follow:
String str= “Hello”;
In this case, JVM creates an object & stores the string “Hello”
Here, „s‟ is an object of String class and that contains the string.
„len‟ is integer variable used to store length of string.
E.g.
class stringLen
{
public static void main(String args[ ])
{
String str=new String(“Hello”);
int len=[Link]( );
[Link](“Length=”+len);
}
}
OUTPUT:
Length=5
2) concat ( ) :
This method is used to concatenate two strings together.
That is, it concatenates second string at the end of first string and returns concatenated
string as a result.
Syntax:
String str = [Link](s2);
Here, „s1‟ is an object of String class and that contains the first string.
„s2‟ is also object of String class and that contains the second string.
„str‟ is also string that stores concatenated string.
E.g.
class stringCat
{
public static void main(String args[ ])
{
String s1= “Delhi”;
String s2= “Mumbai”;
String str=[Link](s2);
[Link](str);
}
}
OUTPUT: DelhiMumbai
3) charAt ( ) :
This method accepts one integer value and returns one character from string
corresponding to passed integer value
That is, it accepts index value (position of element) and returns corresponding character
from string.
Syntax:
char ch = [Link](pos);
Here, „s‟ is an object of String class and that contains the string.
„pos‟ is an integer value.
„ch‟ is char variable which stores returned character from string at position „pos‟
E.g.
class stringChar
{
public static void main(String args[ ])
{
String s= “Delhi”;
char ch=[Link](3);
[Link](ch);
}
}
OUTPUT:
h
4) equals( ) :
This method is also used to compare two strings with each other for equality.
This method returns boolean value depending upon Strings content.
It returns boolean value „true‟ if both strings are equal otherwise it returns „false‟.
Syntax:
boolean m = [Link](s2);
Here, „s1‟ is an object of String class and that contains first string.
„s2‟ is also an object of String class and that contains second string.
„m‟ is boolean variable to store returned value.
E.g. class stringEqual
{
public static void main(String args[ ])
{
String s1= “box”;
String s2= “BOX”;
boolean m= [Link](s2);
if (m = = true)
[Link](“Both strings are equal”);
else
[Link](“Strings are not equal”);
}
}
OUTPUT: Strings are not equal
5) equalsIgnoreCase( ) :
This method is also used to compare two strings with each other for equality. But it
ignores the case of characters present in strings. i.e. it treated “box” string same as
“BOX”
This method returns boolean value depending upon Strings content.
It returns boolean value „true‟ if both strings are equal otherwise it returns „false‟.
Syntax:
boolean m = [Link](s2);
Here, „s1‟ is an object of String class and that contains first string.
„s2‟ is also an object of String class and that contains second string.
„m‟ is boolean variable to store returned value.
E.g.
class stringEqual
{
public static void main(String args[ ])
{
String s1= “box”;
String s2= “BOX”;
boolean m= [Link](s2);
if (m = = true)
[Link](“Both strings are equal”);
else
[Link](“Strings are not equal”);
}
}
OUTPUT: Both Strings are equal
6) compareTo ( ) :
This method is used to compare two strings with each other for equality.
This method returns one integer value depending upon Strings content.
It returned value is Zero then both strings are equal.
If returned value is positive then first string is greater than second string.
If returned value is negative then Second string is greater than first string.
Syntax:
int m = [Link](s2);
Here, „s1‟ is an object of String class and that contains first string.
„s2‟ is also an object of String class and that contains second string.
„m‟ is integer variable to store returned value.
E.g.
class stringCmp
{
public static void main(String args[ ])
{
String s1= “abc”;
String s2= “abd”;
int m= [Link](s2);
if (m = = 0)
[Link](“Both strings are equal”);
else if( m > 0)
[Link](“First string is greater”);
else
[Link](“Second string is greater”);
}
}
OUTPUT: Second string is greater
7) compareToIgnoreCase( ) :
This method is also used to compare two strings with each other for equality. But it
ignores the case of characters present in strings. i.e. it treated “box” string same as
“BOX”
This method returns one integer value depending upon Strings content.
If returned value is Zero then both strings are equal.
If returned value is positive then first string is greater than second string.
If returned value is negative then Second string is greater than first string.
Syntax:
int m = [Link](s2);
Here, „s1‟ is an object of String class and that contains first string.
„s2‟ is also an object of String class and that contains second string.
„m‟ is integer variable to store returned value.
E.g.
class stringCmp
{
public static void main(String args[ ])
{
String s1= “box”;
String s2= “BOX”;
int m= [Link](s2);
if (m = = 0)
[Link](“Both strings are equal”);
else if( m > 0)
[Link](“First string is greater”);
else
[Link](“Second string is greater”);
}
}
OUTPUT:
Both strings are equal
8) startsWith( ) :
This method returns boolean value „true‟ if first string starts with second string otherwise
it returns „false‟.
Syntax:
boolean m = [Link](s2);
Here, „s1‟ is an object of String class and that contains first string.
„s2‟ is also an object of String class and that contains second string.
„m‟ is boolean variable to store returned value.
E.g.
class stringStart
{
public static void main(String args[ ])
{
String s1= “Box is heavy”;
String s2= “Box”;
boolean m= [Link](s2);
if (m = = true)
[Link](“First string start with second string”);
else
[Link](“First string NOT start with second string”);
}
}
OUTPUT: First string start with second string
9) endsWith( ) :
This method returns boolean value „true‟ if first string ends with second string otherwise
it returns „false‟.
Syntax:
boolean m = [Link](s2);
Here, „s1‟ is an object of String class and that contains first string.
„s2‟ is also an object of String class and that contains second string.
„m‟ is boolean variable to store returned value.
E.g.
class stringEnd
{
public static void main(String args[ ])
{
String s1= “Box is heavy”;
String s2= “heavy”;
boolean m= [Link](s2);
if (m = = true)
[Link](“First string ends with second string”);
else
[Link](“First string NOT ends with second string”);
}
}
OUTPUT: First string ends with second string
10) indexOf( ) :
This method returns integer value which is nothing but first position of substring into
main string.
If substring is not found in main string then it returns negative value.
Syntax:
int m = [Link](s2);
Here, „s1‟ is an object of String class and that contains first string.
„s2‟ is also an object of String class and that contains second string.
„m‟ is integer variable to store returned value.
E.g.
class stringFirstIndex
{
public static void main(String args[ ])
{
String s1= “Box is heavy and it is dirty”;
String s2= “is”;
int m= [Link](s2);
if (m < 0 )
[Link](“Substring Not found”);
else
[Link](“Substring found at= ”+m);
}
}
OUTPUT: Substring found at= 4
11) lastIndexOf( ) :
This method returns integer value which is nothing but last position of substring into
main string.
If substring is not found in main string then it returns negative value.
Syntax:
int m = [Link](s2);
Here, „s1‟ is an object of String class and that contains first string.
„s2‟ is also an object of String class and that contains second string.
„m‟ is integer variable to store returned value.
E.g.
class stringLastIndex
{
public static void main(String args[ ])
{
String s1= “Box is heavy and it is dirty”;
String s2= “is”;
int m= [Link](s2);
if (m < 0 )
[Link](“Substring Not found”);
else
[Link](“Substring found at= ”+m);
}
}
OUTPUT: Substring found at= 20
12) replace( ) :
This method replaces characters of existing string with new given character.
Syntax:
String str = [Link](old_char,new_char);
13) substring( ) :
This method has two forms:-
I) substring(int):
This method returns a new string consisting of all characters from given position to the
end of string.
Syntax:
String str = [Link](pos);
II) substring(int,int):
This method returns a new string consisting of all characters from given first position to
the last position -1.
Syntax:
String str = [Link](pos1,pos2);
15) toUpperCase( ) :
This method converts all characters of string into upper case and returns that upper-
cased string as result.
Syntax: String str = [Link]( );
Here, „s‟ is an object of String class and that contains string.
„str‟ is also an object of String that stores returned upper-cased string.
E.g.
class stringUpper
{
public static void main(String args[ ])
{
String s= “box is heavy”;
String str= [Link]( );
[Link](str);
}
}
OUTPUT: BOX IS HEAVY
16) getChars( ) :
This method copies characters from string into character array.
Characters copied into character array from starting position „pos1‟ up to last position
„pos2-1‟ to location starting from „pos3‟ in a character array.
Syntax: [Link](pos1,pos2,arr,pos3);
Here, „s‟ is an object of String class and that contains string.
„pos1‟ is an integer value represents starting position from which string copied.
„pos2‟ is an integer value represents ending position & string copied ends at pos2-1 index.
„arr‟ is character array that stores copied characters from string „s‟.
„pos3‟ is an integer value from which character array „arr‟ stores the copied character.
E.g.
class stringGetchar
{
public static void main(String args[ ])
{
String s= "Box is heavy";
char [ ]arr=new char[20];
[Link](7,11,arr,0);
for(char i:arr)
{
[Link](i);
}
}
}
OUTPUT: heav
17) trim( ) :
This method removes unwanted i.e. extra spaces which were found before and after the
string.
Note that: This method does not remove extra spaces between two words of string.
Syntax: String str = [Link]( );
Here, „s‟ is an object of String class and that contains string.
„str‟ is also object of String class used to store resultant string.
E.g.
18) split( ) :
This method splits or cuts the given string into number of pieces (sub strings)
corresponding to delimiter (specified character) and store it into array of string.
Syntax: String [ ] str = [Link](delimiter);
String Comparison:
* We know that for comparison of two or more quantities with each other, we use relational
operators like <, >, <=, >=, !=, ==.
* But for string comparison, relational operators are not suitable because these operators
compare reference (address) of object with each other. They not compare strings contents.
* For that purpose, compareTo() or equals() methods are used to compare two strings. And these
functions compare strings contents for equality.
Consider following example;
In above example, we got output “Strings are NOT same” still content of strings are same.
This is due to relational operator (= =) because it compares address (address is in
Hexadecimal number) of both strings, it not compares strings content.
When an object is created by JVM, it returns the memory address of the object as a
hexadecimal number which is called “object reference” and this object reference is
separate for every object. i.e. whenever an abject is created, a new address number is
allotted to it by JVM.
Now, consider another example:
In above example, we got output “Strings are same” which is right because equals( )
method compares strings content, not their addresses.
Above mentioned concepts shown in following figures:
Now, consider One another example: There is slightly change in object creation of String. Here,
object of String is created without using „new‟ object:
In above example, we got output “Strings are same”. Still we are using relational operator
(= =) for string comparison. How it is possible?
Here, String objects are created without using „new‟ operator at that time JVM uses
separate memory block which is called „string constant pool‟ and such objects are store
there.
When first statement i.e. String s1= “Hello” is executed then JVM insert object „s1‟ into
„string constant pool‟ with separate address.
And when second statement i.e. String s2 “Hello” is executed then JVM, searches in
„string constant pool‟ to know whether the object with same content is already exist there
or not?
If any object with same content is found in „string constant pool‟ then JVM just
attach second object at reference (address) of first object.
If any object with same content is NOT found in „string constant pool‟ then JVM
allocate separate reference (address) to second object.
Here, content of String „s1‟ and „s2‟ are same therefore JVM just attach „s2‟ at address of
„s1‟. And that‟s made both objects addresses are same. And hence, we got output “Strings
are same”
Above mentioned concept is shown in following fig.
Immutability of String:
We know that, an „object‟ is basic runtime entity that holds data or some content. And every
Objects can broadly classified into two categories viz: 1) Mutable object 2) Immutable object.
Let‟s see them in details:
1) Mutable Object:
The objects whose content can be changeable or modifiable are called „Mutable‟ objects.
2) Immutable Object:
The objects whose content can NOT be changeable or modifiable are called „Immutable‟ Objects.
And Object of String class is Immutable i.e. we cannot modify the content of String object. And
hence, we can say that „String‟ Class is Immutable class.
Consider following example to test immutability of String.
In above example we got output “DataBase”. It seems that, the content of „s1‟ is modified.
Because, earlier „s1‟ has content “Data” and „s2‟ has content “Base”. And after „s1+s2‟ they are
joined together and total string becomes “DataBase”. This result is assigned to „s1‟. If „s1‟ is
mutable then it gets new string “DataBase” and we also got “DataBase” as result.
But „s1‟ is object of String class & we learned that „String objects are immutable‟, then
how we got result “DataBase”?
Definitely String object „s1‟ is immutable. Consider following figure that will explain this
concept briefly:
In the program, JVM creates two objects „s1‟ and „s2‟ separately, as shown in above figure.
When „s1+s2‟ is done then JVM creates new object and stores „DataBase‟ in that created object.
After creating new object, the reference „s1‟ is just attached or assigned to newly created object.
Remember, it does not modify existing content of „s1‟. And that‟s why we are called „String objects
are immutable.‟
The old object that contains „Data‟ has lost its reference. So it is called „unreferenced object‟ and
garbage collector remove it from memory.
CLASSES AND OBJECTS
Class:
„Class‟ is user defined data type which is collection of variables and methods.
That is, these variables are called „properties or attributes‟ and methods are called „actions‟
Also, „Class‟ is blue print for object because everything in class can also hold by object. i.e.
class decides how the object was ?
Since, all variables and methods are also available in objects, because they are created from
class therefore they are called „instance variable‟ and „instance method‟.
Consider, following defined class for „person‟.
class person
{
int age;
String name; //Properties- i.e. instance variables of class
In above, example person is class that consists of instance variables (properties)age, nameand
having instance method (action)talk( ).
Object:
„Object‟ is basic run time entity that holds entire data (variables and methods) of class.
Object is also called as „instance‟ of class.
When object is created then that created object is stored in „Heap area‟ by JVM.
Also, whenever an object is created then JVM allocates separate memory reference (address)
for created object called „hash code‟
This „hash code‟ is unique hexadecimal number created by JVM for object.
We can also see hash code of every created object using hashCode() method of Object class of
[Link] package.
Syntax to create object:
class_name obj= new class_name( );
OUT PUT:
First Object's Hash Code=53ab83406
Second Object's Hash Code=1b6164678
private:
„private‟ members of class are only accessible by methods of same class therefore they have
class scope. That is private members are not accessible outside the class.
They are accessible:
1) Within methods of same class.
They are NOT accessible:
1) Within methods of sub classes.
2) Within methods of other class of same package.
3) Within methods of class of other package.
protected:
The accessibility of „protected‟ members of class is given as follow;
They are accessible:
1) Within methods of same class.
2) Within methods of sub classes.
3) Within methods of other class of same package.
4) Within methods of classes of other package (Since, other package class should be sub
class)
They are NOT accessible:
1) Within methods of classes of other package (If other package class should NOT be sub
Class)
default:
If no access specifier is written by the programmer then, Java compiler uses „default‟ access
specifier.
The „default‟ members of class should be accessible by the methods of class of same package i.e.
they are not accessible out the package. Therefore ‘default’ access specifier has ‘package’ scope.
They are accessible:
1) Within methods of same class.
2) Within methods of sub classes.
3) Within methods of other class of same package.
They are NOT accessible:
1) Within methods of classes of other package.
Methods in Java:
In Java, there are two kinds of methods found;
1) Instance Methods (Non-Static Methods) 2) Class Methods (Static Methods)
Let us see all these methods in details:
1) Instance Methods (Non-Static Methods):
The method which is defined within class body without using keyword „static‟ are called as
„Instance methods or Non-static methods‟.
These types of methods are act on „instance variable‟ of class.
They are called „Instance‟ method because their content is in instance (object) of class.
Instance methods are called with the help of object of class using syntax:
[Link](arg1,arg2, --- );
One specialty of instance method is that they are capable to access instance variable (non-
static variable) and class variable (static variable) directly.
2) Class Methods (Static Methods):
The method which is defined within class body using keyword ‘static’ is called as „class
methods or static methods‟.
These types of methods are act on „class variable (static variable)‟ of class.
They are called „Class‟ methods because they are defined using „static‟ keyword & it is
related with class.
Class methods are called with the help of class name using syntax:
Class_Name.method(arg1,arg2, ---- );
Class methods are capable to access only class variable (static variable) directly.
Still, if we want to access instance variable inside class method then it can be accessed only
by using object of class.
(HOME WORK: Write Difference between Instance Methods and Class Methods)
Types of Instance Methods:
Further, Instance methods are of two types:
1) Accessor Method 2) Mutator Method
Let‟s see these methods in details:
1) Accessor Method:
This type of instance methods are only access or read instance variables i.e. they do not modify
value of instance variable are called as “Accessor Method”
2) Mutator Method:
This type of instance methods are access or read instance variables and also modify value of
instance variable are called as “Mutator Method”.
Following program shows the use of Accessor and Mutator methods.
class Access class Call_me
{ {
int n; public static void main(String [ ] args)
void get( ) //mutator method {
{ Access t=new Access();
n=50; [Link]();
} [Link]();
void show( ) //Accessor method }
{ }
[Link]("Value="+n);
}
}
Static data:
We know that, for single class we can create multiple objects. And each object holds their
individual record. But there are some data which are common to all objects in such
situation that data can be made as static.
Once the data is made as static then this data is common to all objects of class.
In short, static data is common data and which shared by all objects of class.
Only one copy of static data members is maintained for entire class therefore it is shared
among all objects.
Static data by default initialized to zero.
Static data are initialized at once therefore it is used like a counter.
Static data are stored separately rather than as a part of an object.
Syntax to declare static variable:
Here,
„static‟ is keyword which is used to declare member as static
„datatype‟ is any valid data type in Java.
„variable‟ is name of static variable.
Following fig. shows sharing of static data by different objects of class:
In above fig. static data of class is common to all objects Object1, Object2, Object3, Object4. Or
the same copy of static data is shared among all objects.
Following program demonstrate the use of static variable that counts total object created for class:
class count class call_count
{ {
static int cnt; public static void main(String [ ]args)
count( ) {
{ count a=new count( );
cnt++; count b=new count( );
} count c=new count( );
static void show( ) count d=new count( );
{ [Link]( );
[Link]("Total Objects= "+cnt); }
} }
} OUTPUT: Total Objects= 4
Constructor:
The constructor is special method whose name is same as that of class name.
The main task of constructor is to initialize values for object of its class.
It is called constructor because it construct the values for object of the class.
The constructors are implicitly invoked by the compiler whenever an object of class is
created.
A constructor is called concurrently when the object creation is going on. By the time,
object creation is completed, the constructor execution is also completed.
Example:
Consider, there is one class having name “person” then its constructor is given
as:
class person
{
person( ) // constructor
{
}
}
Properties/Characteristics/Features of Constructor:
1) Constructor name is same as that of class name.
2) Constructor does not have any return type even void.
3) Constructors are implicitly invoked by the compiler whenever object of class is created.
4) Constructor can be overloaded.
5) Constructors are not static.
6) Call to constructor is depends on number of objects created for class.
Types of constructor:
Depending upon arguments passed to constructor, it has two types.
1) Default Constructor
2) Parameterized constructor
NOTE:
1) Java language does not support for copy constructor.
2) If we specify return type for constructor then Java compiler treats that method as normal
method.
1) Default constructor:
The constructor that does not have any argument or parameter as input, such constructor is
called as “Default Constructor”.
Default constructor is implicitly invoked by compiler whenever object of class is crated
Syntax:
class class_name
{
class_name( ) // default constructor.
{
}
}
}
}
In above program, we pass two objects „x’, ‘y’ of „emp’ class to doswap( ) method. Here,
objects are pass by value. These passed objects are stored in corresponding formal objects „a’
and ‘b’.
We do some swapping mechanism over objects ‘a’ and ‘b’ inside doswap( ) method that does
not affects on values of ‘id’ hold by objects ‘x’ and ‘y’ because they are passed as pass by
value.
Here, we interchange the objects that interchange the references of objects. That‟s why we
got same output corresponding to input i.e. no interchanging of ‘id’ is done.
This is shown in following figure.
Passing Array to method:
Like normal variable, we can also pass array to the method.
In java array can be pass to method by using only array name.
Following program demonstrate passing array to method.
class passarr class pass
{ {
void show(int z[ ]) public static void main(String [ ] args)
{ {
[Link]("Array Ele= "); int x[ ]={10,20,30,40,50};
for( int i : z) passarr p=new passarr( );
{ [Link](x);
[Link](" "+i); }
} }
} OUTPUT:
} Array Ele= 10 20 30 40 50
Nesting of classes:
If we define or declare one class inside another class then such a form is called as “class
within class or Nested class”
Using this facility complex data type can be created.
Nested class is used to access elements of class which is part of another class.
Syntax for nested class:
class outerClass
{
class innerClass
{
class superinnerClass
{
}
}
}
Syntax to create objects:
1) Create object of outer class as:
outerClass obj1=new outerClass( );
2) Create object of inner class as:
[Link] obj2=[Link] innerClass( );
3) Create object of supper inner class as:
[Link] obj3=[Link] superinnerClass( );
Static Block:
A static block is block of statements declared with keyword „static‟, something like this:
static
{
Static block has highest priority therefore JVM interprets this block first even before main( )
method also.
In, Java interpretation, JVM first searches for static block if it is found then JVM executes it.
If JVM not found any static block then it searches for main( ) method for interpretation. If
main( ) method founds then JVM execute it. If main( ) method not found then it gives error.
Also, Single Java program may contains multiple static blocks; in such situation JVM
executes them one after another in sequence (FIFO) manner.
Following program demonstrate use of static block.
class Test
{
static
{
[Link]("First");
}
public static void main(String [ ] as)
{
[Link]("Main Method");
}
static
{
[Link]("Third");
}
static
{
[Link]("Second");
}
}
OUTPUT:
First
Third
Second
Main Method
Note:
Java program may be compile and run without main( ) method with presence of static block.
The keyword ‘this’:
When an object is created to a class, then JVM implicitly create default reference to created
object and that default reference is called „this‟.
„this‟ keyword always refers to current object of class.
„this‟ is non-static therefore it cannot use within static method or static block.
Generally, we write instance variable, methods and constructors in a class. All these
members are stored in object. As well as all these members are also refers by ‘this’ reference.
„this‟ reference is shown in following figure:
Use of „this‟:
We know that „this‟ is reference for current object of class therefore it is used like object i.e.
1) „this‟ is used to invoke default constructor of present class using syntax=> this( );
Also, we made call to parameterized constructor of present class using syntax=>
this (arg1, arg2, ....... );
2) „this‟ is also used to call instance methods of class using syntax=> [Link](arg1,arg2, ... );
3) „this‟ is also used to access instance variable of class using syntax=> [Link];
4) When instance variables of class and formal parameters of methods are same then that
creates confusion. To solve this confusion „this’ keyword is used to access instance variables
of class.
Following program shows use of „this‟ keyword:
class sample
{
int age;
String name;
sample( )
{
this(45,"Sachin"); //call to parameterized constructor
}
sample( int age, String name)
{
/* Instance variable & formal parameters are same.
Therefore 'this' is used to access instance variable*/
[Link]=age;
[Link]=name;
}
void show( )
{
[Link]("Age="+age);
[Link]("Name="+name);
}
}
class call_sample
{
public static void main(String [ ]args)
{
sample p=new sample( );
[Link]( );
}
}
OUTPUT:
Age= 45
Name=Sachin
Inheritance
Introduction:
We know that, inheritance is one of the most important object oriented concept and Java language
supports it.
The main concept behind inheritance is reusability of code (Software) is possible by adding some extra
feature into existing software without modifying it.
In java language, ‘Object’ is super class of all classes even your own defined class also.
Definition:
“The mechanism of creating new class from existing class is called as Inheritance”.
The existing or old class is called as ‘Base class’ or ‘Parent class’ or ‘Super class’ and new class is called
as ‘Derived class’ or ‘Child class’ or ‘Sub class’.
While deriving the new class from exiting one then,the derived class will have some or all the features of
existing class and also it can add its own featuresi.e sub class will acquires features of base class without
modifying it.
When a new class is derived from exiting class then all public,protected and default data of base class
can easily accessed into its derived class where as private data of baseclass cannot inherited i.e. this
private data cannot accessed inderived class.
Consider following example:
In above figure class B is inherited from class A. Therefore class A is called as Super class or orparent class or
base class of class Bwhere asclass B is called as Sub class or child class or derived class.
Need or Features of Inheritance:
1) It is always nice to use existing software instead of creating new one by adding some extra features
without modifying it. This can be done by only inheritance.
2) Due to inheritance software cost is reduces.
3) Due to inheritance software developing time is also reduces.
4) Inheritance allows reusability of code.
5) Due to inheritance we can add some enhancement to the base class without modifying it this is due to
creating new class from exiting one.
Syntax to derive new class from existing class:
Here;
class is keyword to define class.
extends is keyword used to create or derive or extends new class.
derived_class_name is name of newly created class which is an identifier.
base_class_name is name of existing class which is also an identifier.
Types (forms) of Inheritance:
Depending upon number of base classes and number of derived classes and their arrangement, inheritance has
following types.
1) Single Inheritance:
In case of Single inheritance there is only one base class from which we
derive only one new class.
e.g.
From above figure we can write single inheritance as:
class A
{
//Declaration of Variables and definition of methods.
}
class B extends A
{
//Declaration of Variables and definition of methods.
}
[Link];
class A
{
Int x,y;
Scanner sc=new Scanner([Link]);
void get( )
{
[Link]("Enter two numbers ");
x=[Link]( );
y=[Link]( );
}
}
class add extends A
{
int z;
void doadd( )
{
z=x+y;
[Link]("Addition="+z);
}
}
classsingle
{
publicstatic void main(String [ ] args)
{
add p=new add( );
[Link]();
[Link]( );
}
}
‘super’ keyword:
If we create an object of super class then we can access only super class members, i.e. we are not able to
access the sub class members using object of super class.
But, if we create an object of sub class, then all the members of super class as well as sub class are easily
accessible by object of sub class. And that’s why we always create an object of sub class instead of super
class.
Some time, both super class and sub class may have members (variable or methods) with same name in
such situation, only members of sub class is accessible with its object. Here, super class members are not
considered. And hence, in such condition if we want to access super class members into its sub class then
‘super’ keyword is used along with member of base class.
Use of ‘super’ keyword:
‘super’ keyword is used to access members of base class into its derived class.
We can access, instance variables of base class into its derived class using syntax:
[Link];
We can access, methods of base class into its derived class using syntax:
[Link](arg1,arg2, ...);
Note that, we need not call the default constructor of super class because it is defaultly available to its sub
class. And hence, We can made call to parameterized constructor of base class into its derived class using
syntax:
super( arg1,arg2,.....);
}
class B extends A
{
int x=70;
void get( )
{
[Link]("Super Class variable="+super.x); //access ‘x’ of base class using ‘super’ keyword
[Link]("Sub Class variable="+x);
}
}
class use
{
public static void main(String [ ] args)
{
B p=new B( );
[Link]( );
}
}
OUTPUT:
Super Class variable= 55
Sub Class variable= 70
2) Multilevel Inheritance:
In case of multilevel inheritance we can derive new class from another derived classes, further from
derived classes we again derive new class and so on.
Also, there are some levels of inheritances therefore it is called as “Multilevel inheritance”
E.g.
From above figure we can write multilevel inheritance as fallow:
class A
{
//Declaration of Variables and definition of methods.
}
class B extends A
{
//Declaration of Variables and definition of methods.
}
class C extends B
{
//Declaration of Variables and definition of methods.
}
class A
{
//Declaration of Variables and definition of methods.
}
class B extends A
{
//Declaration of Variables and definition of methods.
}
class C extends A
{
//Declaration of Variables and definition of methods.
}
Implementation of Hierarchical Inheritance is as fallow:
Figure:
class A
{
//Declaration of Variables and definition of methods.
}
class B extends A
{
//Declaration of Variables and definition of methods.
}
class C extends B
{
//Declaration of Variables and definition of methods.
}
class D extends A
{
//Declaration of Variables and definition of methods.
}
In above fig, Super classes [Link] A, Class B and Class C has same member ‘int p’ and from these classes
Class D is derived or extended. In this case, Class D has confusion regarding with copy of‘int p’. That is
Class Ddoes not know whose copy of ‘int p’ is accessed.
Also, class D extends A, B, Csuch syntax is invalid in Java.
If Java does not support for ‘Multiple inheritance’ then it is not considered as pure OOP language. In fact
Java is pure OOP language.
But, In Java, multiple inheritance can be implemented using ‘interface’ concept. We can implement
multiple inheritance latter in chapter ‘Interface’.
Constructor in Inheritance:
We know that, constructor is used to initialize the object.
Without initializing base class members, the derived class members cannot initializes therefore
compiler automatically (implicitly) invoke base class constructor first and then the derived class
constructor is invoked.
That is order of execution of constructor in inheritance is base to derive.
Every constructor in derived class first implicitly make call to default constructor of base class.
When a class is derived from base class then derived class has implicitly copy of default constructor of
base class.
Following program shows invocation of constructor in Inheritance:
class base
{
base( )
{
[Link]("Base class default Constructor ");
}
base(int x)
{
[Link]("Base class Parameterized constructor="+x);
}
}
class derive extends base
{
derive( )
{
[Link]("Derived class default Constructor ");
}
derive(int p)
{
super(p); //call to base class parameterized constructor
[Link]("Derived class Parameterized constructor="+p);
}
}
class myConstructor
{
public static void main(String args[ ])
{
derive p=new derive( );
derive q=new derive(75);
}
}
Polymorphism
Introduction:
Polymorphism is Greek word that consists of two words viz. ‘poly’ & ‘morphism’
‘poly’ means ‘many’ and ‘morphism’ means ‘forms’.
The ability to define or write multiple methods with same name that performs different task such concept
is called ‘Polymorphism’ .
Advantage of polymorphism is that, the programmer can write flexible code depending upon signature
(type of argument & number of argument accept by method) of method.
Polymorphism can be classified into two categories that is shown in following figure:
Method Overloading:
Writing or defining multiple methods with same name within same class but all defined methods are differ from
each other according to their signatures(type of argument & number of argument accept by method) such
concept is called as ‘Method overloading’
Consider following example which shows Method overloading concept:
class myClass
{
void get( )
{
----------
----------
----------
}
void get(int x)
{
----------
----------
----------
}
int get(char y, int z)
{
----------
----------
----------
}
}
In above example, get( ) method is defined three times within same class ‘myClass’ but all these defined
methods are differ from each other according to their signatures& hence, here method overloading is done.
Method Overriding:
When both classes i.e. super class & sub class have same methods with same signatures i.e. both super
class and sub class have same method prototype then sub class method overrides (replaces) the super
class method such a concept is called as ‘Method overriding’
We know that, super class methods are also executed by object of sub class. But, in method overriding
both classes has same methods with same signatures in such situation;JVM only executes methods of sub
class i.e. here sub class method replaces (overrides) the super class method and hence super class method
not executes.
That is we can say that, super class method is overridden by sub class method. And hence super class
method not executed by sub class object.
class first
{
void get(int p)
{
----------
----------
----------
}
}
class second extends first
{
void get(int x)
{
----------
----------
----------
}
}
In above example, ‘first’ is super class whereas ‘second’ is sub class of ‘first’ class.
Also, both classes has get( ) method with same signatures. And if we made call to get() method using object of
sub class then only sub class get( ) method is invoked i.e. sub class method overrides the base class method
&get() method of ‘first’ class never executed. Hence, here method overriding is done.
Difference between method overloading and method overriding:
Method Overloading Method Overriding
1) Defining multiple method with same name with 1) Defining multiple method with same name with
different signature is called ‘Method overloading’ same signature is called ‘Method overriding’
2) Method overloading is done within same class. 2) Method overriding is done within different classes
i.e. in super class & sub class.
3) In method overloading, return type of methods can 3) In method overriding, return type of methods must
be same or different. be same.
4) JVM decides which method has to be called 4) JVM decides which method has to be called
depending upon parameters of methods. depending upon object of sub class or super class.
5) Method overloading is code development. Same 5) Method overriding is code replacement. The sub
method is developed to perform different task. class method overrides (replaces) the super class
method.
Dynamic Polymorphism (Runtime Polymorphism) using Instance method:
Dynamic polymorphism is achieved by method overloading and method overriding by using Instance method.
Let’s seeall these concepts in details:
1) Method Overloading Using Instance methods:
We know that method overloading is nothing but writing or defining multiple methods with same name within same class
but all defined methods are differ from each other according to their signatures(type of argument & number of argument
accept by method).
Here,
We can overload methods using instance method. And to call such instance methods,object of class is required.
Therefore, Java compiler has to wait till object is created and object creation is takes place at runtime of
programtherefore JVM only knows which methods has to execute at runtime. Here Java compiler does not know which
method has to be selected at compile time.
Hence, overloading methods using instance method is type of ‘Runtime or Dynamic polymorphism’
Following program demonstrate the Method overloading concept using instance method:
class myClass class callmyClass
{ {
int p= 45,q= 55; public static void main( String [ ]ar)
void add( ) {
{ myClass t=new myClass( );
[Link](“First=”+(p+q)); [Link]( );
} [Link](5);
void add(int x) [Link](2,3);
{ }
[Link](“Second=”+(p+x)); }
}
void add(int a, int b) OUTPUT:
{ First= 100
[Link](“Third=”+(a+b)); Second= 50
} Third= 5
}
Note:
1) Private methods of base class cannot accessible into its derived class therefore method overriding using
private methods are not possible. That is private methods are not overridden.
2) Remember, we may define same private methods into both base class and derived class but it is not
considered as method overriding because derived class does not know the base class private method and
therefore derived class method not overrides base class private method.
‘final’ Keyword:
We can use ‘final’ keyword before variable declaration or before method definition or before class [Link]
explain all these as follows:
1) final Variable:
If we use ‘final’ keyword before variable declaration then that variable becomes ‘final’ variable.
And final variables are treated in Java as constant.
That is, to declare constant in Java, ‘final’ keyword is used.
final variable cannot be modified because they treated as constant.
Syntax:
final datatype name=value;
here,
‘final’ is keyword.
‘datatype’ is valid data type in java.
‘name’ is an identifier which is constant name .
‘value’ is any constant value assigned to final variable.
Ex:
final double PI= 3.14;
here, Incrementation or Decrementation or initialization other value to ‘PI’ is invalid because it is ‘final’ and
not modified.
2) final Method:
If we use ‘final’ keyword before method definition then that method becomes ‘final’ method.
And final methodscannot override by its derived or sub class. That is sub class method cannot replace
code of its base class final method.
Note that: ‘final’ methods of base class can be accessible into its derived class.
Syntax:
fina lreturn_typeMethod_name( )
{
----------
----------
----------
}
Note:
Final methods of base class cannot override into its derived class therefore method overriding using final methods
are not possible. That is final methods are also not overridden.
But, ‘final’ methods of base class can be accessible into its derived class.
3) finalClass:
If we use ‘final’ keyword before class definition then that class becomes ‘final’ class.
And final classprevents inheritance. That is, we are not able to create or extends new class from ‘final
class’
If we do not allow sub class to access its base class features then base class has to made as ‘final’
Syntax:
final class class_name
{
----------
----------
----------
}
Interface
Introduction:
We know that, Java language does not supports for multiple inheritance but we can implement multiple
inheritance using ‘interface’.
Interface:
An ‘interface’ is collection of only abstract methods.
All the methods of interface by default public & abstract.
Also, ‘interface’ has variables but by default all interface variables are static, final and public.
An interface contains only abstract methods which are all incomplete therefore it is not possible to
create object of interface.
But, we can create separate classes from interface where we can implement all the methods of interface.
These classes are called as ‘implementation’ classes.
Since, ‘implementation classes’ contains method definition therefore we can create object of
implementation classes.
Every implementation class can have its own implementation of abstract methods of the interface.
Syntax to define interface:
interfaceInterface_name
{
datatype var1=value;
return_typeMethod1( );
}
here,
‘interface’ is keyword used to define interface.
‘Interface_name’ is name of interface which is an identifier.
Syntax to define new class (implementation class) from interface:
classimplement_class_name implements Interface_name
{
datatype var1;
here,
‘implements’ is keyword used to define or create new class from interface.
‘Interface_name’ is name of interface from which implement_class_name is created.
In above fig, class D is implementation class which is implemented from three interfaces [Link] A,
interface B and interface C. In this case, Class Dcan access individual copy of‘int p’from all interfaces
usingA.p, B.p and C.p. Because, by default all variables of interface are static therefore they are accessed
by class name. Thus, confusion regarding copy of ‘intp’ inClass D is solved.
Also, class DimplementsA, B, Csuch syntax is valid in Java.
Thus, In Java,multiple inheritanceis implemented using ‘interface’ concept.
Following program shows multiple inheritance using interface.
interface A class D implementsA,B,C
{ {
intp=10; public void calculate()
void calculate(); {
} int z;
interface B z=A.p+B.p+C.p;
{ [Link]("Addition="+z);
intp=20; }
void calculate(); }
} class multiple
interface C {
{ public static void main(String s[])
intp=30; {
void calculate(); D obj=new D();
} [Link]();
}
}
In above program:
class D is implementation class which is implemented from interfaces A,B and C.
The calculate( )method in implementation ‘class D’ must be defined with ‘public’ modifier because it overrides
its abstract methods of interfaces A,B,C. And by default all interface methods are public.
If do not define it with public modifier then compiler gives compilation error.
Wrapper Classes
Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.
The table below shows the primitive type and the equivalent wrapper class:
Primitive Data Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
Sometimes you must use wrapper classes, for example when working with Collection objects, such as ArrayList,
where primitive types cannot be used (the list can only store objects):
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
Creating Wrapper Objects
To create a wrapper object, use the wrapper class instead of the primitive type. To get the value, you can just
print the object:
class Main
{
public static void main(String[] args)
{
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
[Link](myInt);
[Link](myDouble);
[Link](myChar);
}
}
Since you're now working with objects, you can use certain methods to get information about the specific
object.
For example, the following methods are used to get the value associated with the corresponding wrapper
object: intValue(), byteValue(), shortValue(), longValue(), floatValue(), doubleValue(), charValue(),
booleanValue().
This example will output the same result as the example above:
class Main
{
public static void main(String[] args)
{
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}
Java Inheritance Programs
1) Single Inheritance
class A
{
int x=10;
}
class B extends A //Sigle Inheriance
{
int y=5;
void show()
{
int z=x+y;
[Link]("addition is="+z);
}
}
class demo
{
public static void main(String args[])
{
B m=new B();
[Link]();
}
}
2) Multilevel Inheritance
class A class demo
{ {
int x=10; public static void main(String args[])
} {
class B extends A C n=new C();
{ [Link]();
int y=5; }
} }
class C extends B
{
int z;
void show()
{
z=x+y;
[Link]("addition is="+z);
}
}
3) Hierarchical Inheritance
B C