Jp-I Notes
Jp-I Notes
A way of viewing the world is an idea to illustrate the object-oriented programming concept with an example
of a real-world situation.
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 delivery community), tell them the variety and
quantity of food and the hotel name from which I wish to deliver 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.
An object-oriented program is structured as a community of interacting agents, called objects. Where each
object provides a service (data and methods) that is used by other members of the community.
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 object-oriented programming, every action is initiated by passing a message to an agent (object), which is
responsible for the action. The receiver is the object to whom the message was sent. In response to the
message, the receiver performs some method to carry out the request. Every message may include any
additional information as arguments.
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 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.
In object-oriented programming, classes can be organized into a hierarchical inheritance structure. A child
class inherits properties from the parent class that higher in the tree.
Static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.
class Dog{
d1.eat();
Dynamic binding
class Animal{
a.eat();
}
In the class hierarchy, both parent and child classes may have the same method which implemented
individually. Here, the implementation of the parent is overridden by the child. Or a class may provide
multiple definitions to a single method to work with different arguments (overloading).
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 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 essential functionality. In the abstraction concept,
we do not show the actual implementation to the end user, instead we provide only essential 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.
JAVA BUZZ WORDS
Java is the most popular object-oriented programming language. Java has many advanced features, a list of
key features is known as Java Buzz Words. The java team has listed the following terms as java buzz words.
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.
Java has invented to archive "write once; run anywhere, any time, forever". The java provides JVM (Java
Virtual Machine) to to archive architectural-neutral or platform-independent. The JVM allows the java
program created using one operating system can be executed on any other operating system.
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).
AN 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”.
The following three steps are used to create and execute a java program.
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
byte i;
short j;
int k;
long l;
float m;
double n;
char ch;
boolean p;
Output
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
String str;
System.out.println(wish.concat(name));
}
}
Output
These are built-in data types These are created by the users
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)
(or)
(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.
Example
int a = 10;
int b = 20;
obj.show();
obj.display();
}
Output
The variables declared inside a class and outside any method, constructor or block are known as instance
variables or member variables. These variables are visible to all the methods of the class. The changes made
to these variables by method affects all the methods in the class. These variables are created separate copy
for every object of that class.
Example
int x = 100;
x = x + 100;
obj.show();
obj.display();
Output
Static variables or Class variables
A static variable is a variable that declared using static keyword. The instance variables can be static
variables but local variables can not. Static variables are initialized only once, at the start of the program
execution. The static variable only has one copy per class irrespective of how many objects we create.
Example
this.x = x;
this.y = y;
StaticVariablesExample.z = 1000;
obj_2.show();
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.
Example
void show() {
obj.show();
}
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.
Creating an array
In the java programming language, an array must be created using new operator and with a specific size. The
size must be an integer value but not a byte, short, or long. We use the following syntax to create an array.
Syntax
(or)
Example
list[0] = 10;
}
}
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
Example
list[0] = 10;
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
list[4] = 10;
Output
An entire array is accessed using either simple for statement or for-each statement. Look at the following
example program to display sum of all the lements in a list.
Example
import java.util.Scanner;
size = read.nextInt();
list[i] = read.nextShort();
sum = sum + i;
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
(or)
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
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
The above statement creates a two-dimensional array of three rows and two columns.
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.,
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
% Modulus - Remainder of the Division 5 % 2 = 1
++ Increment a++
-- Decrement a--
The addition operator can be used with numerical data types and character or string data type. When it is
used with numerical values, it performs mathematical addition and when it is used with character or string
data type values, it performs concatination (appending).
The modulus (remainder of the division) operator is used with integer data type only.
The increment and decrement operators are used as pre-increment or pre-decrement and post-increment or
post-decrement.
When they are used as pre, the value is get modified before it is used in the actual expresion and when it is
used as post, the value is get modified after the the actual expression evaluation.
Example
result = a + b;
result = a - b;
result = a * b;
result = b / a;
result = b % a;
result = b--;
}}
Output
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
boolean a;
a = 10<5;
System.out.println("10 < 5 is " + a);
a = 10>5;
a = 10<=5;
a = 10>=5;
a = 10==5;
a = 10!=5;
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.
The operators &, |, and ^ can be used with both boolean and integer data type values. When they are used
with integers, performs bitwise operations and with boolean, performs logical operations.
Logical operators and Short-circuit operators both are similar, but in case of short-circuit operators once
the decision is finalized it does not evaluate remaining expressions.
Example
boolean a = true;
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.
Example
boolean x = true;
a += b;
a -= b;
a *= b;
a /= b;
a %= b;
System.out.println("a = " + a);
x |= (a>b);
x &= (a>b);
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.
}}
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
Example
c = (a>b)? a : b;
Output
EXPRESSIONS
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 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.
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
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.
Control Statements
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.
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.
In java, the selection statements are also known as decision making statements or branching 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
if-elif statement
nested 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.
Example
import java.util.Scanner;
if((num % 5) == 0) {
Output
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.
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.
Example
import java.util.Scanner;
public class IfElseStatementTest {
if((num % 2) == 0) {
else {
}}
Output
Writing an if statement inside another if-statement is called nested if statement. The general syntax of the
nested if-statement is as follows.
Syntax
if(condition_1){
if(condition_2){
inner if-block of statements;
...
...
Example
import java.util.Scanner;
if (num % 2 == 0)
System.out.println("And it is EVEN");
else
System.out.println("And it is ODD");
} else
Output
if-else if statement in java
Writing an if-statement inside else of an if statement is called if-else-if statement. The general syntax of the
an if-else-if statement is as follows.
Syntax
if(condition_1){
condition_1 true-block;
...}
else if(condition_2){
condition_2 true-block;
...
Output
The switch statement has the following syntax and execution flow diagram.
Example
import java.util.Scanner;
switch( value )
Output
Iterative Statements
The java programming language provides a set of iterative statements that are used to execute a statement or
a block of statements repeatedly as long as the given condition is true. The iterative statements are also
known as looping statements or repetitive statements. Java provides the following iterative statements.
while statement
do-while statement
for statement
for-each statement
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.
Example
int num = 1;
System.out.println(num);
num++;
Output
do-while statement in java
The do-while statement is used to execute a single statement or block of statements repeatedly as long as
given the condition is TRUE. The do-while statement is also known as the Exit control looping statement.
The do-while statement has the following syntax.
Example
int num = 1;
do {
System.out.println(num);
num++;
The for statement is used to execute a single statement or a block of statements repeatedly as long as the
given condition is TRUE. The for statement has the following syntax and execution flow diagram.
In for-statement, the execution begins with the initialization statement. After the initialization statement, it
executes Condition. If the condition is evaluated to true, then the block of statements executed otherwise it
terminates the for-statement. After the block of statements execution, the modification statement gets
executed, followed by condition again.
Example
Output
The Java for-each statement was introduced since Java 5.0 version. It provides an approach to traverse
through an array or collection in Java. The for-each statement also known as enhanced for statement. The
for-each statement executes the block of statements for each element of the given array or collection.
In for-each statement, we can not skip any element of given array or collection.
The for-each statement has the following syntax and execution flow diagram.
Java Program
for(int i : arrayList) {
}
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 break statement in java is used to terminate a switch or looping statement. That means the break
statement is used to come out of a switch statement and a looping statement like while, do-while, for, and
for-each.
Using the break statement outside the switch or loop statement is not allowed.
The following picture depicts the execution flow of the break statement.
Java Program
for(int i : list) {
if(i == 30)
break;
System.out.println(i);
The continue statement is used to move the execution control to the beginning of the looping statement.
When the continue statement is encountered in a looping statement, the execution control skips the rest of the
statements in the looping block and directly jumps to the beginning of the loop. The continue statement can
be used with looping statements like while, do-while, for, and for-each.
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.
Java Program
for(int i : list) {
if(i == 30)
continue;
System.out.println(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 java.util.Scanner;
verify: if (value % 2 == 0) {
System.out.println("\nYou won!!!");
break reading;
} else {
continue reading;
In java, the return statement used to terminate a method with or without a value. The return statement takes
the execution control to the calling function. That means the return statement transfer the execution control
from called function to the calling function by carrying a value.
Java allows the use of return-statement with both, with and without return type methods.
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 java.util.Scanner;
int value;
int readValue() {
return this.value=read.nextInt();
if(i == 5)
return;
System.out.println(i);
obj.showValue(obj.readValue());
}
CLASSES
Java is an object-oriented programming language, so everything in java program must be based on the object
concept. In a java programming language, the class concept defines the skeleton of an object.
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>{
methods defination;
}
The ClassName must begin with an alphabet, and the Upper-case letter is preferred.
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
The objectName must begin with an alphabet, and a Lower-case letter is preferred.
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.
Every method in java must be declared inside a class. very method declaration has the following characteristics.
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>{
...
block of statements;
...
}
🔔 The methodName must begin with an alphabet, and the Lower-case letter is preferred.
🔔 If a method defined with return type other than void, it must contain the return statement, otherwise, it
may be ignored.
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 java.util.Scanner;
int sNo;
String name;
void readData() {
sNo = read.nextInt();
name = read.next();
}
The objectName must begin with an alphabet, and a Lower-case letter is preferred.
Syntax
<returnType> <methodName>(dataType...parameterName);
Example
void diaplay(int...list) {
for(int i : list) {
System.out.print(i + "\t");
}
obj.diaplay(1, 2);
When a method has both the normal parameter and variable-argument, then the variable argument must be
specified at the end in the parameters list.
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() {
System.out.println("Object created!"); }
}
A constructor cannot have return value.
String Handling
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[5] = '-';
System.out.println(name);
The String class defined in the package java.lang 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
siteName = "www.btechsmartclass.com";
In java, we can use the following two ways to create a string object.
The String class constructor accepts both string and character array as an argument.
In java programming language, the String class contails various methods that can be used to handle string
data values. It containg methods like concat( ), compareTo( ), split( ), join( ), replace( ), trim( ), length( ),
intern( ), equals( ), comparison( ), substring( ), etc.
The following table depicts all built-in methods of String class in java.
Return
Method Description
Value
charAt(int) Finds the character at given index char
length() Finds the length of given string int
compareTo(String) Compares two strings int
compareToIgnoreCase(String) Compares two strings, ignoring case int
concat(String) Concatenates the object string with argument string. String
contains(String) Checks whether a string contains sub-string boolean
contentEquals(String) Checks whether two strings are same boolean
equals(String) Checks whether two strings are same boolean
equalsIgnoreCase(String) Checks whether two strings are same, ignoring case boolean
Checks whether a string starts with the specified
startsWith(String) boolean
string
Checks whether a string ends with the specified
endsWith(String) boolean
string
getBytes() Converts string value to bytes byte[]
hashCode() Finds the hash code of a string int
Finds the first index of argument string in object
indexOf(String) int
string
Finds the last index of argument string in object
lastIndexOf(String) int
string
isEmpty() Checks whether a string is empty or not boolean
replace(String, String) Replaces the first string with second string String
Replaces the first string with second string at all
replaceAll(String, String) String
occurrences.
Extracts a sub-string from specified start and end
substring(int, int) String
index values
toLowerCase() Converts a string to lower case letters String
toUpperCase() Converts a string to upper case letters String
trim() Removes whitespace from both ends String
toString(int) Converts the value to a String object String
Return
Method Description
Value
split(String) splits the string matching argument string String[]
intern() returns string from the pool String
join(String, String, ...) Joins all strings, first string as delimiter. String
Java Program
}
INHERITANCE
INHERITANCE CONCEPT
The inheritance is a very useful and powerful concept of object-oriented programming. In java, using the
inheritance concept, we can use the existing features of one class in another class. The inheritance provides a
greate advantage called code re-usability. With the help of code re-usability, the commonly used code in an
application need not be written again and again.
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.
In java, we use the keyword extends to create a child class. The following syntax used to create a child class
in java.
Syntax
...
...
In a java programming language, a class extends only one class. Extending multiple classes is not allowed in
java.
In this type of inheritance, one child class derives from one parent class. Look at the following example code.
Example
class ParentClass{
int a;
void setData(int a) {
this.a = a;
void showData() {
obj.setData(100);
obj.showData();
In this type of inheritance, the child class derives from a class which already derived from another class.
Look at the following example java code.
Example
class ParentClass{
int a;
void setData(int a) {
this.a = a;
void showData() {
void display() {
System.out.println("Inside ChildChildClass!");
}
public class MultipleInheritance {
obj.setData(100);
obj.showData();
obj.display();
In this type of inheritance, two or more child classes derive from one parent class. Look at the following
example java code.
Example
class ParentClass{
int a;
void setData(int a) {
this.a = a;
void showData() {
System.out.println("Inside ChildClass!");
}
}
void display() {
System.out.println("Inside ChildClassToo!");
child_obj.setData(100);
child_obj.showData();
childToo_obj.setData(200);
childToo_obj.display();
The hybrid inheritance is the combination of more than one type of inheritance. We may use any
combination as a single with multiple inheritances, multi-level with multiple inheritances, etc.,
MEMBER ACCESS
Access Modifiers
In Java, the access specifiers (also known as access modifiers) used to restrict the scope or accessibility of a
class, constructor, variable, method or data member of class and interface. There are four access specifiers,
and their list is below.
In java, we cannot employ all access specifies on everything. The following table describes where we can
apply the access specifies.
Example
...
In java, the accessibility of the members of a class or interface depends on its access specifies. The following
table provides information about the visibility of both data members and methods.
The private members can be accessed only inside the same class.
The protected members are accessible to every child class (same package or other packages).
The default members are accessible within the same package but not outside the package.
Example
class ParentClass{
int a = 10;
void showData()
{ System.out.println("Inside ParentClass");
void accessData() {
System.out.println("Inside ChildClass");
obj.showData();
obj.accessData();
}
Constructors
In the inheritance, the constructors never get inherited to any child class.
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(){
ChildClass(){
ChildChildClass(){
}
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.
Example
class ParentClass{
int a;
ParentClass(int a){
this.a = a;
ParentClass(){
ChildClass(){
}
public class ConstructorInInheritance {
The parameterized constructor of parent class must be called explicitly using the super keyword.
SUPER USES
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.
When both parent class and child class have data members with the same name, then the super keyword is
used to refer to the parent class data member from child class.
Example
class ParentClass{
void showData() {
System.out.println("Inside the ChildClass");
obj.showData();
When both parent class and child class have method with the same name, then the super keyword is used to
refer to the parent class method from child class.
Example
class ParentClass{
void showData() {
System.out.println("\nInside the ParentClass showData method");
void showData() {
super.showData();
obj.showData();
}
super to call parent class constructor
When an object of child class is created, it automatically calls the parent class default-constructor before it's
own. But, the parameterized constructor of parent class must be called explicitly using the super keyword
inside the child class constructor.
Example
class ParentClass{
int num1;
ParentClass(){
num1 = 10;
System.out.println("\nnum1= "+num1);
ParentClass(int value){
num1 = value;
System.out.println("\nnum1= "+num1);
int num2;
ChildClass(){
super(100);
num2 = 200;
System.out.println("\nnum2= "+num1);
}
}
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.
In java, the final is a keyword and it is used with the following things.
When a variable defined with the final keyword, it becomes a constant, and it does not allow us to modify the
value. The variable defined with the final keyword allows only a one-time assignment, once a value assigned
to it, never allows us to change it again.
Example
}
final with methods
When a method defined with the final keyword, it does not allow it to override. The final method extends to
the child class, but the child class can not override or re-define it. It must be used as it has implemented in
the parent class.
Example
class ParentClass{
void showData() {
}}
When a class defined with final keyword, it can not be extended by any other class.
Example
void showData() {
}
PYLYMORPHISM
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 java.util.Arrays;
Arrays.parallelSort(list);
Arrays.parallelSort(names);
PURE POLYMORPHISM
The pure polymorphism is a technique used to define the same method with the same arguments but different
implementations. In a java programming language, pure polymorphism carried out with a method overriding
concept.
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() {
}
}
void showData() {
obj.showData();
obj.showData();
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() {
void showData() {
obj.showData();
obj.showData();
}
}
ABSTRACT CLASS
An abstract class is a class that created using abstract keyword. In other words, a class prefixed with abstract
keyword is known as an abstract class.
In java, an abstract class may contain abstract methods (methods without implementation) and also non-
abstract methods (methods with implementation).
Syntax
...
Example
import java.util.*;
abstract class Shape {
void printArea() {
length = input.nextInt();
breadth = input.nextInt();
void printArea() {
length = input.nextInt();
breadth = input.nextInt();
}
}
void printArea() {
radius = input.nextInt();
rec.printArea();
tri.printArea();
cri.printArea();
}
An abstract class can not be instantiated but can be referenced. That means we can not create an object of an
abstract class, but base reference can be created.
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
Shape obj = new Rectangle(); //Base class reference to Child class instance
obj.printArea();
obj.printArea();
obj.printArea();
OBJECT CLASS
In java, the Object class is the super most class of any class hierarchy. The Object class in the java
programming language is present inside the java.lang package.
Every class in the java programming language is a subclass of Object class by default.
The Object class is useful when you want to refer to any object whose type you don't know. Because it is the
super class of all other classes in java, it can refer to any type of object.
The following table depicts all built-in methods of Object class in java.
Return
Method Description
Value
getClass() Returns Class class object object
hashCode() returns the hashcode number for object being used. int
equals(Object
compares the argument object to calling object. boolean
obj)
clone() Compares two strings, ignoring case int
concat(String) Creates copy of invoking object object
toString() eturns the string representation of invoking object. String
notify() wakes up a thread, waiting on invoking object's monitor. void
notifyAll() wakes up all the threads, waiting on invoking object's monitor. void
wait() causes the current thread to wait, until another thread notifies. void
causes the current thread to wait for the specified milliseconds and
wait(long,int) void
nanoseconds, until another thread notifies.
It is invoked by the garbage collector before an object is being
finalize() void
garbage collected.
FORMS OF INHERITANCE
The inheritance concept used for the number of purposes in the java programming language. One of the main
purposes is substitutability. The substitutability means that when a child class acquires properties from its
parent class, the object of the parent class may be substituted with the child class object. For example, if B is
a child class of A, anywhere we expect an instance of A we can use an instance of B.
The substitutability can achieve using inheritance, whether using extends or implements keywords.
Specialization
Specification
Construction
Eextension
Limitation
Combination
Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent class. It holds the
principle of substitutability.
Specification
This is another commonly used form of inheritance. In this form of inheritance, the parent class just specifies
which methods should be available to the child class but doesn't implement them. The java provides concepts
like abstract and interfaces to support this form of inheritance. It holds the principle of substitutability.
Construction
This is another form of inheritance where the child class may change the behavior defined by the parent class
(overriding). It does not hold the principle of substitutability.
Extension
This is another form of inheritance where the child class may add its new properties. It holds the principle of
substitutability.
Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It does not hold the
principle of substitutability.
Combination
This is another form of inheritance where the subclass inherits properties from multiple parent classes. Java
does not support multiple inheritance type.
Benefits of Inheritance
Inheritance helps in code reuse. The child class may use the code defined in the parent class
without re-writing it.
Inheritance can save time and effort as the main code need not be written again.
Inheritance provides a clear model structure which is easy to understand.
An inheritance leads to less development and maintenance costs.
With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived class. An
inheritance leads to less development and maintenance costs.
In inheritance base class can decide to keep some data private so that it cannot be altered by the
derived class.
Costs of Inheritance
Inheritance decreases the execution speed due to the increased time and effort it takes, the
program to jump through all the levels of overloaded classes.
Inheritance makes the two classes (base and inherited class) get tightly coupled. This means one
cannot be used independently of each other.
The changes made in the parent class will affect the behavior of child class too.
The overuse of inheritance makes the program more complex.