Java Unit I
Java Unit I
UNIT I
Thinking Object-Oriented:
The object oriented Programming Language is based upon the concept of “objects”,
which contains data as attributes in methods.
Object:
Objects are the basic run time entities in an object oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the program has to
handle.
For Example – Consider a Television, It is an object. And the properties related to it are.
It’s With and Height, color, type (Smart TV or CRT TV), etc. And the behavior can be –
we can change the channel, Adjust volumes and settings, switch off, switch on, etc are
lots of behavior are there. The operation on the behavior will affect the
properties. Changing the channel will affect its property.
So, similar things happen in Object-Oriented programming also, that each object has some
properties and behavior associated with it, that are defined in the class.
1. Objects – Object is the entity that makes the classes to be implemented into the
program. It makes the features, properties, and behaviors of the class to be
implemented. Example – A car is an object that has property color, model, brand
name, fuel type, etc, and behaviors like, it runs. So these properties and behavior
make an object (CAR).
2. Classes – A class can be stated as the blueprint of the object. This states what an
object can do. It contains all the features, attributes, and behavior of what the model
can do. We can say that class contains the definition of the object. Example – Car
color, engine type, etc. And with the definition, we can create any number of objects.
3. Methods – Methods are the attributes of the class which are defined for the specified
behavior of the object. It can also modify the state of the class. Example – Method to
drive a car, It changes the state of the car from parking state to running state.
4. Instances – It is the members of the class who holds some values related to the
objects of the class.
Object-Oriented Paradigm:
The main necessity behind inventing object oriented approach is to remove the
drawback encountered in the procedural approach.
Object-oriented programming paradigm methods enable us to create a set of objects
that work together to produce software that is better understandable and models their
problem domains than produced using traditional techniques.
Programs are divided into objects.
Focus is on properties and functions rather than procedure.
Objects may communicate with each other through a function called messaging.
Follow the bottom-up approach in oop design
The major aspects of Object Oriented Programming (OOP) paradigm are as follows:
1. Reduced Maintenance :
The primary goal of object-oriented development is the assurance that the system will enjoy a
longer life while having far smaller maintenance costs. Because most of the processes within
the system are encapsulated, the behaviors may be reused and incorporated into new
behaviors.
2. Real-World Modeling :
Object-oriented system tend to model the real world in a more complete fashion than do
traditional methods. Objects are organized into classes of objects, and objects are associated
with behaviors. The model is based on objects, rather than on data and processing.
Advantages of OOPs
1. Re-usability
It means reusing some facilities rather than building them again and again. This is done with
the use of a class.
2. Data Redundancy
This is a condition created at the place of data storage where the same piece of data is held in
two separate places. So the data redundancy is one of the greatest advantages of OOP.
3. Code Maintenance
This feature is more of a necessity for any programming languages; it helps users from doing
re-work in many ways. It is always easy and time-saving to maintain and modify the existing
codes by incorporating new changes into them.
4. Security
With the use of data hiding and abstraction mechanism, we are filtering out limited data to
exposure, which means we are maintaining security and providing necessary data to view.
5. Easy troubleshooting
lets witness some common issues or problems any developers face in their work.
6. Polymorphism Flexibility
Let’s see a scenario to better explain this behavior.
7. Problems solving
The broken components can be reused in solutions to different other problems
A WAY OF VIEWING THE WORLD:
Suppose I wish to send owers to a friend who lives in a city many miles away. Let me
call my friend Sally. Because of the distance, there is no possibility of my picking the owers
and carrying them to her door myself. Nevertheless, sending her the owers is an easy enough
task; I merely go down to my local orist (who happens to be named Flora), tell her the variety
and quantity of owers I wish to send and give her Sally's address, and I can be assured the
owers will be delivered expediently and automatically.
let me emphasize that the mechanism I used to solve my problem was to find an
appropriate agent (namely, Flora) and to pass to her a message containing my request.
So, our first observation of object oriented problem solving is that the solution to my problem
required the help of many other individuals. . Without their help, my problem could not be
easily solved. We phrase this in a general fashion as the following:
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.
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.
To solve my problem, I started with a request to the agent, which led to still more
requests 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.
Responsibilities:
A traditional program often operates by acting on data structures, for example changing fields
in an array or record. In contrast, an object oriented program requests data structures to
perform a service.
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.
This technique shows classes listed in a hierarchical tree-like structure, with more
abstract classes (such as Material Object or Animal) listed near the top of the tree, and more
specific classes, and finally individuals, are listed near the bottom.
Classes can be organized into a hierarchical inheritance structure. A child class (or
subclass) will inherit attributes from a parent class higher in the tree. An abstract parent class
is a class (such as Mammal) for which there are no direct instances; it is used only to create
subclasses.
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.
Everything is an object.
An object is a runtime entity in an object oriented programming
Computation is performed by objects communicating with each other.
Objects communicate by sending and receiving messages.
A message is a request for action bundled with whatever arguments may be necessary
to complete the task.
Each object has its own memory, which consists of other objects.
Every object is an instance of a class.
A class simply represents a grouping of similar objects, such as integers or lists.
The class is the repository for behavior associated with an object.
That is, all objects that are instances of the same class can perform the same actions.
Classes are organized into a singly rooted tree structure, called the inheritance
hierarchy.
Memory and behavior associated with instances of a class are automatically available
to any class associated with a descendant in this tree structure.
1. Objects
2. Classes
3. Data abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
7. Overloading
8. Dynamic binding
9. Message passing
OBJECTS:
Objects are the basic run-time entities in an object-oriented system. They may
represent a person, a place, a bank account, a table of data or any item that the program must
handle.
The fundamental idea behind object oriented approach is to combine both data and
function into a single unit and these units are called objects.
The term objects means a combination of data and program that represent some real
word entity.
For example: consider an example named kumar. kumar is 25 years old and his salary is
25000. The Kumar may be represented in a computer program as an object. The data part of
the object would be (name: Kumar, age: 25, salary: 25000)
The program part of the object may be collection of programs (retrive of data, change
age, change of salary). In general even any user –defined type-such as employee may be
used. In the Amit object the name, age and salary are called attributes of the object.
CLASS:
A class can be considered as a blue print of object. A group of objects that share
common properties for data part and some program part are collectively called as class.
Class is a collection of objects of similar type. Objects are variables of the type of
class. Once a class has been defined, we can create any number of objects belonging to that
class.
DATA ABSTRACTION :
Abstraction is the process of hiding the internal details of an application from the
outer world. Classes use the concept of abstraction and are defined as size, width and cost and
functions to operate on the attributes.
Types of Abstraction
1. Data Abstraction
2. Process Abstraction
DATA ENCAPSULATION :
The wrapping up of data and function into a single unit (called class) is known as
encapsulation.
Data encapsulation combines data and functions into a single unit called class. Data
encapsulation will prevent direct access to data. The data can be accessed only through
methods (function) present inside the class. The data cannot be modified by an external
nonmember function of a class. Data encapsulation enables data hiding or information hiding.
INHERITENCE:
Inheritance is a process of creating a new class from the base class. Inheritance is the
process by which objects of one class acquire the properties of another class. In the concept
of inheritance provides the idea of reusability.
POLYMORPHISIM:
The word “polymorphism” means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than one form. A
real-life example of polymorphism is a person who at the same time can have different
characteristics.
A man at the same time is a father, a husband, and an employee. So the same person
exhibits different behavior in different situations. This is called polymorphism.
Polymorphism is considered one of the important features of Object-Oriented
Programming.
Types of Polymorphism
Compile-time Polymorphism
Runtime Polymorphism
OVERLOADING:
Overloading allows objects to have different meaning depending uponcontext. There
are 2 types of overloading namely
1. Operator overloading
2. Function overloading
When an existing operator operates on new data type, it is called operator
overloading. Function overloading means two or more functions have same name ,but differ
in the number of arguments or data type of arguments. Therefore it is said that (function
name) is overloaded. Function overloading therefore is the process of defining same function
name to carry out similar types of activities with various data items.
DYNAMIC BINDING:
Binding is the process of connecting one program to another. Dynamic binding means
code associated with a procedure call is known only at the time of program execution routine.
MESSAGE PASSING:
An object oriented program consists of a set of objects that communicate with each
other.
A message for an object is a request for execution of a procedure and therefore will
invoke a function (procedure) in the receiving object that generates the desired result.
Message passing involves specifying the name of the object, the name of the function
(message) and information to be sent.
OVERVIEW OF JAVA:
Java is a programming language created by James Gosling from Sun Microsystems in 1991.
Java allows to write a program and run it on multiple operating systems.
1. Java Compiler: The JDK includes the Java compiler (javac), which converts Java source
code (.java files) into byte code (.class files) that can be executed by the Java Virtual
Machine (JVM).
VM (Java Virtual Machine): The JVM is a virtual machine that executes Java bytecode. It
provides an environment for running Java programs and translates the bytecode into machine
code that can be understood by the underlying hardware.
The Java Development Kit (JDK) is a software development environment used for
developing Java applications. It includes a set of tools, libraries, and compilers that are
necessary for writing, compiling, and running Java programs.
The JRE is a subset of the JDK and includes the JVM, libraries, and other files necessary for
running Java applications. It does not contain the development tools (such as the compiler)
included in the JDK.
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
1. Simple:
2. Object-Oriented:
3. Platform independent:
It is more secured language compare to other language; in this language all code is
converted into byte code after compilation which is not readable by human.
5.Robust:
6. Architecture neutral:
7. Portable:
It supports Dynamic memory allocation, due to this memory wastage is reduced and
performance of application is improved. The process of allocating the memory space to the
input of the program at a run-time is known as dynamic memory allocation. To allocate
memory space dynamically we use an operator called 'new'. 'new' operator is known as
dynamic memory allocation operator.
9. Interpreted:
11. Multithreaded:
A flow of control is known as thread. When any Language executes multiple threads
at a time that language is known as multithreaded Language. It is multithreaded Language.
12. Distributed:
Using this language we can create distributed application. RMI and EJB are used for
creating distributed applications. In distributed application multiple client system are depends
on multiple server systems so that even problem occurred in one server will never be
reflected on any client system.
APPLICATIONS USING JAVA:
There are mainly 4 type of applications that can be created using java
a. Standalone Application:
b. Web Application:
An application that runs on the server side and creates dynamic page, is called web
application. Currently, Servlet, JSP, struts, JSF etc. technologies are used for creating web
applications in java.
c. Enterprise Application:
d. Mobile Application:
An application that is created for mobile devices. Currently Android and Java ME are
used for creating mobile applications.
Java programming language has a rich set of data types. The data type is a category of
data stored in variables. In java, data types are classified into two types and they are as
follows.
• Primitive Data Types
• Non-primitive Data Types
The primitive data types include Boolean, char, byte, short, int, long, float and double.
1. Integers: This group includes byte, short, int, and long, which are for whole-valued signed
numbers.
2. Floating-point numbers: This group includes float and double, which represent numbers
with fractional precision.
3. Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.
4. Boolean: This group includes Boolean, which is a special type for representing true/false
values.
Int Data Type:
The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value
is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.
Example:
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.
Example:
float f1 = 234.5f
The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example:
The Boolean data type is used to store only two possible values: true and false. This
data type is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
The byte data type is an example of primitive data type. It is an 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value
is -128 and maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings
is most required. It saves space because a byte is 4 times smaller than an integer. It can also
be used in place of "int" data type.
Example:
The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is
32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.
Example:
The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value
is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.
Example:
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1) (inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.
Example:
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range
is unlimited. It is recommended to use a float (instead of double) if you need to save memory
in large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.
Example:
float f1 = 234.5f
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited. The double data type is generally used for decimal values just like float.
The double data type also should never be used for precise values, such as currency. Its
default value is 0.0d.
Example:
double d1 = 12.3
The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example:
System.out.println("Hello world!");
Example
Obj.display();
}}
A package is a collection of classes, interfaces and sub-packages. A sub package contains
collection of classes, interfaces and sub-sub packages etc. java.lang.*; package is imported by
default and this package is known as default package.
Class is keyword used for developing user defined data type and every java program must
start with a concept of class.
"ClassName" represent a java valid variable name treated as a name of the class each and
every class name in java is treated as user-defined data type.
Data member represents either instance or static they will be selected based on the name of
the class.
User-defined methods represents either instance or static they are meant for performing the
operations either once or each and every time.
Block of statements represents set of executable statements which are in term calling user-
defined methods are containing business-logic.
The file naming conversion in the java programming is that which-ever class is containing
main() method, that class name must be given as a file name with an extension .java.
A java Program is made up of Classes and Methods and in the Methods are the
Container of the various Statements And a Statement is made up of Variables, Constants,
operators etc .
Tokens are the various Java program elements which are identified by the compiler
and separated by delimiters. The delimiters are not part of the tokens. A token is the smallest
element of a program that is meaningful to the compiler. The compiler breaks lines into
chunks of text called tokens.
Keywords
Identifiers or names
Literals
Separators
Operators
KEYWORDS:
These are special words defined in Java and represent a set of instructions.
The keywords represent groups of instructions for the compiler.
• These are special tokens that have a predefined meaning and their use is restricted.
• keywords cannot be used as names of variables, methods, classes, or packages.
• These are written in the lower case.
• Keywords of Java Language are as follows:
IDENTIFIERS OR NAMES:
Identifier is the name of variables, methods, classes etc. Rules for framing Names or
Identifiers.
It should be a single word which contains alphabets a to z or A to Z, digits 0 to 9,
underscore (_).
It should not contain white spaces and special symbols.
It should not be a keyword of Java.
It should not be Boolean literal, that is, true or false.
It should not be null literal.
It should not start with a digit but it can start with an underscore.
It can comprise one or more unicode characters which are characters as well as digits.
Conventions for Writing Names:
Names of packages are completely in lower-case letters such as mypackage, java.lang.
• Names of classes and interfaces start with an upper-case letter.
• Names of methods start with a lower-case character.
• Names of variables should start with a lower-case character.
LITERALS:
These are values represented by a set of character, digits, etc.
• A literal represents a value which may be of primitive type, String type, or null type.
• The value may be a number (either whole or decimal point number) or a sequence of
characters which is called String literal, Boolean type, etc.
• A literal is a constant value.
SEPARATORS:
These include comma, semicolon, period(.), Parenthesis (), Square brackets [], etc
It is an identifier that denotes a storage location used to store a data value. A variable
provides us with named storage that our programs can manipulate.
Declaration of Variables:
In Java, variables are the names of storage locations. After designing suitable variable names,
we must declare them to the compiler.
Variables are separated by commas. A declaration statement must end with a semicolon.
Some valid declarations are:
Example:
Local variables
Instance variables
Class/static variables
Example:
class A
{
int data=50; //instance variable
static int m=100; //static variable
void method( )
{
int n=90; //local variable
}
} // end of class
Local Variable:
A variable declared inside the body of the method is called local variable.
There is no default value for local variables so local variables should be declared and an
initial value should be assigned before the first use.
Example:
Here, age is a local variable. This is defined inside pupAge() method and its scope is
limited to this method only.
int age = 0;
age = age + 7;
test.pupAge();
Output:
Instance Variable:
A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.
Instance variables are created when an object is created with the use of the keyword 'new' and
dest royed when the object is destroyed.
Instance variables have default values. For numbers the default value is 0
Instance variables can be accessed directly by calling the variable name inside the class.
Class/Static variable:
Class variables also known as static variables are declared with the static keyword in a class,
but outside a method, constructor or a block.
Static variables are created when the program starts and destroyed when the program stops.
Static variables can be accessed by calling with the class name . ClassName.VariableName.
JAVA ARRAYS
An array is a collection of similar data types with a contiguous memory location. It is
used to store multiple values in a single variable instead of declaring separate variables for
each value. It is also known as static data structure because size of an array must be specified
at the time of its declaration.
Arrays are indexed, meaning each array element has a specific position (also called
index) that is used to access it. Array starts from zero index and goes to n-
1 where n is length of the array.
1. One-Dimensional Arrays.
2. Multi-Dimensional Arrays.
One-Dimensional Arrays:
Single dimensional array use single index to store elements.
Syntax:
dataType[] arr;
dataType []arr;
dataType arr[];
Example:
int[] intArray; // Declare an integer array
class Testarray1
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}}
Output : 33
Multi-Dimensional Arrays
In Java, a multidimensional array is an array of arrays. It is a data structure that allows
you to store multiple arrays in a single array. The most common types of multidimensional
arrays are two-dimensional (2D) and three-dimensional (3D) arrays, but Java also supports
arrays with more than three dimensions. These types of arrays are also known
as jagged arrays.
Syntax
<data-type>[][] <variable-name>
<data-type> <variable-name>[][]
class array2d
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
for(int j=0;j<3;J++)
System.out.print(arr[i][j]+" ");
System.out.println();
}}}
Output:1 2 3
245
445
Jagged Array:
Jagged array is an array that has different numbers of columns elements. In java, a
jagged array means to have a multi-dimensional array with uneven size of columns in it.
At the time of array creation compulsory we should specify the size otherwise we will
get compile time error.
It is legal to have an array with size zero in java.
The allowed data types to specify array size are byte, short, char, int. By mistake if we
are using any other type we will get compile time error.
The maximum allowed array size in java is maximum value of int size [2147483647].
class twodarrayaddition
{
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
System.out.println();//new line
}}}
Output : 2 6 8
6 8 10
TYPE CONVERSION
Type conversion is a process in which the data type is automatically converted into
another data type.
The compiler does this automatic conversion at compile time. This type of type
conversion is also called Widening Type Conversion/ Implicit Conversion/ Casting Down.
For type conversion to take place, the destination data type must be larger than the source
type. In short, the below flow chart has to be followed.
In this case, as the lower data types with smaller sizes are converted into higher ones with a
larger size, there is no chance of data loss. This makes it safe for usage.
TYPE CASTING
Type casting is a process in which the programmer manually converts one data type
into another data type. For this the casting operator (), the parenthesis is used. Type casting is
also called Narrowing Type Casting/ Explicit Conversion/ Casting Up.
This case, as the higher data types with a larger size are converted into lower ones
with a smaller size, there is a chance of data loss.
Java Expressions
An expression is a series of variables, operators, and method calls that evaluates to a single
value.
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.
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.
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
OPERATORS
Java supports a rich set of operators. An operator is a symbol that tells the computer
to perform certain mathematical or logical manipulations. Operators are used in programs to
manipulate data and variables. They usually form a part of mathematical or logical
expressions.
Arithmetic Operators
Relational operators
Logical operators
Assignment operators
Increment and decrement operators
Conditional operators
Bitwise operators
Special operators
Arithmetic Operators:
We often compare two quantities, and depending on their relation, take certain
decisions. For example, we may compare the age of two persons, or the price of two items,
and so on. These comparisons can be done with the help of relational operators.
a < b or x < 20
Logical Operators
The logical operators && and | | are used when we want to form compound conditions by
combining two or more relations. An example is:
a > b && x == 10
An expression of this kind which combines two or more relational expressions is termed as a
logical expression or a compound relational expression.
Assignment Operators:
Assignment operators are used to assign the value of an expression to a variable. We
have seen the usual assignment operator, ‘=’. In addition, Java has a set of ‘shorthand’
assignment operators which are used in the form
Java has two very useful operators not generally found in many other languages. These are
the increment and decrement operators.
++ and ––
Conditional Operator
The character pair ? : is a ternary operatory available in Java. This operator is used to
construct conditional expressions of the form
The operator ? : works as follows: exp1 is evaluated first. If it is nonzero (true), then the
expression exp2 is evaluated and becomes the value of the conditional expression. If exp1 is
false, exp3 is evaluated and its value becomes the value of the conditional expression. None
that only one of the expressions (either exp2 or exp3) is evaluated. For example, consider the
following statements:
In this example, x will be assigned the value of b. This can be achieved using the if….else
statement as follows:
if(a > b)
x = a;
else
x = b;
Bitwise Operators:
Java has a distinction of supporting special operators known as bitwise operators for
manipulation of data at values of bit level.
These operators are used for testing the bits, or shifting them to the right or left. Bitwise
operators may not be applied to float or double.
Java supports some special operators of interest such as instanceof operatory and member
selection operator (.).
The instanceof is an object operator and returns true of the object on the left-hand side is an
instance of the class given on the right-hand side. This operator allows us to determine
whether the object belongs to a particular class or not.
CONTROL STATEMENTS
The Java selection statements allow your program to choose a different path of
execution based on a certain condition. Java selection statements provide different type of
statements such as:
1. if statement.
2. if-else statement.
4. nested if statement.
if Statement:
Syntax:
if(condition)
Statement(s);
Flowchart:
Example
int num=70;
}}
Output:
if-else Statement:
Syntax:
if(condition)
{
//code for if statement
else{
int num=120;
else
}}}
Output:
if-else-if Statement:
Syntax
if(condition1)
{
//statement1;
}
else if(condition2)
{
//statement2;
}
else if(condition3)
{
//statement3;
}
.........
.........
.........
Else
{
//default statement;
}
Example:
public class IfElseIfExample
{
public static void main(String args[])
{
int num=1234;
if(num <100&&num>=1)
{
System.out.println("Its a two digit number");
}
else if(num <1000&&num>=100)
{
System.out.println("Its a three digit number");
}
else if(num <10000&&num>=1000)
{
System.out.println("Its a four digit number");
}
else if(num <100000&&num>=10000)
{
System.out.println("Its a five digit number");
}
Else
{
System.out.println("number is not between 1 & 99999");
}
}
}
Output:
Nested if statement:
When there is an if statement inside another if statement then it is called the nested if
statement.
Syntax:
if(condition1){
if(condition2){
Example
Switch case statement is used when we have number of options (or choices) and we may need
to perform a different task for each choice.
A switch statement can work with byte, short, char, and int primitive data types. It also works
with enumerated types and the String class.
The value of the expression is compared with each of the literal values in the case statements.
If a match is found, the code sequence following that case statement is executed. If none of
the constants matches the value of the expression, then the default statement is executed.
The default statement is optional.
The break statement is used inside the switch to terminate a statement sequence.
Syntax
switch(expression)
{
case value1:
//statement sequence
break;
case value2:
//statement sequence
break;
.......
.......
.......
case valueN:
//statement sequence
break;
default:
//default statement sequence
}
Example
class WeekDays
{
public static void main(String s[])
int day = 2;
switch(day)
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid");
break;
}}}
Iteration statement (Looping Statement):
Java Iteration statements allow program execution to repeat one or more statements. java
Iteration statements provide different type of statements such as:
1. For loop.
2. While loop.
3. Do While loop.
1. For loop.
Loops are used to execute a set of statements repeatedly until a particular condition is satisfied.
The for loop in java is used to iterate a part of the program several times.
The Java for loop consumes initialization, condition, and increment/decrement in one line.
Syntax
condition: In this step, we can check the condition. If the condition is true, then the body of
the loop is executed otherwise not.
class ForLoop
{
public static void main(String args[]){
System.out.println("The values from 1 to 10 is: ");
While Loop:
The while loop in java is the most fundamental looping statement. Java while
loop repeats a statement or a block while a particular condition is true. You can use a while
loop if the number of iteration is not fixed.
Syntax
while(boolean condition)
{
//body of the loop.
}
class WhileLoopExample
{
public static void main(String args[])
{
int i=10;
while(i>1)
{
System.out.println(i);
i--;
}}}
Output:
10
9
8
7
6
5
4
3
2
Do While loop:
do-while loop is similar to while loop. In while loop, condition is evaluated before the
execution of loop’s body but in do-while loop condition is evaluated after the execution of
loop’s body.
Do
{
statement(s);
}
while(condition);
class DoWhileLoopExample
{
public static void main(String args[])
{
int i=10;
do
{
System.out.println(i);
i--;
}
while(i>1);
}}
Output:
10
9
8
7
6
5
4
3
2
Jump Statements:
Java Jump statements transfer the control to other parts of the program. java Jump
statements provide different type of statements such as:
1. break statement.
2. continue statement
break statement
Java break statement can be used to terminate the loop. It can be used inside a loop. We can
use a break statement in all types of loops such as: while loop, do-while loop, and for loop.
When a break statement is encountered inside a loop, the loop is terminated and the program
control goes to the next statement following the loop.
break;
case 3:
System.out.println("Case 3 ");
break;
default:
System.out.println("Default ");
}}}
continue statement:
Continue statement is mostly used inside loops. Whenever it is encountered inside a loop,
control directly jumps to the beginning of the loop for next iteration, skipping the execution
of statements inside loop’s body for the current iteration.
Introducing Classes:
Class fundamentals
How to create classes by using the following basics:
The parts of a class definition
Declaring and using instance variables
Defining and using methods
Creating Java applications, including the main() method and how to pass arguments to
a Java program from a command line
1. By reference variable
2. By method
3. By constructor
class Student
int id;
String name;
class TestStudent2
s1.id=101;
s1.name="Sonoo";
}}
Method in Java
A method is a block of statements. A method is like a function which is used to expose the
behavior of an object. Every method is used to perform a specific task. a method defined as a
behavior of an object.
Every method in java must be declared inside a class.
Every method declaration has the following characteristics.
Advantage of Method
Code Reusability
Code Optimization
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;
...
//where we deposit and withdraw amount from our account. //Creating an Account class
which has deposit() and withdraw() methods
class Account
int acc_no;
String name;
float amount;
acc_no=a;
name=n;
amount=amt;
//deposit method
amount=amount+amt;
System.out.println(amt+" deposited");
//withdraw method
if(amount<amt){
System.out.println("Insufcient Balance");
}else{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}}
class TestAccount{
a1.insert(832345,"Ankit",1000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
a1.withdraw(15000);
a1.checkBalance();
}}
Output:
40000.0 deposited
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. The string values are organized as an array
of a character data type.
The String class defined in the package java.lang package. The String class
implements Serializable, Comparable, and CharSequence interfaces.
String literal:
In java, Strings can be created like this: Assigning a String literal to a String instance:
INHERITANCE:
Inheritance can be defined as the process where an object of a class acquires
characteristics from the object of another class.
The process by which one class acquires the properties(data members) and
functionalities (methods) of another class is called inheritance.
The class, which is inherited by the other classes, is known as superclass or base class
or parent class and the class, which inherits the properties of the base class, is called sub class
or derived class or child class. The sub-class can further be inherited to form other derived
classes.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
Reusability: As the name specifes, reusability is a mechanism which facilitates you to reuse
the felds and methods of the existing class when you create a new class. You can use the
same felds and methods already defned in the previous class.
}
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
TYPES OF INHERITANCE
This type of inheritance occurs for only a single class. Only one class is derived
from the parent class. In this type of inheritance, the properties are derived from a single
parent class. As the properties are derived from only a single base class the reusability of a
code is facilitated along with the addition of new features.
Example:
class Employee
{
void salary()
{
System.out.println("Salary= 200000");
}}
class Programmer extends Employee // Programmer class inherits from Employee
class
{
void bonus()
{
System.out.println("Bonus=50000");
}}
class single_inheritance
{
public static void main(String args[])
{
Output:
Salary= 200000
Bonus=50000
Multiple Inheritance
Multiple inheritances is a type of inheritance where a subclass can inherit features
from more than one parent class.
In multiple inheritances the newly derived class can have more than one superclass.
Java does not support multiple inheritance. This means that we can not use multiple
inheritance in java but a class can inherit properties from many classes in java using
interfaces.
Class C is derived from the two classes Class A and Class B. In other words it can be
described that subclass C inherits properties from both Class A and B.
Multi-level Inheritance
In Multilevel Inheritance, one class can inherit from a derived class. Hence, the
derived class becomes the base class for the new class.
In the multilevel inheritance in java, the inherited features are also from the
multiple base classes as the newly derived class from the parent class becomes the base
class for another newly derived class.
package com.techvidvan.inheritance;
//Base class
class Person
{
public void show()
{
System.out.println("Student inheriting properties from Person");
}
}
class Student extends Person
{
public void show1()
{
System.out.println("I am a Student who belongs to Person class");
}
}
//child class
class EngineeringStudent extends Student
{
// defining additional properties to the child class
public void show2()
{
System.out.println("Engineering Student inheriting properties from Student");
}
}
public class MultilevelDemo
{
public static void main(String args[])
{
EngineeringStudent obj = new EngineeringStudent();
obj.show();
obj.show1();
obj.show2();
}
}
Hierarchical Inheritance
Hierarchical inheritance is a type of inheritance in Java where multiple derived classes
inherit the properties of a parent class. It allows all the child classes to inherit methods and
fields from their parent class.
Syntax
Class P {
// fields and methods
}
class C1 extends P {
// fields and methods
}
class C2 extends P {
// fields and methods
}
class C3 extends P {
// fields and methods
}
Hybrid Inheritance
Hybrid inheritance is a combination of more than two types of inheritances single
and multiple. It can be achieved through interfaces only as multiple inheritance is not
supported by Java. It is basically the combination of simple, multiple, hierarchical
inheritances.
class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
}
class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){
Output: D
ADVANTAGES OF INHERITANCE:
Code reusability - public methods of base class can be reused in derived classes
Data hiding – private data of base class cannot be altered by derived class
Overriding- With inheritance, we will be able to override the methods of the base
class in the derived class
USING SUPER
super keyword is similar to this keyword in Java.
It is used to refer to the immediate parent class of the object.
Super keyword used in 3 levels:
It can be used to refer immediate parent class instance variable when both parent and
child class have member with same name
It can be used to invoke immediate parent class method when child class has
overridden that method.
super() can be used to invoke immediate parent class constructor.
super() if present, must always be the first statement executed inside a subclass
constructor.
When we invoke a super() statement from within a subclass constructor, we are
invoking the immediate super class constructor
Example:
class Vehicle
{
Vehicle( )
{
System.out.println("Vehicle is created");
}}
class Bike extends Vehicle
{
Bike()
{
super( ); //will invoke parent class constructor
System.out.println("Bike is created");
}}
class SuperClassConst
{
public static void main(String args[])
{
Bike b=new Bike();
}}
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;
public int b = 20;
protected int c = 30;
private int d = 40;
void showData()
{
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class ChildClass extends ParentClass{
void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample {
public static void main(String[] args) {
}}
Class
Methods
Variables
CONSTRUCTORS IN JAVA
Constructors are used to initialize the state of an object when it is created.
Constructors are invoked while creating objects, usually after the new keyword. Every
time an Object is created using the new() keyword, at least one constructor is called.
It is called when an instance of the class is created. At the time of calling constructor,
memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
public class MyClass
{
//This is the constructor
MyClass()
{
} .. }
Default Constructor:
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>()
{}
Example:
//Java Program to create and call a default constructor
class Bike1
{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}}
Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
The parameterized constructor is used to provide diferent values to distinct objects.
Example
class Student4
{
int id;
String name;
Student4(int i,String n) //creating a parameterized constructor
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]) //creating objects and passing values
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display(); //calling method to display the values of object
s2.display();
}}
CONSTRUCTOR OVERLOADING
Constructor overloading in Java is a technique of having more than one constructor
with different parameter lists. They are arranged in a way that each constructor performs a
different task.
Example
class Student5
{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n)
{
id = i;
name = n;
}
//creating three arg constructor
COPY CONSTRUCTOR
There is no copy constructor in java. But, we can copy the values of one object to
another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
//Java program to initialize the values from one object to another object.
class Student6
{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n)
{
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s)
{
id = s.id;
name =s.name;
}
void display( )
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}}
Output:
111 Karan
111 Karan
Example:
class A
{
A( )
{
System.out.println("A constructor");
}
void Amethod( )
{
System.out.println("method of A");
}}
class B extends A
{
B( )
{
System.out.println("B constructor");
}
void Bmethod( )
{
System.out.println("method of B");
}
void welcome( )
{
System.out.println("class B-welcome method");
}}
class C extends B
{
C( )
{
System.out.println("C constructor");
}
void welcome()
{
System.out.println("class C- welcome method");
}
public static void main(String args[])
{
C oc=new C( );
oc.Amethod( );
oc.Bmethod( );
oc.welcome( );
}}
Output:
A constructor
B constructor
C constructor
method of A
method of B
method of A
POLYMORPHISM
Polymorphism in Java is a concept by which we can perform a single action in
different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java:
1. Compile-time polymorphism or Ad hoc polymorphism
2. Runtime polymorphism. Or Pure polymorphism
Compile time Polymorphism (or Static polymorphism)
Polymorphism that is resolved during compiler time is known as static polymorphism.
Method overloading is an example of compile time polymorphism.
Method Overloading:
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) foe two parameters, and
b(int,int,int) for three parameters then it may be difficult foe you as well as other
programmers to understand the behavior of the method because its name differs.
Example:
class SimpleCalculator
{
int add(int a, int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}}
public class Demo
{
public static void main(String args[])
{
SimpleCalculator obj = new SimpleCalculator();
System.out.println(obj.add(10, 20));
System.out.println(obj.add(10, 20, 30));
}}
Output:
30
60
Example
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle
{
//defining a method
void run()
{
System.out.println("Vehicle is running");
}}
//Creating a child class
class Bike2 extends Vehicle
{
//defining the same method as in the parent class
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2(); //creating object
obj.run(); //calling method
}}
Output: Bike is running safely
A class that is declared with abstract keyword, is known as abstract class in java. It
can have abstract and non-abstract methods (method with body). It needs to be extended and
its method implemented.
Syntax:
}
ABSTRACT METHOD
A method that is declared as abstract and does not have implementation is known as
abstract method. The method body will be defined by its subclass.
Syntax:
The Object class is the parent class of all the classes in java by default (directly or
indirectly). The java.lang.Object class is the root of the class hierarchy. Some of the Object
class are Boolean, Math, Number, String etc.
FORMS OF INHERITANCE:
All objects eventually inherit from Object, which provides useful methods such as
equals and toString.
specification -- the superclass just specifies which methods should be available but doesn't
give code. This is supported in java by interfaces and abstract methods.
construction -- the superclass is just used to provide behavior, but instances of the subclass
don't really act like the superclass.
extension -- subclass adds new methods, and perhaps redefines inherited ones as well.
Most commonly used inheritance and sub classification is for specialization. Always
creates a subtype, and the principles of substitutability is explicitly upheld. It is the most ideal
form of inheritance.
// body of class
Specialization
This is another most common use of inheritance. Two different mechanisms are
provided by Java, interface and abstract, to make use of subclassification for specification.
Subtype is formed and substitutability is explicitly upheld.
Mostly, not used for refinement of its parent class, but instead is used for definitions
of the properties provided by its parent.
// body of class
class B extends A {
Specification
The next most common form of inheritance involves specification. The parent class
specifies some behavior, but does not implement the behavior
Child class inherits most of its functionality from parent, but may change the name or
parameters of methods inherited from parent class to form its interface.
This type of inheritance is also widely used for code reuse purposes. It simplifies the
construction of newly formed abstraction but is not a form of subtype, and often violates
substitutability.
Construction
The parent class is used only for its behavior, the child class has no is-a relationship to
the parent.
An example might be subclassing the idea of a Set from an existing List class.
Example of this type of inheritance is done in the definition of the class Properties
which is an extension of the class HashTable.
Generalization or Extension
The child class generalizes or extends the parent class by providing more functionality
The child doesn't change anything inherited from the parent, it simply adds new features
Subclassification for limitation occurs when the behavior of the subclass is smaller or
more restrictive that the behavior of its parent class.
Like subclassification for extension, this form of inheritance occurs most frequently
when a programmer is building on a base of existing classes.
LIMITATION
The child class limits some of the behavior of the parent class.
Example, you have an existing List data type, and you want a Stack
Inherit from List, but override the methods that allow access to elements other than
top so as to produce errors.
Although the Java does not permit a subclass to be formed be inheritance from more than one
parent class, several approximations to the concept are possible.
// body of class
Combination
Two or more classes that seem to be related, but its not clear who should be the parent
and who should be the child.
Example: Mouse and TouchPad and JoyStick
Better solution, abstract out common parts to new parent class, and use subclassing
for specialization.
Execution Speed
Program Size
Message-Passing Overhead
Program Complexity (in overuse of inheritance)