Post on 21-Apr-2022
DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING
CS8392 OBJECT ORIENTED PROGRAMMING
Object-oriented programming (OOP) is an
engineering approach for building software
systems
• Based on the concepts of classes and objects that
are used for modeling the real world entities
Object-oriented programs
• Consist of a group of cooperating objects
• Objects exchange messages, for the purpose of
achieving a common ob4jective
• Implemented in object-oriented languages
CLASSES AND OBJECTS
• A class is a prototype, idea, and blueprint for
creating objects.
• An object is an instance of a class.
• For example, in Java we define classes,
which in turn are used to create objects
• A class has a constructor for creating objects
• Class is composed of three things: its name,
attributes/properties, and methods.
CLASS
Objects:
Instances of the class
Class
Instance Properties:
Belong to the object
Class Properties:
Belong to the class
Methods:
Functions of class
CLASSES EXAMPLE
EX
hour
minute
void addMinutes( int m )
Time inTime Attributes:
hour = 8 minute = 30
Methods: void addMinutes(int m)
outTime Attributes:
hour = 17 minute = 35
Methods: void addMinutes(int m)
CLASSES & OBJECTS
CLASS
6
objects
CLASSES – EXAMPLE CLASS
Account
+Owner: Person +Ammountt: double
+suspend() +deposit(sum:double) +withdrraw(sum:double)
Class Attttributes
Operattiions
CLASSES AND OBJECTS – EXAMPLE
CLASS AND OBJECTS
Account
+Owner: Person +Ammount: double
+suspend(() +deposit(sum:double) +withdraw(sum:double)
Cllass ivanAccount
+Owner="Ivan Kollev" +Ammount=5000.0
peterAccount
+Owner="Peter Kirov" +Ammountt=1825.33
kirilAccount
+Owner="Kiril Kirov"
+Ammount=1245.0
Objject
Objject
9
CLASS OBJECT
Class is a data type Object is an instance of Class.
It generates OBJECTS It gives life to CLASS
Does not occupy memory
location
It occupies memory location.
It cannot be manipulated
because it is not available in
memory (except static class)
It can be manipulated.
Object is a class in “runtime”
OOPS CONCEPTS
• INHERITANCE
• ABSTRACTION
• ENCAPSULATION
• POLYMORPHISM
OBJECT ORIENTED CONCEPTS
Class – A class defines the blue print i.e. structure and functions of an object.
Objects – Objects help us to decompose large systems and help us to modularize our system. Modularity helps to divide our system into understandable components so that we can build our system piece by piece. An object is the fundamental unit (building block) of a system which is used to depict an entity.
Inheritance – Inheritance is a mechanism by which child classes inherit the properties of their parent classes.
Abstraction – Mechanism by which implementation details are hidden from user.
Encapsulation – Binding data together and protecting it from the outer world is referred to as encapsulation.
Polymorphism – Mechanism by which functions or entities are able to exist in different forms.
CLASS
A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order:
Modifiers: A class can be public or has default access (Refer this for details).
Class name: The name should begin with a initial letter (capitalized by convention).
Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
Body: The class body surrounded by braces, { }
OBJECT
It is a basic unit of Object Oriented Programming and
represents the real life entities. A typical Java program
creates many objects, which as you know, interact by
invoking methods. An object consists of:State : It is
represented by attributes of an object. It also reflects the
properties of an object.
Behavior : It is represented by methods of an object. It
also reflects the response of an object with other objects.
Identity : It gives a unique name to an object and
enables one object to interact with other objects.
Example of an object: dog
INHERITANCE
Inheritance is an important pillar of
OOP(Object Oriented Programming). It is the
mechanism in java by which one class is allow to
inherit the features(fields and methods) of another
class
Syntax:
class derived-class extends base-class
{
//methods and fields
}
INHERITANCE
Inheritance Person
+Name: Sttrriing +Address: String
Employee
+Company: String +Sallarry: double
Student
+Schooll:: String
Subclass Subclass
class Super
{ ..... ..... }
class Sub extends Super
{ ..... ..... }
TYPES
Single Inheritance
Multiple inheritance
Hierarchical inheritance
Multilevel inheritance
IMPORTANT TERMINOLOGY:
Super Class: The class whose features are inherited is known as superclass(or a base class or a parent class).
Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
The keyword used for inheritance is extends.
ENCAPSULATION
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates.
Another way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield.
Technically in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of own class in which they are declared.
As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
Encapsulation can be achieved by Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.
ENCAPSULATIO
N
21
ENCAPSULATION – EXAMPLE
• Data Fields are private
• Constructors and accessor methods are
defined
ABSTRACTION
Data Abstraction is the property by virtue of which only the essential details are displayed to the user.The trivial or the non-essentials units are not displayed to the user.
Ex: A car is viewed as a car rather than its individual components.Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviours of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects.
Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of car or applying brakes will stop the car but he does not know about how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of accelerator, brakes etc in the car. This is what abstraction is.
POLYMORPHISM
Polymorphism refers to the ability of
OOPs programming languages to differentiate
between entities with the same name efficiently.
This is done by Java with the help of the
signature and declaration of these entities.
POLYMORPHISM – EXAMPLE
37
Square::calcSurface() {
return size * size;
}
Circle::calcSurface() {
return PI * radius *
raduis;
}
Abstract class
Abstract action
Concrete class
Overriden action Overriden
action
METHOD
A method is a collection of statements that
perform some specific task and return result to the caller.
A method can perform some specific task without
returning anything. Methods allow us to reuse the code
without retyping the code.
Methods are time savers and help us to reuse the
code without retyping the code.Method Declaration
In general, method declarations has six components:
Access Modifier: Defines access type of the method i.e. from where it can be accessed in your application. In Java, there 4 type of the access specifiers.
public: accessible in all class in your application.
protected: accessible within the package in which it is defined and in its subclass(es)(including subclasses declared outside the package)
private: accessible only within the class in which it is defined.
default (declared/defined without using any modifier): accessible within same class and package within which its class is defined.
The return type: The data type of the value returned by the method or void if does not return a value.
Method Name: the rules for field names apply to method names as well, but the convention is a little different.
Parameter list: Comma separated list of the input parameters are defined, preceded with their data type, within the enclosed parenthesis. If there are no parameters, you must use empty parentheses ().
Exception list: The exceptions you expect by the method can throw, you can specify these exception(s).
Method body: it is enclosed between braces. The code you need to be executed to perform your intended operations.
MESSAGE PASSING
Objects communicate with one another by
sending and receiving information to each other.
A message for an object is a request for
execution of a procedure and therefore will invoke a
function in the receiving object that generates the desired
results.
Message passing involves specifying the name
of the object, the name of the function and the
information to be sent
MESSAGES
A request for an object to perform one of its
operations (methods)
All communication between objects is done via
messages
Object 3
Object 2
OBJECT INTERACTION
32
Object 1
Property
Method
Property
Method
Property
Method
Message
ADVANTAGES OF OOPS: OOP offers easy to understand and a clear modular structure
for programs.
Objects created for Object-Oriented Programs can be reused in
other programs. Thus it saves significant development cost.
Large programs are difficult to write, but if the development
and designing team follow OOPS concept then they can better
design with minimum flaws.
It also enhances program modularity because every object
exists independently
WHAT IS JAVA
•Java is a programming language and a platform. Java
is a high level, robust, object-oriented and secure
programming language.
•Java was developed by Sun Microsystems (which is
now the subsidiary of Oracle) in the year 1995. James
Gosling is known as the father of Java. Before Java, its
name was Oak. Since Oak was already a registered
company, so James Gosling and his team changed the
Oak name to Java.
•Platform: Any hardware or software environment in
which a program runs, is known as a platform. Since
Java has a runtime environment (JRE) and API, it is
called a platform
JAVA EXAMPLE
Let's have a quick look at Java programming example. A
detailed description of Hello Java example .
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Output-Hello Java
APPLICATIONS
According to Sun, 3 billion devices run Java. There are many devices where Java is currently used. Some of them are as follows:
Desktop Applications such as acrobat reader, media player, antivirus, etc.
Web Applications such as irctc.co.in, javatpoint.com, etc.
Enterprise Applications such as banking applications.
Mobile
Embedded System
Smart Card
Robotics
Games, etc.
Types of Java Applications
1) Standalone Application
2) Web Application
3) Enterprise Application
4) Mobile Application
JAVA PLATFORMS / EDITIONS
There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc.
2) Java EE (Java Enterprise Edition)
It is an enterprise platform which is mainly used to develop web and enterprise applications. It is built on the top of the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA, etc.
3) Java ME (Java Micro Edition)
It is a micro platform which is mainly used to develop mobile applications.
4) JavaFX
It is used to develop rich internet applications. It uses a light-weight user interface API
FEATURES OF JAVA
The primary objective of Java programming language
creation was to make it portable, simple and secure
programming language. Apart from this, there are also
some excellent features which play an important role in
the popularity of this language. The features of Java are
also known as java buzzwords
A list of most important features of Java language is given below.
Simple
Object-Oriented
Portable
Platform independent
Secured
Robust
Architecture neutral
Interpreted
High Performance
Multithreaded
Distributed
Dynamic
The Java platform differs from most other
platforms in the sense that it is a software-based
platform that runs on the top of other hardware-
based platforms. It has two components:
Runtime Environment
API(Application Programming Interface)
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
To compile:javac Simple.java
To execute:java Simple
Output:Hello Java
PARAMETERS USED IN FIRST JAVA PROGRAM
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility. It means it is visible to all.
static is a keyword. If we declare any method as static, it is known as the static method. The core advantage of the static method is that there is no need to create an object to invoke the static method. The main method is executed by the JVM, so it doesn't require to create an object to invoke the main method. So it saves memory.
void is the return type of the method. It means it doesn't return any value.
main represents the starting point of the program.
String[] args is used for command line argument. We will learn it later.
System.out.println() is used to print statement. Here, System is a class, out is the object of PrintStream class, println() is the method of PrintStream class. We will learn about the internal working of System.out.println statement later.
By changing the sequence of the modifiers, method
prototype is not changed in Java.
static public void main(String args[])
The subscript notation in Java array can be used after type,
before the variable or after the variable.
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
VALID JAVA MAIN METHOD SIGNATURE
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
public static void main(String... args)
static public void main(String[] args)
public static final void main(String[] args)
final public static void main(String[] args)
final strictfp public static void main(String[] ar
gs)
INVALID JAVA MAIN METHOD SIGNATURE
public void main(String[] args)
static void main(String[] args)
public void static main(String[] args)
abstract public static void main(String[] args)
How to set the Temporary Path of JDK in Windows
To set the temporary path of JDK, you need to
follow the following steps:
Open the command prompt
Copy the path of the JDK/bin directory
Write in command prompt: set path=copied_path
For Example:
set path=C:\Program
Files\Java\jdk1.6.0_23\bin
JRE
JRE is an acronym for JAVA RUNTIME
ENVIRONMENT. It is also written as Java
RTE. The Java Runtime Environment is a set of
software tools which are used for developing Java
applications. It is used to provide the runtime
environment. It is the implementation of JVM. It
physically exists. It contains a set of libraries +
other files that JVM uses at runtime.
JRE
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
Standard Edition Java Platform
Enterprise Edition Java Platform
Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to complete the development of a Java Application
JDK
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist. It is a specification that provides a runtime environment in which Java bytecode can be executed. It can also run those programs which are written in other languages and compiled to Java bytecode.
The JVM performs the following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JVM (JAVA VIRTUAL MACHINE) ARCHITECTURE
JVM (Java Virtual Machine) is an abstract
machine. It is a specification that provides
runtime
environment in which java bytecode can be
executed.
JVMs are available for many hardware and
software platforms (i.e. JVM is platform
dependent)
WHAT IT DOES
The JVM performs following operation:
Loads code
Verifies code
Executes code
Provides runtime environment
JVM provides definitions for the:
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc
Memory areas
allocated by
JVM
Java
native
libraries
CLASSLOADER
1)Classloader
is a subsystem of JVM which is used to load class files.
Whenever we run the java program, it is loaded first by the classloader.
There are three built-in classloaders in Java.
Bootstrap ClassLoader: This is the first classloader which is the super
class of Extension classloader. It loads the rt.jar file which contains all class
files of Java Standard Edition like java.lang package classes, java.net
package classes, java.util package classes, java.io package classes, java.sql
package classes etc.
Extension ClassLoader: This is the child classloader of Bootstrap and
parent classloader of System classloader. It loades the jar files located
inside $JAVA_HOME/jre/lib/ext directory.
System/Application ClassLoader: This is the child classloader of
Extension classloader. It loads the classfiles from classpath. By default,
classpath is set to current directory. You can change the classpath using "-
cp" or "-classpath" switch. It is also known as Application classloader.
JVM ARCHITECTURE
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.
3) Heap
It is the runtime data area in which objects are allocated.
4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
5) Program Counter Register
PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.
6) Native Method Stack
It contains all the native methods used in the application.
7) Execution Engine
It contains:
A virtual processor
Interpreter: Read bytecode stream then execute the instructions.
Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here, the term "compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.
8) Java Native Interface
Java Native Interface (JNI) is a framework which provides an interface to communicate with another application written in another language like C, C++, Assembly etc. Java uses JNI framework to send output to the Console or interact with OS libraries.
DEFINING CLASSES IN JAVA
The class is at the core of Java .A class is a template for an object, and an object is an instance of a class. A class is declared by use of the class keyword
Syntax:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;type
methodname1(parameter-list) {
// body of method}...
type methodnameN(parameter-list) {
// body of method
}
The data, or variables, defined within a class are
called instance variables. The code is contained within
methods.
The methods and variables defined within a class
are called members of the class. In most classes, the
instance variables are acted upon and accessed by the
methods defined for that class.
Variables defined within a class are called
instance variables because each instance of the class
(that is, each object of the class) contains its own copy
of these variables. Thus, the data for one object is
separate and unique from the data for another
A Simple Class
class called Box that defines three instance variables:
width, height, and depth.
class Box
{
double width ;double height; double depth;
}
The new data type is called Box. This name is used to
declare objects of type Box.
The class declaration only creates a template. It does not
create an actual object
DECLARING OBJECTS
First, declare a variable of the class type. This variable does not define an object.
Second, you must acquire an actual,physical copy of the object and assign it to that variable.
This is done using the newoperator. The new operator dynamically a
llocates (that is, allocates at run time) memory for an object and returns a reference to it.
This reference is then stored in the variable. Thus,in Java, all class objects must be dynamically allocated
SYNTAX
Box mybox = new Box();
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box objec
The first line declares mybox as a reference to an object of type
Box.
At this point, myboxdoes not yet refer to an actual object. The
next line allocates an object and assigns areference to it to
mybox.
After the second line executes, wecan use mybox as if it were
aBox object.
But in reality, mybox simply holds, in essence, the memory
address of the actualBox object
ASSIGNING OBJECT REFERENCE
VARIABLES
Syntax:
Box b1 = new Box();
Box b2 = b1;
CONSTRUCTORS Constructors are special member functions whose task is to
initialize the objects of its class.
It is a special member function, it has the same as the class
name.
Java constructors are invoked when their objects are created. It
is named such because, it constructs the value, that isprovides
data for the object and are used to initialize objects.
Every class has a constructor when we don't explicitly declare a
constructor for any java class the compiler creates a default
constructor for that class which does not have any return type.
The constructor in Java cannot be abstract, static, final or
synchronized and these modifiers are not allowed for the
constructor.
There are two types of constructors:
1.Default constructor (no-arg constructor)
2.Parameterized constructor
METHODS
METHOD IN JAVA
In general, a method is a way to perform some task. Similarly, the method in Java is a collection of instructions that performs a specific task.
It provides the reusability of code. We can also easily modify code using methods.
In this section, we will learn what is a method in Java, types of methods, method declaration, and how to call a method in Java.
METHOD
A method is a block of code or collection of
statements or a set of code grouped together to
perform a certain task or operation. It is used to
achieve the reusability of code
Method Signature: Every method has a method signature. It is a part of the method declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the method. Java provides four types of access specifier:
Public: The method is accessible by all classes when we use public specifier in our application.
Private: When we use a private access specifier, the method is accessible only in the classes in which it is defined.
Protected: When we use protected access specifier, the method is accessible within the same package or subclasses in a different package.
Default: When we do not use any access specifier in the method declaration, Java uses default access specifier by default. It is visible only from the same package only.
modifier − It defines the access type of the method and it is optional to use.
Return Type: Return type is a data type that the method returns. It may have a primitive data type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method name must be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It contains the data type and variable name. If the method has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within the pair of curly braces.
NAMING A METHOD
While defining a method, remember that the method name must be a verb and start with a lowercase letter. If the method name has more than two words, the first name must be a verb followed by adjective or noun. In the multi-word method name, the first letter of each word must be in uppercase except the first word. For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name in the same class, it is known as method overloading.
TYPES OF METHOD
There are two types of methods in Java:
Predefined Method
User-defined Method
Predefined Method In Java, predefined methods are the method that is already defined in
the Java class libraries is known as predefined methods. It is also known as the standard library method or built-in method.
We can directly use these methods just by calling them in the program at any point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
User-defined Method The method written by the user or programmer is known as a user-
defined method. These methods are modified according to the requirement.
STATIC METHOD
A method that has static keyword is known as static
method. In other words, a method that belongs to a
class rather than an instance of a class is known as a
static method. We can also create a static method by
using the keyword static before the method name.
The main advantage of a static method is that we can
call it without creating an object. It can access static
data members and also change the value of it. It is
used to create an instance method. It is invoked by
using the class name. The best example of a static
method is the main() method.
INSTANCE METHOD
The method of the class is known as an instance
method. It is a non-static method defined in the class.
Before calling or invoking the instance method, it is
necessary to create an object of its class. Let's see an
example of an instance method.
There are two types of instance method:
Accessor Method
Mutator Method
ABSTRACT METHOD
The method that does not has method body is
known as abstract method. In other words,
without an implementation is known as
abstract method. It always declares in
the abstract class. It means the class itself
must be abstract if it has abstract method. To
create an abstract method, we use the
keyword abstract.
Syntax
abstract void method_name();
OVERLOADING METHODS
When two or more methods within the same class that
have the same name, but their parameter declarations are
different.
The methods are said to be overloaded, and the process
is referred to as method overloading
Method overloading is one of the ways that Java
supports polymorphism.
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
METHOD OVERRIDING
When a method in a subclass has the same name and
type signature as a method in its superclass, then the
method in the subclass is said to override the method in
the superclass.
When an overridden method is called from within its
subclass, it will always refer to the version of that
method defined by the subclass. The version of the
method defined by the superclass will be hidden.
ACCESS PROTECTION
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of java access modifiers:
1. private -The private access modifier is accessible only within class.
2. default- If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package.
3. protected -The protected access modifier is accessible within package and outside the package but through inheritance only.
4. public –The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
STATIC MEMBERS
Static is a non-access modifier in Java which is
applicable for the following:
1. blocks
2. variables
3. methods
4. nested classes
JAVA COMMENTS
The java comments are statements that are not executed by the compiler and interpreter. The comments can be used to provide information or explanation about the variable, method, class or any statement. It can also be used to hide program code for specific time.
There are 3 types of comments in java.
1. Single Line Comment
Syntax:
//This is single line comment
2. Multi Line Comment
Syntax:
/* This is multi line comment */
3. Documentation Comment
Syntax:
/** This is documentation comment*/
DATA
TYPES IN JAVA
DATATYPES IN JAVA
Data types specify the different sizes and
values that can be stored in the variable. There are
two types of data types in Java:
1. Primitive data types:
The primitive data types include Integer,
Character, Boolean, and Floating Point.
2. Non-primitive data types:
The non-primitive data types include Classes,
Interfaces, and Arrays.
Java defines eight primitive types of data: byte, short, int,
long, char, float, double, and boolean. These can be put in four
groups:
• Integers This group includes byte, short, int, and long, which
are for wholevalued signed numbers.
Floating-point numbers This group includes float and
double, which represent numbers with fractional precision.
• Characters This group includes char, which represents symbols
in a character set, like letters and numbers.
• Boolean This group includes boolean, which is a special type
for representing true/false values.
A variable is a container which holds the value and that
can be changed durig the execution of the program.
A variable is assigned with a datatype. Variable is a name
of memory location.
All the variables must be declared before they can be
used.
There are three types of variables in java:
local variable, instance variable and static variable.
VARIABLE
A variable is a container which holds the value
while the Java program is executed. A variable is
assigned with a data type.
1) Local Variable
A variable defined within a block or method or constructor
is called local variable.
2) Instance Variable
Instance variables are non-static variables and are
declared in a class outside any method, constructor or block.
3) Static variable
Static variables are also known as Class variables.
OPERATORS IN JAVA
Java provides a rich set of operators to manipulate
variables. We can divide all the Java operators into the
following groups
Arithmetic Operators
Increment and Decrement
Bitwise Operators
Relational Operators
Boolean Operators
Assignment Operator
Ternary Operator
Arithmetic Operators
Arithmetic operators are used to manipulate
mathematical expressions
JAVA ARRAYS
Java array is an object which contains elements
of a similar data type. Additionally, The elements
of an array are stored in a contiguous memory
location. It is a data structure where we store
similar elements. We can store only a fixed set of
elements in a Java array.
TYPES OF ARRAY IN JAVA
There are two types of array.
Single Dimensional Array
Multidimensional Array
Advantages
Code Optimization: It makes the code optimized,
we can retrieve or sort the data efficiently.
Random access: We can get any data located at an
index position.
Disadvantages
Size Limit: We can store only the fixed size of
elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework
is used in Java which grows automatically.
CONSTRUCTOR
In Java, a constructor is a block of codes similar
to the method. 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.
Every time an object is created using the new()
keyword, at least one constructor is called
A Java constructor is special method that is called
when an object is instantiated. In other words, when you
use the new keyword.
The purpose of a Java constructor is to initializes the
newly created object before it is used
A Java class constructor initializes instances (objects)
of that class
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();
}
}
RULES FOR CREATING JAVA
CONSTRUCTOR
Constructor name must be the same as its class
name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static,
final, and synchronized
[We can use access modifiers while declaring a
constructor. It controls the object creation. In
other words, we can have private, protected,
public or default constructor in Java]
TYPES OF JAVA CONSTRUCTORS
Default constructor (no-arg constructor)
Parameterized constructor
RULE: IF THERE IS NO CONSTRUCTOR IN A CLASS,
COMPILER AUTOMATICALLY CREATES A DEFAULT
CONSTRUCTOR.
DEFAULT CONSTRUCTOR
The default constructor is used to provide the
default values to the object like 0, null, etc.,
depending on the type.
A constructor is called "Default Constructor"
when it doesn't have any parameter
DEFAULT CONSTRUCTOR
JAVA DEFAULT CONSTRUCTOR
A constructor is called "Default Constructor"
when it doesn't have any parameter.
Syntax of default constructor:
<class_name>(){}
JAVA PARAMETERIZED CONSTRUCTOR
A constructor which has a specific number of
parameters is called a parameterized constructor.
The parameterized constructor is used to
provide different values to distinct objects.
However, you can provide the same values also.
JAVA PARAMETERIZED CONSTRUCTOR