2. Objects
An object can be defined as an instance of a class, and there can be multiple
instances of a class in a program. An Object is one of the Java OOPs concepts
which contains both the data and the function, which operates on the data.
For example - chair, bike, marker, pen, table, car, etc.
3. Class
A class is a blueprint for creating objects (a particular data structure),
providing initial values for state (member variables or attributes), and
implementations of behavior (member functions or methods). The user-
defined objects are created using the class keyword.
Class - Dogs
Data members or objects- size, age, color,
breed, etc.
Methods- eat, sleep, sit and run.
4. Inheritance
INHERITANCE is a mechanism in which one class acquires the property of
another class. The parent class is called a super class and the inherited class is
called a subclass. The keyword extends is used by the sub class to inherit the
features of super class.
Super Class
Derived Class
5. Reusability
Reusability in OOP achieves through the features of Java where it possible to
extend or reuse the properties of parent class or super class or base class in a
subclass and in addition to that, adding extra more features or data members
in the subclass or child class or derived class.
Why is reusability important in OOP?
In object-oriented systems, assessing reusability plays a key role in reducing
a cost and improving the quality of the software. Object-oriented
programming helps in achieving the concept of reusability through different
types of inheritance programs, which further help in
developing reusable software modules
• Inheritance support this reusability
7. What is Polymorphism?
❑ The process of representing one form in multiple form in known as
polymorphism . Typically, polymorphism occurs when there is a hierarchy
of classes and they are related by inheritance.
❑ It means that a call to a member function will cause a different function to
be executed depending on the type of object that invokes the function.
https://www.youtube.com/watch?v=jg4MpYr1TBc
8. What is Polymorphism in OOP?
❑ After the inheritance it is another most important feature of OOP.
❑ In polymorphism, the member functions with same name are define in
base class and also in each derived class.
❑ Polymorphism is used to keep the interface of base class to its derived
classes.
❑ Polymorphism can be achieved by mean of virtual functions.
❑ In polymorphism one pointer to a base class object may also point any
object of its derived class
9. How Polymorphism can be achieved:
Polymorphism can be achieved in Three ways:
1. Function Overloading
2. Function Overriding
3. Dynamic Binding
Types of Polymorphism
10. Types of Polymorphism:
❑ Static Polymorphism: It takes place during Compile time. Function
Overloading, Operator Overloading implements static polymorphism.
❑ Dynamic Polymorphism: It takes place during Run time. The member
function which change Their behavior during run time called Virtual
Functions.
11. Function Overloading
Here we have multiple definitions for the same function name in the same
scope. The definition of the function must differ from each other by the types
and/or the number of arguments in the argument list.
12. Function Overriding
Overriding of functions happens when one class inherits another class. Here
functions of both class have the same name and there world be same
parameter list and return type of the functions should be same.
OUTPUT
13. Simple Java Program
class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
OUTPUT:
Hello, World!
14. Class
A class is a blueprint (It is user defined data types it could be anything) or
prototype from which objects are created. This section defines a class that
models the state and behavior of a real-world object. It intentionally focuses
on the basics, showing how even simple classes can cleanly model state and
behavior.
E.g.
class Demo {
public static void main (String args[])
{
System.out.println("Welcome to Java”);
}
}
class class_name
{
}
15. Object
An object is a software bundle of related state and behavior. Software
objects are often used to model the real-world objects that you find in
everyday life (Object is real world Entity to represent a physical instance of a
Class). A software object maintains its state in variables and implements its
behavior with methods.
16. How to Create Object in Java
1.Declaration − A variable declaration with a variable name with an object type.
2.Instantiation − The 'new' keyword is used to create the object.
3.Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
• Example
• Create an object called "myObj" and print the value of x:
public class Main
{
int x = 5;
public static void main(String[] args)
{
Main myObj = new Main();
System.out.println(myObj.x);
}
}
class_name object_name=new class_name();
17. JVM
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 is JVM
• A specification where working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its
implementation has been provided by Oracle and other companies.
• An implementation Its implementation is known as JRE (Java Runtime
Environment).
• Runtime Instance Whenever you write java command on the command
prompt to run the java class, an instance of JVM is created.
18. 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.
23. Method Overriding
class A
{
void displayMessage()
{
System.out.println(“Hi we are in class A”);
}
}
class B extends A
{
void displayMessage()
{
System.out.println(“Hi we are in class B”);
}
}
public class Main
{
public static void main(String[] args)
{
}
}
Display Method
24. Method Overriding
class A
{
void displayMessage()
{
System.out.println(“Hi we are in class A”);
}
}
class B extends A
{
void displayMessage()
{
System.out.println(“Hi we are in class B”);
}
}
public class Main
{
public static void main(String[] args)
{
A objA = new A();
B objB = new B();
objA.displayMessage();
objB.displayMessage();
}
}
OUTPUT
Hi we are in class A
Hi we are in class B
25. Method Overriding
class A
{
void displayMessage()
{
System.out.println(“Hi we are in class A”);
}
}
class B extends A
{
void displayMessage()
{
System.out.println(“Hi we are in class B”);
}
}
public class Main
{
public static void main(String[] args)
{
A objA = new B(); // Super type reference refers to a derived class object
objA.displayMessage();
}
}
A is Super Class
B is subclass /derived class
OUTPUT
Hi we are in class B
This is called Run time polymorphism
26. Method Overriding
class A
{
static void displayMessage()
{
System.out.println(“Hi we are in class A”);
}
}
class B extends A
{
static void displayMessage()
{
System.out.println(“Hi we are in class B”);
}
}
public class Main
{
public static void main(String[] args)
{
A objA = new B();
objA.displayMessage();
}
}
OUTPUT
Hi we are in class A
Can’t override the method when we use static
27. public class OverLoading
{
static class Mthdoverloading
{
void test()
{
System.out.println("No parameters");
}
//Overload test for one integer parameter.
void test(int a)
{
System.out.println("a: "+a);
}
//Overload test for two integer parameters.
void test(int a, int b)
{
System.out.println("a and b: " + a + " " +b);
}
}
public static void main(String[] args)
{
Mthdoverloading obj= new Mthdoverloading();
obj.test();
obj.test(10);
obj.test(10,20);
}
}
Output:
No parameters
a: 10
a and b: 10 20
28. Java Overview
• Java is a popular programming language, created in 1995.
• It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
• Mobile applications (specially Android apps)
• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Database connection
29. Why Use Java?
• Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
• It is one of the most popular programming language in the world
• It is easy to learn and simple to use
• It is open-source and free
• It is secure, fast and powerful
• It has a huge community support (tens of millions of developers)
• Java is an object oriented language which gives a clear structure to programs and
allows code to be reused, lowering development costs
30. Java Variables
• Variables are containers for storing data values.
• In Java, there are different types of variables, for example:
• String - stores text, such as "Hello". String values are surrounded by double quotes
• int - stores integers (whole numbers), without decimals, such as 123 or -123
• float - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded by
single quotes
• boolean - stores values with two states: true or false
Declaring (Creating) Variables
Syntax
type variable = value;
Example
• Create a variable called name of type String and assign it the
value "John":
String name = "John"; System.out.println(name);
int myNum = 15;
System.out.println(myNum);
31. Java Data Types
Data types are divided into two groups:
❑ Primitive data types - includes byte, short, int, long, float, double, boolean and
char
❑ Non-primitive data types - such as String, Arrays and Classes
Primitive Data Types
• A primitive data type specifies the size and type of variable values, and it has no
additional methods.
• There are eight primitive data types in Java:
32. Primitive Datatypes
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to
2,147,483,647
long 8 bytes Stores whole numbers from -
9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6
to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing
15 decimal digits
boolean 1 bit Stores true or false values
char 2 bytes Stores a single character/letter or ASCII values
33. Numbers
Numbers
• Primitive number types are divided into two groups:
• Integer types stores whole numbers, positive or negative (such as 123 or -456),
without decimals. Valid types are byte, short, int and long. Which type you should
use, depends on the numeric value.
• Floating point types represents numbers with a fractional part, containing one or
more decimals. There are two types: float and double.
Integer Types
Byte
The byte data type can store whole numbers from -128 to 127. This can be used
instead of int or other integer types to save memory when you are certain that the
value will be within -128 and 127:
Example
byte myNum = 100;
System.out.println(myNum);
34. Short
Short
• The short data type can store whole numbers from -32768 to 32767:
Example
short myNum = 5000; System.out.println(myNum);
Int
• The int data type can store whole numbers from -2147483648 to 2147483647. In
general, and in our tutorial, the int data type is the preferred data type when we
create variables with a numeric value.
Example
int myNum = 100000; System.out.println(myNum);
Long
• The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the
value. Note that you should end the value with an "L":
Example
long myNum = 15000000000L; System.out.println(myNum);
35. Floating Point Types
Floating Point Types
• You should use a floating point type whenever you need a number with a decimal,
such as 9.99 or 3.14515.
Float
• The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note
that you should end the value with an "f":
Example
float myNum = 5.75f;
System.out.println(myNum);
Double
• The double data type can store fractional numbers from 1.7e−308 to 1.7e+308.
Note that you should end the value with a "d":
Example
double myNum = 19.99d;
System.out.println(myNum);
36. Booleans
• A boolean data type is declared with the boolean keyword and can only take the
values true or false:
Example
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); // Outputs true
System.out.println(isFishTasty); // Outputs false
Characters
• The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':
Example
char myGrade = 'B'; System.out.println(myGrade);
37. Strings
• The String data type is used to store a sequence of characters (text). String values
must be surrounded by double quotes:
Example
String greeting = "Hello World";
System.out.println(greeting);
38. Operators
OPERATOR
❑ An operator is a symbol that operates on one or more arguments to produce
a result.
❑ Java provides a rich set of operators to manipulate variables.
OPERANDS
🞆 An operands are the values on which the operators act upon.
🞆 An operand can be:
o A numeric variable - integer, floating point or character
o Any primitive type variable - numeric and boolean
o Reference variable to an object
o A literal - numeric value, boolean value, or string.
o An array element, "a[2]“
o char primitive, which in numeric operations is treated as an unsigned two
byte integer
40. ASSIGNMENT OPERATORS
• The assignment statements has the following syntax:
<variable> = <expression>
ASSIGNING VALUES EXAMPLE
41. INCREMENT AND DECREMENT OPERATORS
++ AND --
❑ The increment and decrement operators add an integer variable by one.
❑ increment operator:
❑ two successive plus signs, ++
❑ decrement operator: --
Common Shorthand
a = a + 1; a++; or ++a;
a = a - 1; a--; or --a;
42. EXAMPLE OF ++ AND -- OPERATORS
public class Example
{
public static void main(String[] args)
{
int j, p, q, r, s;
j = 5;
p = ++j;
System.out.println("p = " + p);
q = j++;
System.out.println("q = " + q);
System.out.println("j = " + j);
r = --j;
System.out.println("r = " + r);
s = j--;
System.out.println("s = " + s);
}
}
OUTPUT:
> java example
p = 6
q = 6
j = 7
r = 6
s = 6
43. ARITHMETIC OPERATORS
❑ The arithmetic operators are used to construct mathematical expressions as in
algebra.
❑ Their operands are of numeric type.
45. BITWISE OPERATORS
• Java's bitwise operators operate on individual bits of integer (int and long) values.
• If an operand is shorter than an int, it is promoted to int before doing the
operations.
46. EXAMPLE OF BITWISE OPERATORS
class Test {
public static void main(String args[])
{
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
System.out.println("a & b = " + c );
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = ~a; /*-61 = 1100 0011 */
System.out.println("~a = " + c );
c = a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c );
c = a >> 2; /* 215 = 1111 */
System.out.println("a >> 2 = " + c );
c = a >>> 2; /* 215 = 0000 1111 */
System.out.println("a >>> 2 = " + c );
}
}
47. RELATIONAL OPERATORS
❑ A relational operator compares two values and determines the relationship
between them.
❑ For example, != returns true if its two operands are unequal.
❑ Relational operators are used to test whether two values are equal, whether one
value is greater than another, and so forth.
48. EXAMPLE OF RELATIONAL OPERATORS
public LessThanExample
{
public static void main(String args[])
{
int a = 5; int b = 10;
if(a < b)
{
System.out.println("a is less than b");
}
}
49. LOGICAL OPERATORS
• These logical operators work only on boolean operands. Their return values are
always boolean.
50. EXAMPLE OF LOGICAL OPERATORS
public class ANDOperatorExample
{
public static void main(String[] args)
{
char ans = 'y';
int count = 1;
if(ans == 'y' & count == 0){
System.out.println("Count is Zero.");
}
if(ans == 'y' & count == 1) {
System.out.println("Count is One.");
}
if(ans == 'y' & count == 2) {
System.out.println("Count is Two.");
}
}
}
51. TERNARY OPERATORS
❑ Java has a short hand way by using ?: the ternary aka conditional operator for
doing ifs that compute a value.
❑ Unlike the if statement, the conditional operator is an expression which can be
used for
EXAMPLE OF TERNARY OPERATOR
52. COMMA OPERATORS
❑ Java has an often look past feature within it’s for loop and this is the comma
operator.
❑ Usually when people think about commas in the java language they think of a way
to split up arguments within a functions parameters
EXAMPLE OF COMMA OPERATOR
public class CommaOperator
{
public static void main(String[] args)
{
for(int i = 1, j = i + 10; i < 5;
i++, j = i * 2) {
System.out.println("i= " + i + " j= " + j);
}
}
}
53. INSTANCEOF OPERATORS
❑ This operator is used only for object reference variables. The operator checks
whether the object is of a particular type(class type or interface type).
❑ InstanceOf operator is wriiten as:
54. EXAMPLE OF INSTANCEOF OPERATOR
class Vehicle
{
}
public class Car extends Vehicle
{
public static void main(String args[])
{
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result);
}
}
55. control statements
Statements that determine which statement to execute and when are known as
decision-making statements. The flow of the execution of the program is controlled by
the control flow statement.
There are four decision-making statements available in java.
❑ Simple if statement
❑ if-else statement
❑ Nested if statement
❑ Switch statement
Looping statements
❑ While
❑ Do-while
❑ For
Branching statements
❑ Switch
❑ Break
❑ Continue
56. If state
Control Statements can be divided into three categories, namely
• Selection statements
• Iteration statements
• Jump statements
if Statement
Use the if statement to specify a block of Java code to be executed if a condition
is true.
Example
if (20 > 18)
{
System.out.println("20 is greater than 18");
}
57. Class Fundamental
• The general form of class
• When you define a class, you declare its exact form and nature. You do this
by specifying the data that it contains and the code that operates on that data.
While very simple classes may contain only code or only data, most real-world
classes contain both. As you will see, a class’ code defines the interface to its data.
• A class is declared by use of the class keyword. The classes that have been
used up to this point are actually very limited examples of its complete form.
Classes can ( and usually do) get much more complex. The general form of a class
definition is shown here:
58. class classname {
type instance-variable1;
type instance-variable2;
// ..
type instance-variableN;
type methodname1(parameter-list) {
//body of method
}
type methodname2(parameter-list) {
//body of method
}
//..
type methodnameN(parameter-list) {
// body of method
}
}
59. Methods
A method is a block of code which only runs when it is called. You can pass data,
known as parameters, into a method. Methods are used to perform certain actions,
and they are also known as functions.
Create a Method
• A method must be declared within a class. It is defined with the name of
the method, followed by parentheses (). Java provides some pre-defined
methods, such as System.out.println(), but you can also create your own
methods to perform certain actions:
• Example
public class Main {
static void myMethod()
{
// code to be executed
}
}
60. Call a Method
call a method in Java, write the method's name followed by two parentheses () and a
semicolon;
In the following example, myMethod() is used to print a text (the action), when it is
called:
61. Constructor
Java Constructors
• A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created. It can be used to set initial
values for object attributes
// Create a Main class
public class Main
{
int x; // Create a class attribute
// Create a class constructor for the Main class
public static void main(String[] args) {
Main myObj = new Main(); // Create an object of class Main (This will call the
constructor)
System.out.println(myObj.x); // Print the value of x
}
}
// Outputs 5
62. Parameterized Constructors
/* Here, Box uses a parameterized constructor to
initialize the dimensions of a box.
*/
class Box
{
double width;
double height;
double depth;
// This is the constructor for Box.
void Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
63. Parameterized Constructors
class BoxDemo7
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
The output from this program is shown here:
Volume is 3000.0
Volume is 162.0
64. this
• Definition and Usage
• The this keyword refers to the current object in a method or constructor.
• The most common use of the this keyword is to eliminate the confusion between
class attributes and parameters with the same name (because a class attribute is
shadowed by a method or constructor parameter). If you omit the keyword in the
example above, the output would be "0" instead of "5".
this can also be used to:
• Invoke current class constructor
• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call
65. Example
public class Main {
int x;
// Constructor with a parameter
public Main(int x)
{
int x=10;
this.x = x;
}
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}
66. This
public class Main
{
int a=10; //instance variable(Global Variable in C)
void display()
{
int a=1000; //Local variable
System.out.println(a);
System.out.println(this.a);
}
public static void main(String[] args)
{
Main obj=new Main();
obj.display();
}
}
67. Garbage Collections
Java garbage collection is the process by which Java programs perform automatic
memory management. Java programs compile to bytecode that can be run on a Java
Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are
created on the heap, which is a portion of memory dedicated to the program.
Eventually, some objects will no longer be needed. The garbage collector finds these
unused objects and deletes them to free up memory.
68. public class Main
{
int a=10; //instance variable(Global Variable in C)
void display()
{
int a=1000; //Local variable
System.out.println(a);
System.out.println(this.a);
}
public static void main(String[] args)
{
Main obj=new Main();
Main obj1=new Main();
Main obj2=new Main();
Main obj3=new Main();
obj.display();
}
}