Understanding Object-Oriented Programming
Understanding Object-Oriented Programming
Let us consider a situation, I am at my office and I wish to get food to my family members who are
at my home from a hotel. Because of the distance from my office to home, there is no possibility of
getting food from a hotel myself. So, how do we solve the issue?
To solve the problem, let me call zomato (an agent in food delevery community), tell them the
variety and quantity of food and the hotel name from which I wish to delever the food to my family
members. Look at the following image.
So, in object-oriented programming, problem-solving is the solution to our problem which requires
the help of many individuals in the community. We may describe agents and communities as
follows.
In our example, the online food delivery system is a community in which the agents are zomato and
set of hotels. Each hotel provides a variety of services that can be used by other members like
zomato, myself, and my family in the community.
Messages and Methods
To solve my problem, I started with a request to the agent zomato, which led to still more requestes
among the members of the community until my request has done. Here, the members of a
community interact with one another by making requests until the problem has satisfied.
In our example, I send a request to zomato with a message that contains food items, the quantity of
food, and the hotel details. The receiver uses a method to food get delivered to my home.
Responsibilities
In object-oriented programming, behaviors of an object described in terms of responsibilities.
In our example, my request for action indicates only the desired outcome (food delivered to my
family). The agent (zomato) free to use any technique that solves my problem. By discussing a
problem in terms of responsibilities increases the level of abstraction. This enables more
independence between the objects in solving complex problems.
In our example, the zomato a class and all the hotels are sub-classes of it. For every request
(message), the class creates an instance of it and uses a suitable method to solve the problem.
Classes Hierarchies
A graphical representation is often used to illustrate the relationships among the classes (objects) of a
community. This graphical representation shows classes listed in a hierarchical tree-like structure. In
this more abstract class listed near the top of the tree, and more specific classes in the middle of the
tree, and the individuals listed near the bottom.
The search for the method to invoke in response to a request (message) begins with the class of this
receiver. If no suitable method is found, the search is performed in the parent class of it. The search
continues up the parent class chain until either a suitable method is found or the parent class chain is
exhausted. If a suitable method is found, the method is executed. Otherwise, an error message is
issued.
OOP Concepts in Java
OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which every
program is follows the concept of object. In other words, OOP is a way of writing programs based on
the object concept.
Encapsulation
Inheritance
Polymorphism
Abstraction
The popular object-oriented programming languages are Smalltalk, C++, Java, PHP, C#, Python, etc.
Encapsulation
Encapsulation is the process of combining data and code into a single unit (object / class). In OOP,
every object is associated with its data and code. In programming, data is defined as variables and
code is defined as methods. The java programming language uses the class concept to implement
encapsulation.
Inheritance
Inheritance is the process of acquiring properties and behaviors from one object to another object or
one class to another class. In inheritance, we derive a new class from the existing class. Here, the
new class acquires the properties and behaviors from the existing class. In the inheritance concept,
the class which provides properties is called as parent class and the class which recieves the
properties is called as child class. The parent class is also known as base class or supre class. The
child class is also known as derived class or sub class.
In the inheritance, the properties and behaviors of base class extended to its derived class, but the
base class never receive properties or behaviors from its derived class.
Polymorphism
Polymorphism is the process of defining same method with different implementation. That means
creating multiple methods with different behaviors.
The java uses method overloading and method overriding to implement polymorphism.
Method overloading - multiple methods with same name but different parameters.
Method overriding - multiple methods with same name and same parameters.
Abstraction
Abstraction is hiding the internal details and showing only esential functionality. In the abstraction
concept, we do not show the actual implemention to the end user, instead we provide only esential
things. For example, if we want to drive a car, we does not need to know about the internal
functionality like how wheel system works? how brake system works? how music system works?
etc.
Simple
Secure
Portable
Object-oriented
Robust
Architecture-neutral (or) Platform Independent
Multi-threaded
Interpreted
High performance
Distributed
Dynamic
Simple
Java programming language is very simple and easy to learn, understand, and code. Most of the
syntaxes in java follow basic programming language C and object-oriented programming concepts
are similar to C++. In a java programming language, many complicated features like pointers,
operator overloading, structures, unions, etc. have been removed. One of the most useful features is
the garbage collector it makes java more simple.
Secure
Java is said to be more secure programming language because it does not have pointers concept, java
provides a feature "applet" which can be embedded into a web application. The applet in java does
not allow access to other parts of the computer, which keeps away from harmful programs like
viruses and unauthorized access.
Portable
Portability is one of the core features of java which enables the java programs to run on any
computer or operating system. For example, an applet developed using java runs on a wide variety of
CPUs, operating systems, and browsers connected to the Internet.
Object-oriented
Java is said to be a pure object-oriented programming language. In java, everything is an object. It
supports all the features of the object-oriented programming paradigm. The primitive data types java
also implemented as objects using wrapper classes, but still, it allows primitive data types to archive
high-performance.
Robust
Java is more robust because the java code can be executed on a variety of environments, java has a
strong memory management mechanism (garbage collector), java is a strictly typed language, it has a
strong set of exception handling mechanism, and many more.
Multi-threaded
Java supports multi-threading programming, which allows us to write programs that do multiple
operations simultaneously.
Interpreted
Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode. The byte code is interpreted to any machine code so that it runs
on the native machine.
High performance
Java provides high performance with the help of features like JVM, interpretation, and its simplicity.
Distributed
Java programming language supports TCP/IP protocols which enable the java to support the
distributed environment of the Internet. Java also supports Remote Method Invocation (RMI), this
feature enables a program to invoke methods across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on a running
system and it has a dynamic memory allocation and deallocation (objects and garbage collector).
Overview of Java
Java is a computer programming language. Java was created based on C and C++. Java uses C
syntax and many of the object-oriented features are taken from C++. Before Java was invented there
were other languages like COBOL, FORTRAN, C, C++, Small Talk, etc. These languages had few
disadvantages which were corrected in Java. Java also innovated many new features to solve the
fundamental problems which the previous languages could not solve. Java was invented by a team of
13 employees of Sun Microsystems, Inc. which is lead by James Gosling, in 1991. The team includes
persons like Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan, etc., Java was developed
as a part of the Green project. Initially, it was called Oak, later it was changed to Java in 1995.
History of Java
The C language developed in 1972 by Dennis Ritchie had taken a decade to become the most
popular language.
In 1979, Bjarne Stroustrup developed C++, an enhancement to the C language with included
OOP fundamentals and features.
A project named “Green” was initiated in December of 1990, whose aim was to create a
programming tool that could render obsolete the C and C++ programming languages.
Finally in the year of 1991 the Green Team was created a new Programming language named
“OAK”.
After some time they found that there is already a programming language with the name
“OAK”.
So, the green team had a meeting to choose a new name. After so many discussions they want
to have a coffee. They went to a Coffee Shop which is just outside of the Gosling’s office and
there they have decided name as “JAVA”.
In java, primitive data types includes byte, short, int, long, float, double, char, and boolean.
The following table provides more description of each primitive data type.
Example
public class PrimitiveDataTypes {
byte i;
short j;
int k;
long l;
float m;
double n;
char ch;
boolean p;
}
}
When we run the above example code, it produces the following output.
Non-primitive Data Types
In java, non-primitive data types are the reference data types or user-created data types. All non-
primitive data types are implemented using object concepts. Every variable of the non-primitive data
type is an object. The non-primitive data types may use additional methods to perform certain
operations. The default value of non-primitive data type variable is null.
In java, examples of non-primitive data types are String, Array, List, Queue, Stack, Class, Interface,
etc.
Example
public class NonPrimitiveDataTypes {
String str;
When we run the above example code, it produces the following output.
Primitive Vs Non-primitive Data Types
Primitive Data Type Non-primitive Data Type
These are built-in data types These are created by the users
Does not support additional methods Support additional methods
Always has a value It can be null
Starts with lower-case letter Starts with upper-case letter
Size depends on the data type Same size for all
Java Variables
A variable is a named memory location used to store a data value. A variable can be defined as a
container that holds a data value.
Syntax
data_type variable_name;
(or)
data_type variable_name_1, variable_name_2,...;
(or)
data_type variable_name = value;
(or)
data_type variable_name_1 = value, variable_name_2 = value,...;
Local variables
Instance variables or Member variables or Global variables
Static variables or Class variables
Final variables
Local variables
The variables declared inside a method or a block are known as local variables. A local variable is
visible within the method in which it is declared. The local variable is created when execution
control enters into the method or block and destroyed after the method or block execution completed.
Let's look at the following example java program to illustrate local variable in java.
Example
public class LocalVariables {
When we run the above example code, it produces the following output.
Let's look at the following example java program to illustrate instance variable in java.
Example
public class ClassVariables {
int x = 100;
When we run the above example code, it produces the following output.
Let's look at the following example java program to illustrate static variable in java.
Example
public class StaticVariablesExample {
When we run the above example code, it produces the following output.
Final variables
A final variable is a variable that declared using final keyword. The final variable is initialized only
once, and does not allow any method to change it's value again. The variable created using final
keyword acts as constant. All variables like local, instance, and static variables can be final variables.
Let's look at the following example java program to illustrate final variable in java.
Example
public class FinalVariableExample {
When we run the above example code, it produces the following output.
Java Arrays
An array is a collection of similar data values with a single name. An array can also be defined as, a
special type of variable that holds multiple values of the same data type at a time.
In java, arrays are objects and they are created dynamically using new operator. Every array in java
is organized using index values. The index value of an array starts with '0' and ends with 'zise-1'. We
use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
Syntax
data_type array_name[ ] = new data_type[size];
(or)
data_type[ ] array_name = new data_type[size];
Example
public class ArrayExample {
list[0] = 10;
[Link]("Value at index 0 - " + list[0]);
[Link]("Length of the array - " + [Link]);
When we run the above example code, it produces the following output.
In java, an array can also be initialized at the time of its declaration. When an array is initialized at
the time of its declaration, it need not specify the size of the array and use of the new operator. Here,
the size is automatically decided based on the number of values that are initialized.
Example
int list[ ] = {10, 20, 30, 40, 50};
Example
public class ArrayExample {
list[0] = 10;
[Link]("Value at index 0 - " + list[0]);
When we run the above example code, it produces the following output.
ArrayIndexOutOfBoundsException with Arrays
In java, the JVM (Java Virtual Machine) throws ArrayIndexOutOfBoundsException when an array is
trying to access with an index value of negative value, value equal to array size, or value more than
the array size.
Example
public class ArrayExample {
list[4] = 10;
[Link]("Value at index 0 - " + list[0]);
When we run the above example code, it produces the following output.
Example
import [Link];
public class ArrayExample {
public static void main(String[] args) {
When we run the above example code, it produces the following output.
Multidimensional Array
In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-
dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a multidimensional array variable,
specify each additional index using another set of square brackets. We use the following syntax to
create two-dimensional array.
Syntax
data_type array_name[ ][ ] = new data_type[rows][columns];
(or)
data_type[ ][ ] array_name = new data_type[rows][columns];
When we create a two-dimensional array, it created with a separate index for rows and columns. The
individual element is accessed using the respective row index followed by the column index. A
multidimensional array can be initialized while it has created using the following syntax.
Syntax
data_type array_name[ ][ ] = {{value1, value2}, {value3, value4}, {value5,
value6},...};
When an array is initialized at the time of declaration, it need not specify the size of the array and use
of the new operator. Here, the size is automatically decided based on the number of values that are
initialized.
Example
int matrix_a[ ][ ] = {{1, 2},{3, 4},{5, 6}};
The above statement creates a two-dimensional array of three rows and two columns.
Java Operators
An operator is a symbol used to perform arithmetic and logical operations. Java provides a rich set of
operators.
Arithmetic Operqators
Relational (or) Comparision Operators
Logical Operators
Assignment Operators
Bitwise Operators
Conditional Operators
Arithmetic Operators
In java, arithmetic operators are used to performing basic mathematical operations like addition,
subtraction, multiplication, division, modulus, increment, decrement, etc.,
Example
public class ArithmeticOperators {
result = a + b;
[Link]("Addition : " + a + " + " + b + " = " +
result);
result = a - b;
[Link]("Subtraction : " + a + " - " + b + " = " +
result);
result = a * b;
[Link]("Multiplucation : " + a + " * " + b + " = " +
result);
result = b / a;
[Link]("Division : " + b + " / " + a + " = " +
result);
result = b % a;
[Link]("Modulus : " + b + " % " + a + " = " +
result);
result = ++a;
[Link]("Pre-increment : ++a = " + result);
result = b--;
[Link]("Post-decrement : b-- = " + result);
}
}
When we run the above example code, it produces the following output.
Relational Operators (<, >, <=, >=, ==, !=)
The relational operators are the symbols that are used to compare two values. That means the
relational operators are used to check the relationship between two values. Every relational operator
has two posible results either TRUE or FALSE. In simple words, the relational operators are used to
define conditions in a program. The following table provides information about relational operators.
Example
public class RelationalOperators {
boolean a;
a = 10<5;
[Link]("10 < 5 is " + a);
a = 10>5;
[Link]("10 > 5 is " + a);
a = 10<=5;
[Link]("10 <= 5 is " + a);
a = 10>=5;
[Link]("10 >= 5 is " + a);
a = 10==5;
[Link]("10 == 5 is " + a);
a = 10!=5;
[Link]("10 != 5 is " + a);
}
When we run the above example code, it produces the following output.
Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.
Example
public class LogicalOperators {
When we run the above example code, it produces the following output.
Assignment Operators
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side
variable (Lvalue). The assignment operator is used in different variants along with arithmetic
operators. The following table describes all the assignment operators in the java programming
language.
Operator Meaning Example
= Assign the right-hand side value to left-hand side variable A = 15
Add both left and right-hand side values and store the result into left-hand side
+= A += 10
variable
Subtract right-hand side value from left-hand side variable value and store the
-= A -= B
result into left-hand side variable
Multiply right-hand side value with left-hand side variable value and store the
*= A *= B
result into left-hand side variable
Divide left-hand side variable value with right-hand side variable value and
/= A /= B
store the result into the left-hand side variable
Divide left-hand side variable value with right-hand side variable value and
%= A %= B
store the remainder into the left-hand side variable
&= Logical AND assignment -
|= Logical OR assignment -
^= Logical XOR assignment -
Example
public class AssignmentOperators {
a += b;
[Link]("a = " + a);
a -= b;
[Link]("a = " + a);
a *= b;
[Link]("a = " + a);
a /= b;
[Link]("a = " + a);
a %= b;
[Link]("a = " + a);
x |= (a>b);
[Link]("x = " + x);
x &= (a>b);
[Link]("x = " + x);
}
}
When we run the above example code, it produces the following output.
Bitwise Operators
The bitwise operators are used to perform bit-level operations in the java programming language.
When we use the bitwise operators, the operations are performed based on binary values. The
following table describes all the bitwise operators in the java programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
Example
public class BitwiseOperators {
When we run the above example code, it produces the following output.
Conditional Operators
The conditional operator is also called a ternary operator because it requires three operands. This
operator is used for decision making. In this operator, first, we verify a condition, then we perform
one operation out of the two operations based on the condition result. If the condition is TRUE the
first option is performed, if the condition is FALSE the second option is performed. The conditional
operator is used with the following syntax.
Syntax
Condition ? TRUE Part : FALSE Part;
Look at the following example program.
Example
public class ConditionalOperator {
c = (a>b)? a : b;
When we run the above example code, it produces the following output.
Java Expressions
Java In any programming language, if we want to perform any calculation or to frame any condition
etc., we use a set of symbols to perform the task. These set of symbols makes an expression.
In the java programming language, an expression is defined as follows.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations,
logical operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a direct value
or variable or address of memory location.
Expression Types
In the java programming language, expressions are divided into THREE types. They are as follows.
Infix Expression
Postfix Expression
Prefix Expression
Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Example
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
Example
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Example
Java Control Statements
In java, the default execution flow of a program is a sequential order. But the sequential order of
execution flow may not be suitable for all situations. Sometimes, we may want to jump from line to
another line, we may want to skip a part of the program, or sometimes we may want to execute a part
of the program again and again. To solve this problem, java provides control statements.
In java, the control statements are the statements which will tell us that in which order the
instructions are getting executed. The control statements are used to control the order of execution
according to our requirements. Java provides several control statements, and they are classified as
follows.
if statement
if-else statement
if-elif statement
nested if statement
switch statement
Java Selection Statements
In java, the selection statements are also known as decision making statements or branching
statements or conditional control statements. The selection statements are used to select a part of the
program to be executed based on a condition. Java provides the following selection statements.
if statement
if-else statement
nested if statement
if-else if statement
switch statement
if statement in java
In java, we use the if statement to test a condition and decide the execution of a block of statements
based on that condition result. The if statement checks, the given condition then decides the
execution of a block of statements. If the condition is True, then the block of statements is executed
and if it is False, then the block of statements is ignored. The syntax and execution flow of if the
statement is as follows.
Java Program
import [Link];
if((num % 5) == 0) {
[Link]("We are inside the if-block!");
[Link]("Given number is divisible by 5!!");
}
[Link]("We are outside the if-block!!!");
In the above execution, the number 12 is not divisible by 5. So, the condition becomes False and the
condition is evaluated to False. Then the if statement ignores the execution of its block of statements.
When we enter a number which is divisible by 5, then it produces the output as follows.
if-else statement in java
In java, we use the if-else statement to test a condition and pick the execution of a block of
statements out of two blocks based on that condition result. The if-else statement checks the given
condition then decides which block of statements to be executed based on the condition result. If the
condition is True, then the true block of statements is executed and if it is False, then the false block
of statements is executed. The syntax and execution flow of if-else statement is as follows.
Java Program
import [Link];
if((num % 2) == 0) {
[Link]("We are inside the true-block!");
[Link]("Given number is EVEN number!!");
}
else {
[Link]("We are inside the false-block!");
[Link]("Given number is ODD number!!");
}
}
When we run this code, it produce the following output.
Syntax
if(condition_1){
if(condition_2){
inner if-block of statements;
...
}
...
}
Java Program
import [Link];
Syntax
if(condition_1){
condition_1 true-block;
...
}
else if(condition_2){
condition_2 true-block;
condition_1 false-block too;
...
}
Java Program
import [Link];
else
[Link]("\nThe largest number is " + num3) ;
The switch statement has the following syntax and execution flow diagram.
Let's look at the following example java code.
Java Program
import [Link];
switch( value )
{
case 0: [Link]("ZERO") ; break ;
case 1: [Link]("ONE") ; break ;
case 2: [Link]("TWO") ; break ;
case 3: [Link]("THREE") ; break ;
case 4: [Link]("FOUR") ; break ;
case 5: [Link]("FIVE") ; break ;
case 6: [Link]("SIX") ; break ;
case 7: [Link]("SEVEN") ; break ;
case 8: [Link]("EIGHT") ; break ;
case 9: [Link]("NINE") ; break ;
default: [Link]("Not a Digit") ;
}
while statement
do-while statement
for statement
for-each statement
while statement
do-while statement
for statement
for-each statement
while statement in java
The while statement is used to execute a single statement or block of statements repeatedly as long as
the given condition is TRUE. The while statement is also known as Entry control looping statement.
The syntax and execution flow of while statement is as follows.
Java Program
int num = 1;
Java Program
do {
[Link](num);
num++;
}while(num <= 10);
Java Program
}
When we run this code, it produce the following output.
The for-each statement has the following syntax and execution flow diagram.
Let's look at the following example java code.
Java Program
for(int i : arrayList) {
[Link]("i = " + i);
}
Jump Statements
In java, the jump statements are used to terminate a block or take the execution control to the next
iteration. Java provides the following jump statements.
break
continue
return
Java Jump Statements
The java programming language supports jump statements that used to transfer execution control
from one line to another line. The java programming language provides the following jump
statements.
break statement
continue statement
labelled break and continue statements
return statement
The floowing picture depictes the execution flow of the break statement.
Java Program
for(int i : list) {
if(i == 30)
break;
[Link](i);
}
}
When we run this code, it produce the following output.
When we use continue statement with while and do-while statements, the execution control directly
jumps to the condition. When we use continue statement with for statement the execution control
directly jumps to the modification portion (increment/decrement/any modification) of the for loop.
The continue statement flow of execution is as shown in the following figure.
Let's look at the following example java code.
Java Program
for(int i : list) {
if(i == 30)
continue;
[Link](i);
}
The labelled break statement terminates the block with specified label. The labbeled contonue
statement takes the execution control to the beginning of a loop with specified label.
Java Program
import [Link];
verify: if (value % 2 == 0) {
[Link]("\nYou won!!!");
[Link]("Your score is " + i*10 + " out
of 30.");
break reading;
} else {
[Link]("\nSorry try again!!!");
[Link]("You let with " + (3-i) + "
more options...");
continue reading;
}
}
}
}
In java, the return statement used with both methods with and without return type. In the case of a
method with the return type, the return statement is mandatory, and it is optional for a method
without return type.
When a return statement used with a return type, it carries a value of return type. But, when it is used
without a return type, it does not carry any value. Instead, simply transfers the execution control.
Java Program
import [Link];
public class JavaReturnStatementExample {
int value;
int readValue() {
Scanner read = new Scanner([Link]);
[Link]("Enter any number: ");
return [Link]=[Link]();
}
[Link]([Link]());
}
}
The java class is a template of an object. The class defines the blueprint of an object. Every class in
java forms a new data type. Once a class got created, we can generate as many objects as we want.
Every class defines the properties and behaviors of an object. All the objects of a class have the same
properties and behaviors that were defined in the class.
Look at the following picture to understand the class and object concept.
Creating a Class
In java, we use the keyword class to create a class. A class in java contains properties as variables
and behaviors as methods. Following is the syntax of class in the java.
Syntax
class <ClassName>{
data members declaration;
methods defination;
}
Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the class is said to be
instantiated. All the objects that are created using a single class have the same properties and
methods. But the value of properties is different for every object. Following is the syntax of class in
the java.
Syntax
Java Methods
A method is a block of statements under a name that gets executes only when it is called. Every
method is used to perform a specific task. The major advantage of methods is code re-usability
(define the code once, and use it many times).
In a java programming language, a method defined as a behavior of an object. That means, every
method in java must belong to a class.
Creating a method
A method is created inside the class and it may be created with any access specifier. However,
specifying access specifier is optional.
Syntax
class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}
}
Calling a method
In java, a method call precedes with the object name of the class to which it belongs and a dot
operator. It may call directly if the method defined with the static modifier. Every method call must
be made, as to the method name with parentheses (), and it must terminate with a semicolon.
Syntax
<objectName>.<methodName>( actualArguments );
Example
import [Link];
public class JavaMethodsExample {
int sNo;
String name;
Scanner read = new Scanner([Link]);
void readData() {
[Link]("Enter Serial Number: ");
sNo = [Link]();
[Link]("Enter the Name: ");
name = [Link]();
}
}Output:
Variable arguments of a method
In java, a method can be defined with a variable number of arguments. That means creating a method
that receives any number of arguments of the same data type.
Syntax
<returnType> <methodName>(dataType...parameterName);
Example
void diaplay(int...list) {
for(int i : list) {
[Link](i + "\t");
}
[Link](1, 2);
[Link](10, 20, 30, 40, 50);
}Output:
Constructor
A constructor is a special method of a class that has the same name as the class name. The
constructor gets executes automatically on object creation. It does not require the explicit method
call. A constructor may have parameters and access specifiers too. In java, if you do not provide any
constructor the compiler automatically creates a default constructor.
Example
ConstructorExample() {
[Link]("Object created!");
}
public static void main(String[] args) {
Output:
Java String Handling
A string is a sequence of characters surrounded by double quotations. In a java programming
language, a string is the object of a built-in class String.
In the background, the string values are organized as an array of a character data type.
The string created using a character array can not be extended. It does not allow to append more
characters after its definition, but it can be modified.
Example
char[] name = {'J', 'a', 'v', 'a', ' ', 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l',
's'};
//name[14] = '@'; //ArrayIndexOutOfBoundsException
name[5] = '-';
[Link](name);
The String class defined in the package [Link] package. The String class implements Serializable,
Comparable, and CharSequence interfaces.
The string created using the String class can be extended. It allows us to add more characters after its
definition, and also it can be modified.
Example
Example
The following table depicts all built-in methods of String class in java.
equalsIgnoreCase(String) Checks whether two strings are same, ignoring case boolean
startsWith(String) Checks whether a string starts with the specified string boolean
endsWith(String) Checks whether a string ends with the specified string boolean
indexOf(String) Finds the first index of argument string in object string int
lastIndexOf(String) Finds the last index of argument string in object string int
replace(String, String) Replaces the first string with second string String
replaceAll(String, String) Replaces the first string with second string at all occurrences. String
substring(int, int) Extracts a sub-string from specified start and end index values String
join(String, String, ...) Joins all strings, first string as delimiter. String
Java Program
The inheritance is the process of acquiring the properties of one class to another class.
Inheritance Basics
In inheritance, we use the terms like parent class, child class, base class, derived class, superclass,
and subclass.
The Parent class is the class which provides features to another class. The parent class is also known
as Base class or Superclass.
The Child class is the class which receives features from another class. The child class is also known
as the Derived Class or Subclass.
In the inheritance, the child class acquires the features from its parent class. But the parent class
never acquires the features from its child class.
Syntax
In a java programming language, a class extends only one class. Extending multiple classes is not
allowed in java.
Let's look at individual inheritance types and how they get implemented in java with an example.
Example
class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
[Link]("Value of a is " + a);
}
}
public class SingleInheritance {
Example
class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
[Link]("Value of a is " + a);
}
}
class ChildChildClass extends ChildClass{
void display() {
[Link]("Inside ChildChildClass!");
}
}
public class MultipleInheritance {
}
}
Example
class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
[Link]("Inside ChildClass!");
[Link]("Value of a is " + a);
}
}
class ChildClassToo extends ParentClass{
void display() {
[Link]("Inside ChildClassToo!");
[Link]("Value of a is " + a);
}
}
public class HierarchicalInheritance {
In java, we can not employ all access specifiers on everything. The following table describes where
we can apply the access specifiers.
Let's look at the following example java code, which generates an error because a class does not
allow private access specifier unless it is an inner class.
Example
Example
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData() {
[Link]("Inside ParentClass");
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
[Link]("d = " + d);
}
}
void accessData() {
[Link]("Inside ChildClass");
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
//[Link]("d = " + d); // private member can't be
accessed
}
}
public class AccessModifiersExample {
}
}
In java, the default constructor of a parent class called automatically by the constructor of its child
class. That means when we create an object of the child class, the parent class constructor executed,
followed by the child class constructor executed.
Example
class ParentClass{
int a;
ParentClass(){
[Link]("Inside ParentClass constructor!");
}
}
class ChildClass extends ParentClass{
ChildClass(){
[Link]("Inside ChildClass constructor!!");
}
}
class ChildChildClass extends ChildClass{
ChildChildClass(){
[Link]("Inside ChildChildClass constructor!!");
}
}
public class ConstructorInInheritance {
However, if the parent class contains both default and parameterized constructor, then only the
default constructor called automatically by the child class constructor.
ChildClass(){
[Link]("Inside ChildClass constructor!!");
}
}
public class ConstructorInInheritance {
The parameterized constructor of parent class must be called explicitly using the super keyword.
Java super keyword
In java, super is a keyword used to refers to the parent class object. The super keyword came into
existence to solve the naming conflicts in the inheritance. When both parent class and child class
have members with the same name, then the super keyword is used to refer to the parent class
version.
Example
class ParentClass{
void showData() {
[Link]("Inside the ChildClass");
[Link]("ChildClass num = " + num);
[Link]("ParentClass num = " + [Link]);
}
}
[Link]();
}
When we run this code, it produce the following output.
Example
class ParentClass{
void showData() {
[Link]("\nInside the ParentClass showData method");
[Link]("ChildClass num = " + num1);
}
}
void showData() {
[Link]("\nInside the ChildClass showData method");
[Link]("ChildClass num = " + num2);
[Link]();
}
}
[Link]();
//[Link](); // super can't be used here
}
}
Example
class ParentClass{
int num1;
ParentClass(){
[Link]("\nInside the ParentClass default
constructor");
num1 = 10;
}
ParentClass(int value){
[Link]("\nInside the ParentClass parameterized
constructor");
num1 = value;
}
}
int num2;
ChildClass(){
super(100);
[Link]("\nInside the ChildClass constructor");
num2 = 200;
}
}
}
}When we run this code, it produce the following output.
To call the parameterized constructor of the parent class, the super keyword must be the first
statement inside the child class constructor, and we must pass the parameter values.
Java final keyword
In java, the final is a keyword and it is used with the following things.
Example
Example
class ParentClass{
void showData() {
[Link]("Inside ChildClass showData() method");
[Link]("num = " + num);
}
}
}
}When we run this code, it produce the following output.
final with class
When a class defined with final keyword, it can not be extended by any other class.
Example
void showData() {
[Link]("Inside ParentClass showData() method");
[Link]("num = " + num);
}
}
}when we run this code, it produce the following output.
Java Polymorphism
The polymorphism is the process of defining same method with different implementation. That
means creating multiple methods with different behaviors.
Ad hoc polymorphism
The ad hoc polymorphism is a technique used to define the same method with different
implementations and different arguments. In a java programming language, ad hoc polymorphism
carried out with a method overloading concept.
In ad hoc polymorphism the method binding happens at the time of compilation. Ad hoc
polymorphism is also known as compile-time polymorphism. Every function call binded with the
respective overloaded method based on the arguments.
Example
import [Link];
In pure polymorphism, the method binding happens at run time. Pure polymorphism is also known as
run-time polymorphism. Every function call binding with the respective overridden method based on
the object reference.
When a child class has a definition for a member function of the parent class, the parent class
function is said to be overridden.
Example
class ParentClass{
void showData() {
[Link]("Inside ChildClass showData() method");
[Link]("num = " + num);
}
}
}
}When we run this code, it produce the following output.
Java Method Overriding
The method overriding is the process of re-defining a method in a child class that is already defined
in the parent class. When both parent and child classes have the same method, then that method is
said to be the overriding method.
The method overriding enables the child class to change the implementation of the method which
aquired from parent class according to its requirement.
In the case of the method overriding, the method binding happens at run time. The method binding
which happens at run time is known as late binding. So, the method overriding follows late binding.
The method overriding is also known as dynamic method dispatch or run time polymorphism or pure
polymorphism.
Example
class ParentClass{
void showData() {
[Link]("Inside ParentClass showData() method");
[Link]("num = " + num);
}
void showData() {
[Link]("Inside ChildClass showData() method");
[Link]("num = " + num);
}
}
}
}
In java, an abstract class may contain abstract methods (methods without implementation) and also
non-abstract methods (methods with implementation).
Syntax
Example
import [Link].*;
In the above example program, the child class objects are created to invoke the overridden abstract
method. But we may also create base class reference and assign it with child class instance to invoke
the same. The main method of the above program can be written as follows that produce the same
output.
Example