JAVA Merged MN
JAVA Merged MN
Currently It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
Features of Java
OUTPUT
Hello World
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity − Java is case sensitive, which means
identifier Hello and hello would have different meaning in Java.
Class Names − For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class, each inner word's
first letter should be in Upper Case.
Example: class MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner
word's first letter should be in Upper Case.
Example: public void myMethodName()
Program File Name − Name of the program file should exactly match the
class name.
When saving the file, you should save it using the class name (Remember
Java is case sensitive) and append '.java' to the end of the name (if the file
name and the class name do not match, your program will not compile).
But please make a note that in case you do not have a public class present
in the file then file name can be different than class name. It is also not
mandatory to have a public class in the file.
Example: Assume 'MyFirstJavaProgram' is the class
name. Then the file should be saved as 'MyFirstJavaProgram.java'
public static void main(String args[]) − Java program processing starts
from the main() method which is a mandatory part of every Java program.
Java Programming
JVM
JVM (Java Virtual Machine) is an abstract machine that
enables your computer to run a Java program.
When you run the Java program, Java compiler first compiles your Java
code to bytecode. Then, the JVM translates bytecode into native machine
code (set of instructions that a computer's CPU executes directly).
JRE
JRE (Java Runtime Environment) is a software package
that provides Java class libraries, Java Virtual Machine (JVM), and other
components that are required to run Java applications.
If you need to run Java programs, but not develop them, JRE is what you
need.
JDK
JDK (Java Development Kit) is a software development
kit required to develop applications in Java. When you download JDK, JRE
is also downloaded with it.
Java Input
import java.util.Scanner;
Then, we need to create an object of the Scanner class. We can use the
object to take input from the user.
import java.util.Scanner;
class Input {
public static void main(String[] args) {
}
}
Output:
Enter an integer: 23
You entered 23
Java Output
In Java, you can simply use to send output to standard output (screen).
System.out.println(); or
System.out.print(); or
System.out.printf();
Here,
System is a class
out is a public static field: it accepts output data.
Java Programming
class Topperworld {
public static void main(String[] args) {
Output:
like print() method. Then the cursor moves to the beginning of the
next line.
class Output {
public static void main(String[] args) {
Output:
1. println
2. println
1. print 2. print
Java Programming
Keywords in Java
For example:
int score;
implemented in a subclass.
an AssertionError is thrown.
Java Programming
Java.
thrown or not.
Java.
int: used to declare an int variable, which is a data type that can
which means that it can be accessed within the same class or any
subclass.
program.
in Java.
As the name suggests, data types specify the type of data that can be stored
inside variables in Java.
Java is a statically-typed language. This means that all variables must be
declared before they can be used.
int topperworld;
Here, topperworld is a variable, and the data type of the variable is int.
The int data type determines that the topperworld variable can only contain
integers.
Primitive Data Type: such as boolean, char, int, short, byte, long,
float, and double
Non-Primitive Data Type or Object Data type: such as String,
Array, etc.
Java Programming
1. boolean type
The boolean data type has two possible values, either true or false.
class Main {
public static void main(String[] args) {
2. byte type
The byte data type can have values from -128 to 127 (8-bit signed
two's complement integer).
If it's certain that the value of a variable will be within -128 to 127,
then it is used instead of int to save memory.
Default value: 0
class Main {
public static void main(String[] args) {
byte range;
Java Programming
range = 124;
System.out.println(range); // prints 124
}
}
3. short type
class Main {
public static void main(String[] args) {
short temperature;
temperature = -200;
System.out.println(temperature); // prints -200
}
}
Java Programming
4. int type
The int data type can have values from -231 to 231-1 (32-bit signed
two's complement integer).
If you are using Java 8 or later, you can use an unsigned 32-bit
integer. This will have a minimum value of 0 and a maximum value of
232-1.
Default value: 0
class Main {
public static void main(String[] args) {
5. long type
The long data type can have values from -263 to 263-1 (64-bit signed
two's complement integer).
If you are using Java 8 or later, you can use an unsigned 64-bit integer
with a minimum value of 0 and a maximum value of 264-1.
Default value: 0
class LongExample {
public static void main(String[] args) {
}
}
Notice, the use of L at the end of -42332200000. This represents that it's an
6. double type
class Main {
public static void main(String[] args) {
7. float type
class Main {
public static void main(String[] args) {
Notice that we have used -42.3f instead of -42.3in the above program. It's
because -42.3 is a double literal.
To tell the compiler to treat -42.3 as float rather than double, you need to
use f or F.
8. char type
The minimum value of the char data type is '\u0000' (0) and the
class Main {
public static void main(String[] args) {
class Main {
public static void main(String[] args) {
}
}
String type
Java also provides support for character strings via java.lang.String class.
Strings in Java are not primitive types. Instead, they are objects. For
example,
// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";
// print strings
System.out.println(first); // print Java
System.out.println(second); // print Python
System.out.println(third); // print JavaScript
}
}
In the above example, we have created three strings named first , second ,
and third.
Java Programming
Conditional Statement
if Statement
switch Statement
Java-if Statement :
The java if-Statement is used to test the condition.It check boolean condition:
true or false.
If statement
If-else statement
If-else-if ladder
Nested if statement
Java Programming
1. Java if Statement
if (condition) {
// statements
}
Working of if Statement
class IfStatement {
public static void main(String[] args) {
Output
In the program, number < 0 is false. Hence, the code inside the body of
the if statement is skipped.
of else block are executed if the test expression is evaluated to false. This is
known as the if-...else statement in Java.
if (condition) {
// codes in if block
}
Java Programming
else {
// codes in else block
}
Here, the program will do one task (codes inside if block) if the condition
is true and another task (codes inside else block) if the condition is false.
class Main {
public static void main(String[] args) {
int number = 10;
}
}
Output
In the above example, we have a variable named number. Here, the test
Since the value of the number is 10, the test expression evaluates to true.
If we run the program with the new value of number, the output will be:
Here, the value of number is -5. So the test expression evaluates to false.
if (condition1) {
// codes
}
else if(condition2) {
// codes
}
else if (condition3) {
// codes
}
.
.
else {
// codes
}
Here, if statements are executed from the top towards the bottom. When the
test condition is true, codes inside the body of that if block is executed. And,
program control jumps outside the if...else...if ladder.
If all test expressions are false, codes inside the body of else are executed.
class Main {
public static void main(String[] args) {
int number = 0;
Output
The number is 0.
class Main {
public static void main(String[] args) {
else {
largest = n3;
}
} else {
else {
largest = n3;
}
}
Output:
Switch Statement :
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
...
...
default:
// default statements
}
Java Programming
class Main {
public static void main(String[] args) {
case 29:
size = "Small";
break;
case 42:
size = "Medium";
break;
case 48:
size = "Extra Large";
break;
default:
Java Programming
size = "Unknown";
break;
}
System.out.println("Size: " + size);
}
}
Output:
Size: Large
In the above example, we have used the switch statement to find the size.
Here, we have a variable number. The variable is compared with the value of
each case statement.
Since the value matches with 44, the code of case 44 is executed.
size = "Large";
break;
Looping Statement
It is a tool that helps you automate repetitive tasks and can be used to
iterate over arrays, collections, and other data structures. Loops are an
important programming construct that makes code more efficient and
concise, and can help solve complex problems.
For example, if you want to show a message 100 times, then rather
than typing the same code 100 times, you can use a loop.
Types of Loops
In Java, there are three types of loops:
1. For loop
2. For-each loop
3. While loop
4. Do..while loop
For Loop :
Here,
class Main {
public static void main(String[] args) {
int n = 5;
// for loop
for (int i = 1; i <= n; ++i) {
System.out.println("Topperworld");
}
}
}
Output
Topperworld
Topperworld
Topperworld
Topperworld
Topperworld
For-each Loop :
In Java, the for-each loop is used to iterate
through elements of arrays and collections (like ArrayList). It is also
known as the enhanced for loop.
Here,
class Main {
public static void main(String[] args) {
// create an array
int[] numbers = {31, 9, 5, -15};
Output
31
9
5
-15
While Loop :
while (condition) {
// body of loop
}
Here,
class Main {
public static void main(String[] args) {
// declare variables
int i = 1, n = 5;
Output
1
2
3
4
5
Do…While loop :
do {
// body of loop
} while(condition);
Java Programming
Here,
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int i = 1, n = 5;
Output
1
2
3
4
5
Java Programming
Jumping Statement
1. Break statement
2. Continue statement
3. Return statement
Break Statement :
break;
Java Programming
// for loop
for (int i = 1; i <= 10; ++i) {
Output:
1
2
3
4
In the above program, we are using the for loop to print the value of i in
each iteration.
Java Programming
if (i == 5) {
break;
}
This means when the value of i is equal to 5, the loop terminates. Hence
we get the output with values less than 5 only.
Continue Statement :
continue;
// for loop
for (int i = 1; i <= 10; ++i) {
Output:
1
2
3
4
9
10
In the above program, we are using the for loop to print the value of i in
each iteration.
Return Statement :
Output:
Sum of a & b: 15
Java Programming
Operator in Java
Arithmetic Operators :
Operator Description
+ ( Addition ) This operator is used to add the value of the
operands.
Example
Let us look at a simple code that in which all the arithmetic operators are used.
// Addition Operator
result = num1 + num2;
System.out.println("Addition: " + result);
// Subtraction Operator
result = num1 - num2;
System.out.println("Subtraction: " + result);
// Multiplication Operator
result = num1 * num2;
System.out.println("Multiplication: " + result);
// Division Operator
result = num1 / num2;
Java Programming
// Modulus Operator
result = num1 % num2;
System.out.println("Modulus: " + result);
// Increment Operator
num1++;
System.out.println("Increment: " + num1);
// Decrement Operator
num2--;
System.out.println("Decrement: " + num2);
}
}
OUTPUT
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Modulus: 0
Increment: 11
Decrement: 4
Assignment Operators :
Assignment operator are used to assign new value to a variable. The left
side operand of the assignment operator is called variable and the right
side operand of the assignment operator is called value.
Operator Description
This operator is used to assign the value on the
=
right to the operand on the left.
Java Programming
Example
Let us look at a simple code in which all the assignment operators are used.
OUTPUT
10
30
Java Programming
10
200
2
0
Logical Operators :
Operator Description
This operator returns True if both the operands
&& (Logical AND)
are true, otherwise, it returns False.
Example
Let us look at a simple code that in which all the logical operators are used.
OUTPUT
False
True
True
Bitwise Operators :
The bitwise operator operates on bit string, binary number, or bit array. It
is fast and simple and directly supported by the processor. The bitwise
operation is also known as bit-level programming.
Operator Description
This operator takes two numbers as operands
& (Bitwise AND)
and does AND on every bit of two numbers.
Example
Let us look at a simple code that in which all the bitwise operators are used.
// Bitwise OR Operator
result = num1 | num2;
System.out.println("Bitwise OR: " + result);
OUTPUT
Bitwise AND: 0
Bitwise OR: 15
Bitwise XOR: 15
Bitwise Complement of num1: -11
Left Shift of num1: 40
Right Shift of num1: 2
Unsigned Right Shift of num1: 2
Ternary Operators :
Example
OUTPUT
Relational Operators :
Relational operator compares two numbers and returns a boolean value. This
operator is used to define a relation or test between two operands.
Operator Description
This operator returns True, if the value of the
< (Less than) left operand is less than the value of the right
operand, else it returns False.
This operator returns True, if the value of the
> (Greater than) left operand is greater than the value of the right
operand, else it returns False.
This operator returns True, if the value of the
<= (Less than or equal to) left operand is less than or equal to the value of
the right operand, else it returns False.
This operator returns True, if the value of the
>= (Greater than or equal to) left operand is greater than or equal to the value
of the right operand, else it returns False.
Example
Let us look at a simple code that in which all the realational operators are used.
OUTPUT
true
false
true
false
false
true
Java Programming
>= += -= *= /= %= >>=
Assignment Right to left
<<= &= ^= |=
Java Programming
Package in Java
If you want to use the ResultSet interface in your code, just import
the java.sql package (Importing packages will be discussed later in the
article).
For example, you can find two Date classes in Java. However, the rule of
thumb in Java programming is that only one unique class name is allowed
in a Java project.
How did they manage to include two classes with the same name
Date in JDK?
This was possible because these two Date classes belong to two different
packages:
java.util.Date - this is a normal Date class that can be used
anywhere.
java.sql.Date - this is a SQL Date used for the SQL query and such.
Java Programming
Built-in Package
Built-in packages are existing java packages that come along with
the JDK. For example, java.lang, java.util, java.io, etc. For example:
import java.util.ArrayList;
class ArrayListUtilization {
public static void main(String[] args) {
System.out.println(myList);
}
}
Output:
myList = [3, 2, 1]
import java.util.ArrayList;
Java Programming
User-defined Package
Java also allows you to create packages as per your need. These
packages are called user-defined packages.
package packageName;
Java uses file system directories to store packages. Let's create a Java file
inside another directory.
For example:
└── com
└── test
└── Test.java
Now, edit Test.java file, and at the beginning of the file, write the
package statement as:
package com.test;
Here, any class that is declared within the test directory belongs to
the com.test package.
Here's the code:
package com.test;
class Test {
System.out.println("Hello World!");
Output:
Hello World!
The package name must be unique (like a domain name). Hence, there's
a convention to create a package as a domain name, but in reverse order.
For example, com.company.name
Here, each level of the package is a directory in your file system. Like
this:
└── com
└── company
└── name
3. A pop-up box will appear where you can enter the package name.
For example,
import java.util.Date;
// body
The same task can be done using the fully qualified name as follows:
//body
package com.programiz;
}
Java Programming
Now, you can import Helper class from com.programiz package to your
implementation class. Once you import it, the class can be referred
directly by its name. Here's how:
import com.programiz.Helper;
class UseHelper {
Output:
formattedValue = $99.50
Here,
package package.name;
class MyClass {
// body
}
Java Programming
Array in Java
Arrays in Java are declared with a specific data type, followed by square
brackets “[ ]” indicating the size of the array.
Advantage of Array
Easy to use: Arrays are easy to use and implement, making them a
popular choice among programmers.
Fast access: Arrays provide fast and efficient access to elements
based on their index, which makes them ideal for storing and
retrieving data quickly.
Memory efficiency: Arrays are memory-efficient, as they store data
in a contiguous block of memory, which makes them ideal for handling
large amounts of data.
Easy to manipulate: Arrays can be easily manipulated using loops,
making it easy to perform operations on all elements of an array.
Java Programming
Disadvantage of Array
Fixed size: Arrays in Java are of fixed size, which means that the size
of the array cannot be changed once it is initialized.
Lack of flexibility: Arrays cannot be resized dynamically, which
means that if you need to add or remove elements from an array, you
need to create a new array with a different size.
Inefficient for certain operations: Arrays are inefficient for certain
operations, such as sorting and searching, as these operations can
require a lot of computational power and time to execute.
Complex data types: Arrays are not suitable for storing complex data
types, such as objects and structures, as they can only store a single
data type.
Types of Array
Single-Dimensional array
Multi-Dimensional array
Single-Dimensional Array :
dataType[] arrayName;
dataType - it can be primitive data types like int , char , double , byte ,
For example,
double[] data;
// declare an array
double[] data;
// allocate memory
data = new double[10];
Here, the array can store 10 elements. We can also say that the size or
length of the array is 10.
In Java, we can declare and allocate the memory of an array in one single
statement.
For example,
Here, we have created an array named age and initialized it with the values
inside the curly brackets.
Note that we have not provided the size of the array. In this case, the Java
compiler automatically specifies the size by counting the number of elements
in the array (i.e. 5).
In the Java array, each memory location is associated with a number. The
number is known as an array index. We can also initialize arrays in Java,
using the index number. For example,
// declare an array
int[] age = new int[5];
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
..
Note:
Array indices always start from 0. That is, the first element of an array
is at index 0.
If the size of an array is n, then the last element of the array will be at
index n-1.
We can access the element of an array using the index number. Here is the
syntax for accessing elements of an array,
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5, 2, 5};
Output
Multi-Dimensional Array :
2-dimensional Array
Remember, Java uses zero-based indexing, that is, indexing of arrays in Java
starts with 0 and not 1.
Let's take another example of the multidimensional array. This time we will
be creating a 3-dimensional array. For example,
type String.
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
Java Programming
// create a 2d array
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
Output:
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
Java Programming
class MultidimensionalArray {
public static void main(String[] args) {
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
System.out.println(a[i][j]);
}
}
}
}
Output:
1
-2
3
-4
-5
6
9
7
class MultidimensionalArray {
public static void main(String[] args) {
// create a 2d array
int[][] a = {
{1, -2, 3},
{-4, -5, 6, 9},
{7},
};
-2
-4
-5
Let's see how we can use a 3d array in Java. We can initialize a 3d array
similar to the 2d array. For example,
// test is a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};
class ThreeArray {
public static void main(String[] args) {
// create a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{
{-4, -5, 6, 9},
{1},
{2, 3}
}
};
Java Programming
Output:
1
-2
3
2
3
4
-4
-5
6
9
1
2
3
Java Programming
Constructors
A constructor has the same name as that of the class and does not have
any return type.
For example,
class Topperworld {
Topperworld() {
// constructor body
Types of Constructor
In Java, constructors can be divided into 3 types:
Default Constructor
Parameterized Constructor
Java Programming
Default Constructor :
int a;
boolean b;
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Output:
Default Value:
a=0
b = false
Parameterized Constructor :
class Topperworld {
String languages;
Output:
Here, we are passing the single value to the constructor. Based on the
argument passed, the language variable is initialized inside the constructor.
Java Programming
results.
Object
Class
Abstraction
Inheritance
Polymorphism
Encapsulation
Java Programming
Object :
Any entity that has state and behavior is known as an
object. For example, a chair, pen, table, keyboard, bike, etc. It can be
physical or logical.
Class :
A class can also be defined as a blueprint from which you can create an
individual object. Class doesn't consume any space.
Inheritance :
class is derived from an existing class. The new class is called the
subclass, and the existing class is called the superclass. The subclass
Polymorphism :
Abstraction :
Abstraction means hiding the implementation
details of a class and exposing only the necessary details to the user. In
Java, abstraction can be achieved through abstract classes and interfaces.
Encapsulation :
Encapsulation means wrapping up the data
and methods into a single unit. In Java, encapsulation can be achieved
through access modifiers such as private, protected, and public.
These concepts are the pillars of OOP‟s in Java we will Discuss these
in Detail seperately.
Java Programming
An object is any entity that has a state and behavior. For example,
a bicycle is an object. It has
Java Class
Since many houses can be made from the same description, we can
create many objects from a class.
Java Programming
We can create a class in Java using the class keyword. For example,
class ClassName {
// fields
// methods
}
Here, fields (variables) and methods represent the state and behavior of
class Bicycle {
// state or field
private int gear = 5;
// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}
Java Object
We have used the new keyword along with the constructor of the class to
create an object. Constructors are similar to methods and have the same
name as the class. For example, Bicycle() is the constructor of
We can use the name of objects along with the . operator to access
class Bicycle {
// field of class
int gear = 5;
// method of class
void braking() {
...
}
}
// create object
Bicycle sportsBicycle = new Bicycle();
Here,
we have created an object of Bicycle named sportsBicycle. We then use
class Main {
public static void main(String[] args) {
Output:
output.
The variable isOn defined inside the class is also called an instance
variable. It is because when we create an object of the class, it is called an
instance of the class. And, each instance will have its own copy of the
variable.
That is, led and halogen objects will have their own copy of
the isOn variable.
Class Object
A class is a template for creating The object is an instance of a
You can create class using “class” You can create object using “new”
Inheritance in Java
class Animal {
// methods and fields
}
In the above example, the Dog class is created by inheriting the methods
Now, you are asked to build a scientific calculator, which does additional
operations like power, logarithms, trigonometric operations, etc., along
with standard operations. So, how would you go about writing this new
scientific calculator application?
Would you write the code for all standard operations, like addition,
subtraction, etc., again? No, you have already written that code. Right?
You would want to use it in this new application without writing it all over
again. Using inheritance in this case, you can achieve this objective. Let
us see how in the below section.
You will apply inheritance and inherit the standard calculator class, which
contains code for standard operations for the new scientific calculator
class. This new class now inherits all the calculator operations of the old
class. And you can now write methods for the additional operations in this
new class. This is the primary use case of inheritance in java.
Java Programming
Let us list out a few of the terms and keywords generally used in
inheritance.
Subclass: The class that inherits the attributes and methods of another
class.
Example :
class SuperClass {
void methodSuper() {
System.out.println("I am a super class method");
}
}
Output:
Java Programming
Explanation:
1. Single
2. Multilevel
3. Hierarchical
4. Multiple
5. Hybrid
Java Programming
Single Inheritance :
Output:
I am green!
I am a Bird
Java Programming
Here,
Multilevel Inheritance :
Output:
I can sing Opera!
I am green!
I am a Bird
Here,
Hierarchical Inheritance :
Output:
I am green!
I am a Bird
I am black!
I am a Bird
Here,
Multiple Inheritance :
class has a method testMethod(), which has the same name as class A.
Now, lets us suppose that classes A and B are both inherited by a
subclass named C. And if testMethod() is called from the subclass C, an
Ambiguity would arise as the same method is present in both the
superclasses.
Hybrid Inheritance :
Super Keyword
The super keyword is used to refer to the parent class of any class. This
keyword can be used to access the variables, methods, and constructors
of the parent class from the child class.
Let us explore the usage of the super keyword using the below examples.
void display() {
System.out.println("The var value of child: " +
var);
System.out.println("The var value of parent: " + super.var);
//using the super keyword will refer to parent class variables
}
}
class Main {
public static void main(String args[]) {
TestChildClass tcc = new TestChildClass();
tcc.display();
}
}
Output:
The var value of child: 50
The var value of parent: 100
Explanation:
Below is how access modifiers public, private, protected and default affect
the way the variables and methods of the parent class are inherited by
the child class.
Private:
Public:
Protected:
Default:
Polymorphism in Java
That is, the same entity (method or operator or object) can perform
different operations in different scenarios.
// renders Square
public void render() {
System.out.println("Rendering Square...");
}
}
// renders circle
public void render() {
System.out.println("Rendering Circle...");
Java Programming
}
}
class Main {
public static void main(String[] args) {
Output
Rendering Square...
Rendering Circle...
The main purpose of the render() method is to render the shape. However,
the process of rendering a square is different than the process of rendering
a circle.
Types of Polymorphism
Compile-time polymorphism
Run-time polymorphism
Java Programming
Compile-time Polymorphism :
Compile-time polymorphism in Java is
also called static polymorphism or static method dispatch. It can be
achieved by method overloading. In this process, an overloaded method is
resolved at compile time rather than resolving at runtime.
In a Java class, we can create methods with the same name if they differ
in parameters. For example,
This is known as method overloading in Java. Here, the same method will
perform different operations based on the parameter.
class Pattern {
class Main {
public static void main(String[] args) {
Java Programming
Output:
**********
##########
In the above example, we have created a class named Pattern. The class
Run-time Polymorphism :
Run-time polymorphism in Java is also
called Dynamic method dispatch. It can be achieved by method overriding.
In this process, Instead of resolving the overridden method at compile-
time, it is resolved at runtime.
If the same method is present in both the superclass and the subclass.
Then, the method in the subclass overrides the same method in the
superclass. This is called method overriding.
In this case, the same method will perform one operation in the superclass
and another operation in the subclass. For example,
class Language {
public void displayInfo() {
System.out.println("Common English Language");
}
}
class Main {
public static void main(String[] args) {
}
}
Output:
named Java.
Characteristics of Polymorphism :
Encapsulation in Java
The variables or fields can be accessed by methods of their class and can
be hidden from the other classes using private access modifiers. One
thing to note here is that data hiding and encapsulation may
sound the same but different.
Java Programming
class Perimeter {
class Main {
public static void main(String[] args) {
Output:
Perimeter of Rectangle : 18
In the Main class, the object of the Perimeter class is created and values
for length and breadth are passed. Further, the method getPerimeter() is
called and the calculated perimeter gets printed.
Why Encapsulation ?
class Person {
private int age;
this.age = age;
}
}
}
Here, we are making the age variable private and applying logic
And, they are kept hidden from outer classes. This is called data
hiding.
doesn‟t get any chance to change any specific variable or data and
hinder the running of the program.
Data Hiding
class Person {
// private field
private int age;
// getter method
public int getAge() {
return age;
}
// setter method
public void setAge(int age) {
this.age = age;
}
}
class Main {
public static void main(String[] args) {
}
}
Output
My age is 24
If we try to access the age field from the Main class, we will get an error.
Abstraction in Java
Java provides many in-built abstractions and few tools to create our own.
Abstract classes
Interfaces
An abstract class can have both the regular methods and abstract
methods. For example,
// abstract method
abstract void method1();
// regular method
void method2() {
System.out.println("This is regular method");
}
}
by ;.
For example,
// error
// class should be abstract
class Language {
// abstract method
abstract void method1();
Java Programming
The major advantage of hiding the working of the brake is that now
the manufacturer can implement brake differently for different
motorbikes, however, what brake does will be the same.
class Main {
public static void main(String[] args) {
MountainBike m1 = new MountainBike();
m1.brake();
SportsBike s1 = new SportsBike();
Java Programming
s1.brake();
}
}
Output:
MountainBike Brake
SportsBike Brake
method brake().
Advantage of Abstraction :
Disadvantage of Abstraction :
Interface in Java
In other words, you can say that interfaces can have abstract methods
and variables. It cannot have a method body.
interface Topperworld {
public void getType();
Here,
Topperworld is an interface.
There are mainly three reasons to use interface. They are given below.
Implementation of Interface
interface Topperworld {
void getArea(int length, int breadth);
}
class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.getArea(10, 5);
}
}
Output
Extending an Interface
Similar to classes, interfaces can extend other interfaces.
The extends keyword is used for extending interfaces.
For example,
interface Javatutorial {
// members of Java interface
}
// extending interface
interface Topperworld extends Javatutorial {
// members of Topperworld interface
// members of Javatutorial interface
}
interface A {
...
}
interface B {
...
}
Java Programming
interface C extends A, B {
...
}
This is used to solve the Diamond problem occur during the multiple
inheritance.
interface A {
// members of A
}
interface B {
// members of B
}
class C implements A, B {
// abstract members of A
// abstract members of B
}
Java Programming
Advantage of Interface
Here are some advantages of using Interfaces in Java:
without affecting the code that uses the class through its interface.
same interface.
maintainable code.
provide a clear and concise contract that other developers can use
CLASS INTERFACE